diff --git a/.gitignore b/.gitignore index 1006d42b46..b6c4278bba 100644 --- a/.gitignore +++ b/.gitignore @@ -34,51 +34,71 @@ log.html ScriptLog.txt data/scene/atmosphereearth/textures -data/scene/dawn/ceres/textures -data/scene/dawn/dawn/obj -data/scene/dawn/dawn/textures -data/scene/dawn/vestaprojection/textures -data/scene/dawn/vestaprojection/VestaComet data/scene/debugglobe/textures data/scene/earth/textures -data/scene/juno/juno/Juno.mtl -data/scene/juno/juno/Juno.obj -data/scene/juno/juno/spice -data/scene/juno/juno/textures data/scene/jupiter/callisto/textures data/scene/jupiter/europa/textures data/scene/jupiter/ganymede/textures data/scene/jupiter/io/textures data/scene/jupiter/jupiter/textures +data/scene/lodglobes/jupiter/callisto/textures +data/scene/lodglobes/earth/textures +data/scene/lodglobes/jupiter/europa/textures +data/scene/lodglobes/jupiter/ganymede/textures +data/scene/lodglobes/jupiter/io/textures +data/scene/lodglobes/jupiter/jupiter/textures +data/scene/lodglobes/mars/textures +data/scene/lodglobes/mercury/textures +data/scene/lodglobes/moon/textures +data/scene/lodglobes/neptune/textures +data/scene/lodglobes/saturn/textures +data/scene/lodglobes/uranus/textures +data/scene/lodglobes/venus/textures data/scene/mars/textures data/scene/mercury/textures data/scene/milkyway/textures data/scene/milkyway-eso/textures +data/scene/missions/dawn/ceres/textures +data/scene/missions/dawn/dawn/obj +data/scene/missions/dawn/dawn/textures +data/scene/missions/dawn/vestaprojection/textures +data/scene/missions/dawn/vestaprojection/VestaComet +data/scene/missions/juno/juno/Juno.mtl +data/scene/missions/juno/juno/Juno.obj +data/scene/missions/juno/juno/spice +data/scene/missions/juno/juno/textures +data/scene/missions/newhorizons/jupiter/callisto/textures +data/scene/missions/newhorizons/jupiter/europa/textures +data/scene/missions/newhorizons/jupiter/ganymede/textures +data/scene/missions/newhorizons/jupiter/io/textures +data/scene/missions/newhorizons/jupiter/jupiter/ProjectionsOfInterest +data/scene/missions/newhorizons/newhorizons/models +data/scene/missions/newhorizons/newhorizons/textures +data/scene/missions/newhorizons/pluto/charon/textures +data/scene/missions/newhorizons/pluto/pluto/assets +data/scene/missions/newhorizons/pluto/pluto/full_images +data/scene/missions/newhorizons/pluto/pluto/images +data/scene/missions/newhorizons/pluto/pluto/textures +data/scene/missions/osirisrex/bennu/models +data/scene/missions/osirisrex/bennu/textures +data/scene/missions/osirisrex/osirisrex/models +data/scene/missions/osirisrex/osirisrex/textures +data/scene/missions/rosetta/67P/obj +data/scene/missions/rosetta/67P/rosettaimages +data/scene/missions/rosetta/67P/textures +data/scene/missions/rosetta/rosetta/rosetta +data/scene/missions/rosetta/rosetta/textures data/scene/moon/textures data/scene/neptune/textures -data/scene/newhorizons/jupiter/callisto/textures -data/scene/newhorizons/jupiter/europa/textures -data/scene/newhorizons/jupiter/ganymede/textures -data/scene/newhorizons/jupiter/io/textures -data/scene/newhorizons/jupiter/jupiter/ProjectionsOfInterest -data/scene/newhorizons/newhorizons/models -data/scene/newhorizons/newhorizons/textures -data/scene/newhorizons/pluto/charon/textures -data/scene/newhorizons/pluto/pluto/assets -data/scene/newhorizons/pluto/pluto/full_images -data/scene/newhorizons/pluto/pluto/images -data/scene/newhorizons/pluto/pluto/textures -data/scene/osirisrex/bennu/models -data/scene/osirisrex/bennu/textures -data/scene/osirisrex/osirisrex/models -data/scene/osirisrex/osirisrex/textures data/scene/pluto/textures -data/scene/saturn/textures -data/scene/rosetta/67P/obj -data/scene/rosetta/67P/rosettaimages -data/scene/rosetta/67P/textures -data/scene/rosetta/rosetta/rosetta -data/scene/rosetta/rosetta/textures +data/scene/saturn/dione/textures +data/scene/saturn/enceladus/textures +data/scene/saturn/iapetus/textures +data/scene/saturn/mimas/textures +data/scene/saturn/rhea/textures +data/scene/saturn/saturn/textures +data/scene/saturn/tethys/textures +data/scene/saturn/titan/textures data/scene/stars/colorbv.cmap data/scene/stars/speck data/scene/stars/textures @@ -90,11 +110,12 @@ data/scene/uranus/textures data/scene/venus/textures data/scene/volumetricmilkyway/milkyway data/spice/DawnKernels -data/spice/jup260.bsp data/spice/de430_1850-2150.bsp +data/spice/jup260.bsp data/spice/MAR063.BSP data/spice/NewHorizonsKernels data/spice/nh_kernels data/spice/OsirisRexKernels +data/spice/plu055.bsp data/spice/Rosetta - +data/spice/sat375.bsp diff --git a/CREDITS b/CREDITS index 1190a23a66..3bb64218eb 100644 --- a/CREDITS +++ b/CREDITS @@ -2,14 +2,15 @@ Alexander Bock Joakim Kilby Emil Axelsson Jonathas Costa -Niclas Hultberg -Michael Nilsson -Sebastian Piwell -Kalle Bladin -Erik Broberg +Matthew Territo Jonas Strandstedt Hans-Christian Helltegen Michal Marcinkowski Anton Arbring Tomas Forsyth Rosin +Kalle Bladin +Erik Broberg +Michael Nilsson +Sebastian Piwell +Niclas Hultberg diff --git a/apps/Launcher/CMakeLists.txt b/apps/Launcher/CMakeLists.txt index 34affa1004..a17a8dbe36 100644 --- a/apps/Launcher/CMakeLists.txt +++ b/apps/Launcher/CMakeLists.txt @@ -74,4 +74,4 @@ endif () # Libtorrent include_external_library(${APPLICATION_NAME} libtorrent ${application_path}/ext/libtorrent) -target_include_directories(${APPLICATION_NAME} PUBLIC SYSTEM ${application_path}/ext/libtorrent/include) +target_include_directories(${APPLICATION_NAME} SYSTEM PUBLIC ${application_path}/ext/libtorrent/include) diff --git a/apps/Launcher/mainwindow.cpp b/apps/Launcher/mainwindow.cpp index ffe01f2cd7..502c97a400 100644 --- a/apps/Launcher/mainwindow.cpp +++ b/apps/Launcher/mainwindow.cpp @@ -62,7 +62,7 @@ namespace { class QLog : public ghoul::logging::Log { public: void log( - ghoul::logging::LogManager::LogLevel level, + ghoul::logging::LogLevel level, const std::string& category, const std::string& message ) { @@ -96,7 +96,7 @@ MainWindow::MainWindow() _informationWidget = new QTextEdit(this); _informationWidget->setReadOnly(true); - _informationWidget->setEnabled(false); + //_informationWidget->setEnabled(false); layout->addWidget(_informationWidget, 1, 0, 2, 1); layout->setRowStretch(1, 10); layout->setColumnStretch(0, 4); @@ -106,13 +106,13 @@ MainWindow::MainWindow() { QGridLayout* innerLayout = new QGridLayout; - QLabel* shortcutLabel = new QLabel("Keyboard Shortcuts:"); - innerLayout->addWidget(shortcutLabel, 0, 0); - QPushButton* shortcutButton = new QPushButton("Open..."); - QObject::connect(shortcutButton, SIGNAL(clicked(bool)), - this, SLOT(shortcutButtonPressed()) - ); - innerLayout->addWidget(shortcutButton, 0, 1); + //QLabel* shortcutLabel = new QLabel("Keyboard Shortcuts:"); + //innerLayout->addWidget(shortcutLabel, 0, 0); + //QPushButton* shortcutButton = new QPushButton("Open..."); + //QObject::connect(shortcutButton, SIGNAL(clicked(bool)), + // this, SLOT(shortcutButtonPressed()) + // ); + //innerLayout->addWidget(shortcutButton, 0, 1); innerLayout->setRowStretch(1, 10); @@ -189,7 +189,7 @@ void MainWindow::initialize() { _syncWidget->setWindowModality(Qt::WindowModal); _syncWidget->hide(); - ghoul::logging::LogManager::initialize(ghoul::logging::LogManager::LogLevel::Debug); + ghoul::logging::LogManager::initialize(ghoul::logging::LogLevel::Debug); LogMgr.addLog( std::make_unique< ghoul::logging::ConsoleLog >() ); // TODO: This can crash the system in cases where the logfile can't be created ---abock LogMgr.addLog( std::make_unique< ghoul::logging::HTMLLog >("LauncherLog.html", ghoul::logging::HTMLLog::Append::No) ); diff --git a/apps/Launcher/syncwidget.cpp b/apps/Launcher/syncwidget.cpp index cd57f204d2..1f4099ac4e 100644 --- a/apps/Launcher/syncwidget.cpp +++ b/apps/Launcher/syncwidget.cpp @@ -31,8 +31,9 @@ #include #include #include -#include +#include #include +#include #include #include diff --git a/apps/OpenSpace/main.cpp b/apps/OpenSpace/main.cpp index a84df70c2d..7273f41661 100644 --- a/apps/OpenSpace/main.cpp +++ b/apps/OpenSpace/main.cpp @@ -31,8 +31,13 @@ #include #include +#include + #include +#include +#include + sgct::Engine* _sgctEngine; void mainInitFunc(); @@ -169,7 +174,27 @@ int main(int argc, char** argv) { // Main loop LDEBUG("Starting rendering loop"); - _sgctEngine->render(); + try { + _sgctEngine->render(); + } + catch (const ghoul::RuntimeError& e) { + // Write out all of the information about the exception, flush the logs, and throw + LFATALC(e.component, e.message); + LogMgr.flushLogs(); + throw; + } + catch (const std::exception& e) { + // Write out all of the information about the exception, flush the logs, and throw + LFATALC("Exception", e.what()); + LogMgr.flushLogs(); + throw; + } + catch (...) { + // Write out all of the information about the exception, flush the logs, and throw + LFATALC("Exception", "Unknown exception"); + LogMgr.flushLogs(); + throw; + } //clear function bindings to avoid crash after destroying the OpenSpace Engine sgct::MessageHandler::instance()->setLogToCallback(false); diff --git a/data/scene/atmosphereearth.scene b/data/scene/atmosphereearth.scene index bc120bbd57..914c040ca7 100644 --- a/data/scene/atmosphereearth.scene +++ b/data/scene/atmosphereearth.scene @@ -10,7 +10,7 @@ function preInitialization() openspace.spice.loadKernel("${SPICE}/pck00010.tpc") openspace.time.setTime(openspace.time.currentWallTime()) - dofile(openspace.absPath('${SCRIPTS}/bind_keys.lua')) + dofile(openspace.absPath('${SCRIPTS}/bind_common_keys.lua')) end function postInitialization() diff --git a/data/scene/atmosphereearth/atmosphereearth.mod b/data/scene/atmosphereearth/atmosphereearth.mod index f54904ac1f..f5c98aaf3f 100644 --- a/data/scene/atmosphereearth/atmosphereearth.mod +++ b/data/scene/atmosphereearth/atmosphereearth.mod @@ -4,12 +4,14 @@ return { Name = "EarthBarycenter", Parent = "SolarSystemBarycenter", Static = true, - Ephemeris = { - Type = "Spice", - Body = "EARTH BARYCENTER", - Observer = "SUN", - Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" - }, + Transform = { + Translation = { + Type = "Spice", + Body = "EARTH BARYCENTER", + Observer = "SUN", + Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" + }, + } }, -- Earth module { @@ -18,7 +20,7 @@ return { Renderable = { Type = "RenderablePlanet", Frame = "IAU_EARTH", - Body = "EARTH", + Body = "EARTH", Geometry = { Type = "SimpleSphere", Radius = { 6.371, 6 }, @@ -41,7 +43,7 @@ return { Textures = { Type = "simple", Color = "textures/earth_bluemarble.jpg", - Night = "textures/earth_night.jpg", + Night = "textures/earth_night.jpg", --Height = "textures/earth_bluemarble_height.jpg", -- Depth = "textures/earth_depth.png", Reflectance = "textures/earth_reflectance.png", @@ -105,15 +107,20 @@ return { Name = "EarthTrail", Parent = "SolarSystemBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "EARTH", - Frame = "GALACTIC", - Observer = "SUN", - RGB = { 0.5, 0.8, 1.0}, - TropicalOrbitPeriod = 365.242, - EarthOrbitRatio = 1, - DayLength = 24 - } + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "EARTH", + Observer = "SUN" + }, + Color = { 0.5, 0.8, 1.0 }, + -- StartTime = "2016 JUN 01 12:00:00.000", + -- EndTime = "2017 JAN 01 12:00:00.000", + -- SampleInterval = 3600 + Period = 365.242, + Resolution = 1000 + }, + GuiName = "/Solar/EarthTrail" }, { Name = "EarthMarker", @@ -126,7 +133,7 @@ return { Texture = "textures/marker.png", BlendMode = "Additive" }, - Ephemeris = { + Ephemeris = { Type = "Static", Position = {0, 0, 0, 5} } diff --git a/data/scene/dawn.scene b/data/scene/dawn.scene index 74ad519767..6ae70e3fb9 100644 --- a/data/scene/dawn.scene +++ b/data/scene/dawn.scene @@ -10,7 +10,7 @@ function preInitialization() openspace.spice.loadKernel("${SPICE}/pck00010.tpc") openspace.time.setTime("2011 AUG 06 00:00:00") - dofile(openspace.absPath('${SCRIPTS}/bind_keys.lua')) + dofile(openspace.absPath('${SCRIPTS}/bind_common_keys.lua')) end function postInitialization() @@ -46,18 +46,14 @@ return { "venus", "earth", "mars", - "jupiter", - "saturn", + "jupiter/jupiter", + "saturn/saturn", "uranus", "neptune", "pluto", "stars", "milkyway", - "rosetta", - "67P", - "dawn", - "vestaprojection", - "ceres" + "missions/dawn" } } diff --git a/data/scene/debugglobe/debugglobe.mod b/data/scene/debugglobe/debugglobe.mod deleted file mode 100644 index 7f559dce3a..0000000000 --- a/data/scene/debugglobe/debugglobe.mod +++ /dev/null @@ -1,197 +0,0 @@ -return { - -- Earth barycenter module - { - Name = "EarthBarycenter", - Parent = "SolarSystemBarycenter", - Static = true, - Ephemeris = { - Type = "Spice", - Body = "EARTH BARYCENTER", - Observer = "SUN", - Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" - }, - }, - -- RenderableGlobe module - { - Name = "DebugGlobe", - Parent = "EarthBarycenter", - Renderable = { - Type = "RenderableGlobe", - Frame = "IAU_EARTH", - Body = "EARTH", - --Radii = {6378137.0, 6378137.0, 6356752.314245}, -- Earth's radii - --Radii = {1738100, 1738100, 1736000}, -- Moon's radii - Radii = {3396190.0, 3396190.0, 3376200.0}, -- Mars' radii - --Radii = {2439700.0, 2439700.0, 2439700.0}, - CameraMinHeight = 1000, - InteractionDepthBelowEllipsoid = 10000, -- Useful when having negative height map values - SegmentsPerPatch = 90, - TextureInitData = { - ColorTextureMinimumSize = 512, - OverlayMinimumSize = 512, - HeightMapMinimumSize = 64, - }, - Textures = { - ColorTextures = { - { - Type = "Temporal", - Name = "Temporal VIIRS SNPP", - FilePath = "map_service_configs/earth/Temporal_VIIRS_SNPP_CorrectedReflectance_TrueColor.xml", - }, - { - Type = "SingleImage", - Name = "Debug Tiles", - FilePath = "textures/test_tile.png", - }, - --[[{ - Type = "Temporal", - Name = "Temporal MODIS Aqua CorrectedRecflectance TrueColor", - FilePath = "map_service_configs/earth/Temporal_MODIS_Aqua_CorrectedReflectance_TrueColor.xml", - }, - { - Name = "MODIS_Terra_CorrectedReflectance_TrueColor", - FilePath = "map_service_configs/earth/MODIS_Terra_CorrectedReflectance_TrueColor.xml", - },]] - - { - Name = "ESRI Imagery World 2D", - FilePath = "map_service_configs/earth/ESRI_Imagery_World_2D.wms", - --Enabled = true, - }, - { - Name = "MARS_Viking_MDIM21", - FilePath = "map_service_configs/mars/MARS_Viking_MDIM21.xml", - Enabled = true, - }, - --[[ - { - Name = "Mars Viking Clr", - FilePath = "textures/Mars_Viking_ClrMosaic_global_925m_longlat_full.vrt", - Enabled = true, - }, - { - Name = "On Mercury Color", - FilePath = "map_service_configs/mercury/OnMercuryColor.xml", - }, - { - Name = "On Mercury Image", - FilePath = "map_service_configs/mercury/OnMercuryImage.xml", - }, - ]] - }, - GrayScaleOverlays = { - { - Name = "CTX Mosaic", - FilePath = "map_service_configs/mars/CTX_Mosaic.xml", - Enabled = false, - }, - - --[[ - { - Name = "On Moon Color", - FilePath = "map_service_configs/moon/OnMoonColor.xml", - --Enabled = true, - }]] - - }, - NightTextures = { - { - Name = "Earth at Night 2012", - FilePath = "map_service_configs/earth/VIIRS_CityLights_2012.xml", - }, - }, - WaterMasks = { - { - Name = "MODIS_Water_Mask", - FilePath = "map_service_configs/earth/MODIS_Water_Mask.xml", - }, - }, - Overlays = { - { - Name = "Coastlines", - FilePath = "map_service_configs/earth/Coastlines.xml", - }, - { - Name = "Reference_Features", - FilePath = "map_service_configs/earth/Reference_Features.xml", - }, - { - Name = "Reference_Labels", - FilePath = "map_service_configs/earth/Reference_Labels.xml", - }, - { - Type = "ChunkIndex", - Name = "Indices", - FilePath = "textures/test_tile.png", - }, - }, - HeightMaps = { - - { - Name = "Mola Elevation", - FilePath = "map_service_configs/mars/Mola_Elevation.xml", - Enabled = true, - }, - --[[ { - Name = "Terrain tileset", - FilePath = "map_service_configs/earth/TERRAIN.wms", - --Enabled = true, - }, - - { - Name = "On Moon Height", - FilePath = "map_service_configs/moon/OnMoonHeight.xml", - --Enabled = true, - },]] - { - Name = "On Mercury Height", - FilePath = "map_service_configs/mercury/OnMercuryElevationGaskell.xml", - }, - }, - HeightMapOverlays = { - --[[ - { - Name = "West_Candor_Chasma_DEM_longlat_global2", - FilePath = "map_datasets/West_Candor_Chasma_DEM_longlat_global.vrt", - Enabled = true, - }, - ]] - }, - }, - }, - Ephemeris = { - Type = "Spice", - Body = "EARTH", - Reference = "ECLIPJ2000", - Observer = "EARTH BARYCENTER", - Kernels = { - "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" - } - } - }, - -- EarthTrail module - { - Name = "EarthTrail", - Parent = "SolarSystemBarycenter", - Renderable = { - Type = "RenderableTrail", - Body = "EARTH", - Frame = "GALACTIC", - Observer = "SUN", - RGB = { 0.5, 0.8, 1.0}, - TropicalOrbitPeriod = 365.242, - EarthOrbitRatio = 1, - DayLength = 24 - } - } - --[[, - { - Name = "DebugPlane", - Parent = "DebugGlobe", - Renderable = { - Type = "RenderableDebugPlane", - Texture = 34, - Size = { 1, 7 } - } - }]] -} diff --git a/data/scene/debugglobe/map_service_configs/earth/TERRAIN.wms b/data/scene/debugglobe/map_service_configs/earth/TERRAIN.wms deleted file mode 100644 index 6782144c50..0000000000 --- a/data/scene/debugglobe/map_service_configs/earth/TERRAIN.wms +++ /dev/null @@ -1,13 +0,0 @@ - - - http://198.102.45.23/arcgis/rest/services/worldelevation3d/terrain3d? - GCS_Elevation - - - -180.0 - 90.0 - 180.0 - -90.0 - bottom - - diff --git a/data/scene/debugglobe/map_service_configs/earth/VIIRS_SNPP_CorrectedReflectance_TrueColor.xml b/data/scene/debugglobe/map_service_configs/earth/VIIRS_SNPP_CorrectedReflectance_TrueColor.xml deleted file mode 100644 index 881dce3e58..0000000000 --- a/data/scene/debugglobe/map_service_configs/earth/VIIRS_SNPP_CorrectedReflectance_TrueColor.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - http://map1.vis.earthdata.nasa.gov/wmts-geo/VIIRS_SNPP_CorrectedReflectance_TrueColor/default/2016-05-16/EPSG4326_250m/${z}/${y}/${x}.jpg - - - -180.0 - 90 - 396.0 - -198 - 8 - 2 - 1 - top - - EPSG:4326 - 512 - 512 - 3 - \ No newline at end of file diff --git a/data/scene/debugglobe/map_service_configs/mars/MARS_Viking_MDIM21.xml b/data/scene/debugglobe/map_service_configs/mars/MARS_Viking_MDIM21.xml deleted file mode 100644 index f4952b7ed1..0000000000 --- a/data/scene/debugglobe/map_service_configs/mars/MARS_Viking_MDIM21.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - http://dzw9r5p966egh.cloudfront.net/catalog/Mars_Viking_MDIM21_ClrMosaic_global_232m/1.0.0//default/default028mm/${z}/${y}/${x}.jpg - - - -180.0 - 90 - 180.0 - -90 - 8 - 2 - 1 - top - - 256 - 256 - 3 - \ No newline at end of file diff --git a/data/scene/debugglobe/textures/ToastMapOfEarth.jpg b/data/scene/debugglobe/textures/ToastMapOfEarth.jpg deleted file mode 100644 index 9064235622..0000000000 Binary files a/data/scene/debugglobe/textures/ToastMapOfEarth.jpg and /dev/null differ diff --git a/data/scene/debugglobe/textures/earth_bluemarble.jpg b/data/scene/debugglobe/textures/earth_bluemarble.jpg deleted file mode 100644 index 55b715d061..0000000000 Binary files a/data/scene/debugglobe/textures/earth_bluemarble.jpg and /dev/null differ diff --git a/data/scene/debugglobe/textures/earth_bluemarble_height.jpg b/data/scene/debugglobe/textures/earth_bluemarble_height.jpg deleted file mode 100644 index 6658823163..0000000000 Binary files a/data/scene/debugglobe/textures/earth_bluemarble_height.jpg and /dev/null differ diff --git a/data/scene/debugglobe/textures/earth_night.jpg b/data/scene/debugglobe/textures/earth_night.jpg deleted file mode 100644 index bf1a1a483c..0000000000 Binary files a/data/scene/debugglobe/textures/earth_night.jpg and /dev/null differ diff --git a/data/scene/debugglobe/textures/marker.png b/data/scene/debugglobe/textures/marker.png deleted file mode 100644 index fc42c047b8..0000000000 Binary files a/data/scene/debugglobe/textures/marker.png and /dev/null differ diff --git a/data/scene/debugglobe/textures/test_tile.png b/data/scene/debugglobe/textures/test_tile.png deleted file mode 100644 index cb16c0952f..0000000000 Binary files a/data/scene/debugglobe/textures/test_tile.png and /dev/null differ diff --git a/data/scene/debugglobe/textures/test_tile511x511.png b/data/scene/debugglobe/textures/test_tile511x511.png deleted file mode 100644 index 07e5d7888d..0000000000 Binary files a/data/scene/debugglobe/textures/test_tile511x511.png and /dev/null differ diff --git a/data/scene/debugglobe/textures/test_tile512x511.png b/data/scene/debugglobe/textures/test_tile512x511.png deleted file mode 100644 index b3e775581e..0000000000 Binary files a/data/scene/debugglobe/textures/test_tile512x511.png and /dev/null differ diff --git a/data/scene/debugglobe/textures/test_tile727x728.png b/data/scene/debugglobe/textures/test_tile727x728.png deleted file mode 100644 index 20a517915f..0000000000 Binary files a/data/scene/debugglobe/textures/test_tile727x728.png and /dev/null differ diff --git a/data/scene/debugglobe/textures/test_tile728x727.png b/data/scene/debugglobe/textures/test_tile728x727.png deleted file mode 100644 index ca02a942f1..0000000000 Binary files a/data/scene/debugglobe/textures/test_tile728x727.png and /dev/null differ diff --git a/data/scene/debugmodel.scene b/data/scene/debugmodel.scene deleted file mode 100644 index c53596b87e..0000000000 --- a/data/scene/debugmodel.scene +++ /dev/null @@ -1,53 +0,0 @@ --- TextureResolution = "low" -TextureResolution = "med" --- TextureResolution = "high" - -function preInitialization() - --[[ - The scripts in this function are executed after the scene is loaded but before the - scene elements have been initialized, thus they should be used to set the time at - which the scene should start and other settings that might determine initialization - critical objects. - ]]-- - - dofile(openspace.absPath('${SCRIPTS}/bind_keys.lua')) - - openspace.spice.loadKernel("${SPICE}/naif0011.tls") - openspace.spice.loadKernel("${SPICE}/pck00010.tpc") - - openspace.time.setTime("2018-10-25T04:00:00.00") - openspace.time.setDeltaTime(0) -end - -function postInitialization() - --[[ - The scripts in this function are executed after all objects in the scene have been - created and initialized, but before the first render call. This is the place to set - graphical settings for the renderables. - ]]-- - openspace.printInfo("Setting default values") - - openspace.setPropertyValue("Sun.renderable.enabled", false) - openspace.setPropertyValue("SunGlare.renderable.enabled", false) - openspace.setPropertyValue("SunMarker.renderable.enabled", false) - - openspace.printInfo("Done setting default values") - - openspace.resetCameraDirection() -end - -return { - ScenePath = ".", - CommonFolder = "common", - Camera = { - Focus = "DebugModel", - Position = {292946.630948, 377755.961928, 366248.427057}, - Rotation = {0.732615, -0.137003, 0.430036, 0.509485}, - }, - Modules = { - "sun", - "stars", - "debugmodel", - } -} - diff --git a/data/scene/default-moon.scene b/data/scene/default-moon.scene deleted file mode 100644 index 90748de3bf..0000000000 --- a/data/scene/default-moon.scene +++ /dev/null @@ -1,93 +0,0 @@ -function preInitialization() - --[[ - The scripts in this function are executed after the scene is loaded but before the - scene elements have been initialized, thus they should be used to set the time at - which the scene should start and other settings that might determine initialization - critical objects. - ]]-- - - --YYYY-MM-DDTHH:MN:SS - --openspace.time.setTime(openspace.time.currentWallTime()) - --[[ - -- March 9, 2016 total eclipse times from land - -- Palembang, South Sumatra, Indonesia - -- Partial solar eclipse begins: 6:20 a.m. local Western Indonesian Time - -- Total solar eclipse begins: 7:20 a.m. local time - -- Maximum eclipse: 7:21 a.m. local time - -- Total solar eclipse ends: 7:22 a.m. local time - -- Partial solar eclipse ends: 8:31 a.m. local time - - -- 6:20 -> 23:20 day before in UTC - ]]-- - openspace.spice.loadKernel("${SPICE}/naif0011.tls") - openspace.spice.loadKernel("${SPICE}/pck00010.tpc") - - openspace.time.setTime("2016-03-08T22:45:00") - - - -- Total Lunar Eclipse Jan 31, 2018 at 10:51:13 UTC - -- Regions seeing, at least, some parts of the eclipse: North/East Europe, - -- Asia, Australia, North/East Africa, North America, North/East South America, - -- Pacific, Atlantic, Indian Ocean, Arctic, Antarctica. - --openspace.time.setTime("2018-01-31T10:30:00") - - --openspace.time.setDeltaTime(200.0) - dofile(openspace.absPath('${SCRIPTS}/bind_keys.lua')) -end - -function postInitialization() - --[[ - The scripts in this function are executed after all objects in the scene have been - created and initialized, but before the first render call. This is the place to set - graphical settings for the renderables. - ]]-- - openspace.printInfo("Setting default values") - openspace.setPropertyValue("Sun.renderable.enabled", false) - openspace.setPropertyValue("SunMarker.renderable.enabled", false) - openspace.setPropertyValue("EarthMarker.renderable.enabled", false) - --openspace.setPropertyValue("Constellation Bounds.renderable.enabled", false) - openspace.setPropertyValue("PlutoTrail.renderable.enabled", false) - openspace.setPropertyValue("PlutoTexture.renderable.enabled", false) - - openspace.setPropertyValue("MilkyWay.renderable.transparency", 0.55) - openspace.setPropertyValue("MilkyWay.renderable.segments", 50) - - openspace.printInfo("Done setting default values") -end - -return { - ScenePath = ".", - CommonFolder = "common", - Camera = { - Focus = "Earth", - --Focus = "Moon", - Position = {526781518487.171326, 257168309890.072144, -1381125204152.817383}, - Rotation = {-0.106166, 0.981574, -0.084545, 0.134513}, - }, - Modules = { - "sun", - "mercury", - "venus", - "earth", - "moon", - "mars", - --"jupiter", - "saturn", - "uranus", - "neptune", - "stars", - -- "stars-denver", - "milkyway", - -- "milkyway-eso", - --"constellationbounds", - -- "fieldlines", - --"io", - --"europa", - --"ganymede", - --"callisto", - --"gridGalactic", - --"gridEcliptic", - --"gridEquatorial", - } -} - diff --git a/data/scene/default.scene b/data/scene/default.scene index 9dc1e2802d..d2344f3ab0 100644 --- a/data/scene/default.scene +++ b/data/scene/default.scene @@ -10,7 +10,7 @@ function preInitialization() openspace.spice.loadKernel("${SPICE}/pck00010.tpc") openspace.time.setTime(openspace.time.currentWallTime()) - dofile(openspace.absPath('${SCRIPTS}/bind_keys.lua')) + dofile(openspace.absPath('${SCRIPTS}/bind_common_keys.lua')) end @@ -21,8 +21,6 @@ function postInitialization() graphical settings for the renderables. ]]-- openspace.printInfo("Setting default values") - openspace.setPropertyValue("Sun.renderable.enab`led", true) - openspace.setPropertyValue("SunGlare.renderable.enabled", false) openspace.setPropertyValue("SunMarker.renderable.enabled", false) openspace.setPropertyValue("EarthMarker.renderable.enabled", false) openspace.setPropertyValue("Constellation Bounds.renderable.enabled", false) @@ -33,20 +31,6 @@ function postInitialization() openspace.resetCameraDirection() openspace.printInfo("Done setting default values") - - if openspace.modules.isLoaded("ISWA") then - - openspace.iswa.addCdfFiles("${OPENSPACE_DATA}/cdflist.json"); - - --openspace.iswa.addCygnet(7); - - --openspace.iswa.addCygnet(-4,"Data","Gm"); - --openspace.iswa.addCygnet(-5,"Data","Gm"); - --openspace.iswa.addCygnet(-6,"Data","Gm"); - --openspace.iswa.addCygnet(-7,"Data","Gm"); - --openspace.iswa.addCygnet(-8,"Data","Gm"); - --openspace.iswa.addCygnet(-9,"Data","Gm"); - end end @@ -55,8 +39,8 @@ return { CommonFolder = "common", Camera = { Focus = "Earth", - Position = {526781518487.171326, 257168309890.072144, -1381125204152.817383}, - Rotation = {-0.106166, 0.981574, -0.084545, 0.134513}, + Position = {505370268486.696167, 1089706179272.719116, -890259148524.319458}, + Rotation = {0.250635, -0.028751, 0.879269, 0.404030}, }, Modules = { "sun", diff --git a/data/scene/earth/earth.mod b/data/scene/earth/earth.mod index cda7130a76..78b3a3bb90 100644 --- a/data/scene/earth/earth.mod +++ b/data/scene/earth/earth.mod @@ -3,6 +3,26 @@ return { { Name = "EarthBarycenter", Parent = "SolarSystemBarycenter", + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "EARTH", + Observer = "SUN", + Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" + } + } + }, + { + -- The default reference frame for Earth-orbiting satellites + Name = "EarthInertial", + Parent = "EarthBarycenter", + Transform = { + Rotation = { + Type = "SpiceRotation", + SourceFrame = "J2000", + DestinationFrame = "GALACTIC", + } + }, }, -- Earth module { @@ -30,12 +50,6 @@ return { } }, Transform = { - Translation = { - Type = "SpiceEphemeris", - Body = "EARTH", - Observer = "SUN", - Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" - }, Rotation = { Type = "SpiceRotation", SourceFrame = "IAU_EARTH", @@ -51,16 +65,20 @@ return { -- EarthTrail module { Name = "EarthTrail", - Parent = "EarthBarycenter", + Parent = "SolarSystemBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "EARTH", - Frame = "GALACTIC", - Observer = "SUN", - RGB = { 0.5, 0.8, 1.0}, - TropicalOrbitPeriod = 365.242, - EarthOrbitRatio = 1, - DayLength = 24 + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "EARTH", + Observer = "SUN" + }, + Color = { 0.5, 0.8, 1.0 }, + -- StartTime = "2016 JUN 01 12:00:00.000", + -- EndTime = "2017 JAN 01 12:00:00.000", + -- SampleInterval = 3600 + Period = 365.242, + Resolution = 1000 }, GuiName = "/Solar/EarthTrail" }, @@ -76,7 +94,7 @@ return { Texture = "textures/marker.png", BlendMode = "Additive" }, - Ephemeris = { + Ephemeris = { Type = "Static", Position = {0, 0, 0, 5} } diff --git a/data/scene/fieldlines.scene b/data/scene/fieldlines.scene index 43068d7b75..3cee4bf1e3 100644 --- a/data/scene/fieldlines.scene +++ b/data/scene/fieldlines.scene @@ -10,7 +10,7 @@ function preInitialization() openspace.spice.loadKernel("${SPICE}/pck00010.tpc") openspace.time.setTime("2015 JAN 01 12:00:00.000") - dofile(openspace.absPath('${SCRIPTS}/bind_keys.lua')) + dofile(openspace.absPath('${SCRIPTS}/bind_common_keys.lua')) end function postInitialization() diff --git a/data/scene/globebrowsing-debug.scene b/data/scene/globebrowsing-debug.scene deleted file mode 100644 index ef64c4ef0d..0000000000 --- a/data/scene/globebrowsing-debug.scene +++ /dev/null @@ -1,46 +0,0 @@ -function preInitialization() - --[[ - The scripts in this function are executed after the scene is loaded but before the - scene elements have been initialized, thus they should be used to set the time at - which the scene should start and other settings that might determine initialization - critical objects. - ]]-- - - --openspace.time.setTime(openspace.time.currentWallTime()) - openspace.spice.loadKernel("${SPICE}/naif0011.tls") - openspace.spice.loadKernel("${SPICE}/pck00010.tpc") - - openspace.time.setTime("2015 NOV 24 00:00:00") - - - dofile(openspace.absPath('${SCRIPTS}/bind_keys.lua')) -end - -function postInitialization() - openspace.printInfo("Setting default values") - - openspace.setInteractionMode('GlobeBrowsing') - - openspace.time.setDeltaTime(0) - openspace.restoreCameraStateFromFile("debugstart.view") - openspace.resetCameraDirection() - openspace.gui.show() - - openspace.printInfo("Done setting default values") -end - - -return { - ScenePath = ".", - CommonFolder = "common", - Camera = { - Focus = "DebugGlobe", - Position = {3428016.852415, 616607.056698, 60430.587719}, - Rotation = {0.178551, -0.280661, 0.916566, 0.221935}, - }, - - Modules = { - "debugglobe" - } -} - diff --git a/data/scene/globebrowsing.scene b/data/scene/globebrowsing.scene index f1d2bc3e15..c03c92d1b7 100644 --- a/data/scene/globebrowsing.scene +++ b/data/scene/globebrowsing.scene @@ -10,17 +10,61 @@ function preInitialization() openspace.spice.loadKernel("${SPICE}/naif0011.tls") openspace.spice.loadKernel("${SPICE}/pck00010.tpc") - openspace.time.setTime("2015 NOV 24 00:00:00") - openspace.time.setTime(openspace.time.currentWallTime()) - dofile(openspace.absPath('${SCRIPTS}/bind_keys.lua')) + dofile(openspace.absPath('${SCRIPTS}/bind_common_keys.lua')) + + + -- Toggle night texture, shading, atmosphere and water + openspace.bindKey("s", + helper.property.invert('Earth.RenderableGlobe.Layers.NightLayers.Earth at Night 2012.enabled') .. + helper.property.invert('Earth.RenderableGlobe.performShading') .. + helper.property.invert('Earth.RenderableGlobe.atmosphere') .. + helper.property.invert('Earth.RenderableGlobe.Layers.WaterMasks.MODIS_Water_Mask.enabled'), + "Toggle night texture, shading, atmosphere, and water for Earth." + ) + + -- Toggle background + openspace.bindKey("b", + helper.property.invert('MilkyWay.renderable.enabled') .. + helper.property.invert('Stars.renderable.enabled'), + "Toggle background (Stars and Milkyway)." + ) + + openspace.bindKey("g", + "openspace.setInteractionMode('GlobeBrowsing')" .. + helper.property.invert('MilkyWay.renderable.enabled') .. + helper.property.invert('Stars.renderable.enabled') .. + helper.property.invert('Earth.RenderableGlobe.Layers.NightLayers.Earth at Night 2012.enabled') .. + helper.property.invert('Earth.RenderableGlobe.performShading') .. + helper.property.invert('Mars.RenderableGlobe.performShading') .. + helper.property.invert('Earth.RenderableGlobe.atmosphere') .. + helper.property.invert('Earth.RenderableGlobe.Layers.WaterMasks.MODIS_Water_Mask.enabled') .. + helper.property.invert('Moon.RenderableGlobe.enabled') .. + helper.property.invert('Sun.renderable.enabled'), + "Toogles background and shading mode on the Earth and Mars alongside visibility of the Moon and the Sun" + ) + + openspace.bindKey("h", + "openspace.setPropertyValue('*Trail.renderable.enabled', false)", + "Disables visibility of the trails" + ) + + --[[ + -- Toggle trails + openspace.bindKey("o", + 'openspace.setPropertyValue("*Trail.renderable.enabled", false)' + ) + openspace.bindKey("p", + 'openspace.setPropertyValue("*Trail.renderable.enabled", true)' + ) + +]] end function postInitialization() openspace.printInfo("Setting default values") openspace.setInteractionMode('GlobeBrowsing') - --openspace.restoreCameraStateFromFile("camera_lookat_planet.lua") openspace.setPropertyValue("MilkyWay.renderable.transparency", 0.55) openspace.setPropertyValue("MilkyWay.renderable.segments", 50) @@ -29,9 +73,11 @@ function postInitialization() openspace.setPropertyValue("SunGlare.renderable.enabled", false) openspace.setPropertyValue("SunMarker.renderable.enabled", false) + openspace.setPropertyValue("Earth.RenderableGlobe.atmosphere", true) + openspace.setPropertyValue("Earth.RenderableGlobe.Layers.NightLayers.Earth at Night 2012.settings.gamma", 1.8) + openspace.setPropertyValue("Earth.RenderableGlobe.Layers.NightLayers.Earth at Night 2012.settings.multiplier", 10) openspace.resetCameraDirection() - openspace.time.setDeltaTime(0) openspace.printInfo("Done setting default values") end @@ -41,19 +87,16 @@ return { ScenePath = ".", CommonFolder = "common", Camera = { - Focus = "Mars", + Focus = "Earth", Position = {138530625167.228241, 42217005217.825005, -46336405755.934372}, Rotation = {0.633883, 0.492158, -0.123913, -0.583625}, }, Modules = { - "lodearth", - "lodmoon", - "lodmars", - "lodmercury", + "lodglobes", "sun", "stars", - "milkyway", + "milkyway", } } diff --git a/data/scene/juno.scene b/data/scene/juno.scene index 346b872c2d..f63276e744 100755 --- a/data/scene/juno.scene +++ b/data/scene/juno.scene @@ -9,7 +9,6 @@ function preInitialization() openspace.spice.loadKernel("${SPICE}/pck00010.tpc") openspace.time.setTime("2016-07-05T10:05:00.00") - openspace.time.setDeltaTime(0) dofile(openspace.absPath('${SCRIPTS}/common.lua')) openspace.clearKeys() @@ -18,8 +17,6 @@ function preInitialization() 1, 5, 10, 20, 40, 90, 360, 720, 2880, 14400, 28800, 57600, 115200, 230400, 460800, 921600, 1843200, 3686400, 7372800, 14745600 }) - - openspace.bindKey("F6", "openspace.setPropertyValue('Interaction.coordinateSystem', 'Jupiter');"); end function postInitialization() @@ -55,12 +52,12 @@ return { "earth", "mars", "jupiter", - "saturn", + "saturn/saturn", "uranus", "neptune", "stars", "milkyway", - "juno" + "missions/juno" } } diff --git a/data/scene/jupiter/callisto/callisto.mod b/data/scene/jupiter/callisto/callisto.mod index 1af5b70f73..74c3360adf 100644 --- a/data/scene/jupiter/callisto/callisto.mod +++ b/data/scene/jupiter/callisto/callisto.mod @@ -24,7 +24,7 @@ return { }, Transform = { Translation = { - Type = "SpiceEphemeris", + Type = "SpiceTranslation", Body = "CALLISTO", Observer = "JUPITER BARYCENTER", Kernels = "${OPENSPACE_DATA}/spice/jup260.bsp" @@ -45,19 +45,15 @@ return { Name = "CallistoTrail", Parent = "JupiterBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "CALLISTO", - Frame = "GALACTIC", - Observer = "JUPITER BARYCENTER", - RGB = { 0.4, 0.3, 0.01 }, - TropicalOrbitPeriod = 60 , - EarthOrbitRatio = 0.045, - DayLength = 9.9259, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "CALLISTO", + Observer = "JUPITER BARYCENTER", + }, + Color = { 0.4, 0.3, 0.01 }, + Period = 17, + Resolution = 1000 } } } diff --git a/data/scene/jupiter/europa/europa.mod b/data/scene/jupiter/europa/europa.mod index 44c2ded0a5..54df372720 100644 --- a/data/scene/jupiter/europa/europa.mod +++ b/data/scene/jupiter/europa/europa.mod @@ -24,7 +24,7 @@ return { }, Transform = { Translation = { - Type = "SpiceEphemeris", + Type = "SpiceTranslation", Body = "EUROPA", Observer = "JUPITER BARYCENTER", Kernels = "${OPENSPACE_DATA}/spice/jup260.bsp" @@ -33,11 +33,7 @@ return { Type = "SpiceRotation", SourceFrame = "IAU_EUROPA", DestinationFrame = "IAU_JUPITER", - }, - Scale = { - Type = "StaticScale", - Scale = 1, - }, + } } }, -- EuropaTrail module @@ -45,19 +41,15 @@ return { Name = "EuropaTrail", Parent = "JupiterBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "EUROPA", - Frame = "GALACTIC", - Observer = "JUPITER BARYCENTER", - RGB = { 0.5, 0.3, 0.3 }, - TropicalOrbitPeriod = 60, - EarthOrbitRatio = 0.01, - DayLength = 9.9259, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "EUROPA", + Observer = "JUPITER BARYCENTER", + }, + Color = { 0.5, 0.3, 0.3 }, + Period = 85 / 24, + Resolution = 1000 } } } diff --git a/data/scene/jupiter/ganymede/ganymede.mod b/data/scene/jupiter/ganymede/ganymede.mod index c31809f2be..c2c9fdca08 100644 --- a/data/scene/jupiter/ganymede/ganymede.mod +++ b/data/scene/jupiter/ganymede/ganymede.mod @@ -24,7 +24,7 @@ return { }, Transform = { Translation = { - Type = "SpiceEphemeris", + Type = "SpiceTranslation", Body = "GANYMEDE", Observer = "JUPITER BARYCENTER", Kernels = "${OPENSPACE_DATA}/spice/jup260.bsp" @@ -45,19 +45,15 @@ return { Name = "GanymedeTrail", Parent = "JupiterBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "GANYMEDE", - Frame = "GALACTIC", - Observer = "JUPITER BARYCENTER", - RGB = { 0.4, 0.3, 0.3 }, - TropicalOrbitPeriod = 60 , - EarthOrbitRatio = 0.019, - DayLength = 9.9259, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "GANYMEDE", + Observer = "JUPITER BARYCENTER", + }, + Color = { 0.4, 0.3, 0.3 }, + Period = 172 / 24, + Resolution = 1000 } } } diff --git a/data/scene/jupiter/io/io.mod b/data/scene/jupiter/io/io.mod index ba04eb8c6d..03d28e60d1 100644 --- a/data/scene/jupiter/io/io.mod +++ b/data/scene/jupiter/io/io.mod @@ -24,7 +24,7 @@ return { }, Transform = { Translation = { - Type = "SpiceEphemeris", + Type = "SpiceTranslation", Body = "IO", Observer = "JUPITER BARYCENTER", Kernels = "${OPENSPACE_DATA}/spice/jup260.bsp" @@ -45,19 +45,15 @@ return { Name = "IoTrail", Parent = "JupiterBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "IO", - Frame = "GALACTIC", - Observer = "JUPITER BARYCENTER", - RGB = { 0.4, 0.4, 0.2 }, - TropicalOrbitPeriod = 40 , - EarthOrbitRatio = 0.0045, - DayLength = 9.9259, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "IO", + Observer = "JUPITER BARYCENTER", + }, + Color = { 0.4, 0.4, 0.2 }, + Period = 42 / 24, + Resolution = 1000 } } } diff --git a/data/scene/newhorizons/newhorizons/jup260.bsp.torrent b/data/scene/jupiter/jupiter/jup260.bsp.torrent similarity index 100% rename from data/scene/newhorizons/newhorizons/jup260.bsp.torrent rename to data/scene/jupiter/jupiter/jup260.bsp.torrent diff --git a/data/scene/jupiter/jupiter/jupiter.data b/data/scene/jupiter/jupiter/jupiter.data index 34dcaf0900..b22e81119b 100644 --- a/data/scene/jupiter/jupiter/jupiter.data +++ b/data/scene/jupiter/jupiter/jupiter.data @@ -2,4 +2,7 @@ return { FileRequest = { { Identifier = "jupiter_textures", Destination = "textures", Version = 1 } }, + TorrentFiles = { + { File = "jup260.bsp.torrent", Destination = "${SPICE}" }, + } } \ No newline at end of file diff --git a/data/scene/jupiter/jupiter/jupiter.mod b/data/scene/jupiter/jupiter/jupiter.mod index 6d51c47314..6302b66739 100644 --- a/data/scene/jupiter/jupiter/jupiter.mod +++ b/data/scene/jupiter/jupiter/jupiter.mod @@ -5,7 +5,7 @@ return { Parent = "SolarSystemBarycenter", Transform = { Translation = { - Type = "SpiceEphemeris", + Type = "SpiceTranslation", Body = "JUPITER BARYCENTER", Observer = "SUN", Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" @@ -37,7 +37,7 @@ return { }, Transform = { Translation = { - Type = "StaticEphemeris", + Type = "StaticTranslation", Position = {0, 0, 0}, -- jupiter is at its barycenter }, Rotation = { @@ -56,19 +56,15 @@ return { Name = "JupiterTrail", Parent = "SolarSystemBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "JUPITER BARYCENTER", - Frame = "GALACTIC", - Observer = "SUN", - RGB = { 0.8, 0.7, 0.7 }, - TropicalOrbitPeriod = 4330.595 , - EarthOrbitRatio = 11.857, - DayLength = 9.9259, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "JUPITER BARYCENTER", + Observer = "SUN", + }, + Color = { 0.8, 0.7, 0.7 }, + Period = 4330.595, + Resolution = 1000 } } } diff --git a/data/scene/lodearth/map_service_configs/ESRI/ESRI_Imagery_World_2D.wms b/data/scene/lodearth/map_service_configs/ESRI/ESRI_Imagery_World_2D.wms deleted file mode 100644 index ef90f48509..0000000000 --- a/data/scene/lodearth/map_service_configs/ESRI/ESRI_Imagery_World_2D.wms +++ /dev/null @@ -1,24 +0,0 @@ - - - http://services.arcgisonline.com/ArcGIS/rest/services/ESRI_Imagery_World_2D/MapServer/tile/${z}/${y}/${x} - - - 15 - 2 - 1 - top - - EPSG:4326 - 512 - 512 - 3 - 5 - - \ No newline at end of file diff --git a/data/scene/lodearth/map_service_configs/GIBS/Coastlines.xml b/data/scene/lodearth/map_service_configs/GIBS/Coastlines.xml deleted file mode 100644 index c9578ad205..0000000000 --- a/data/scene/lodearth/map_service_configs/GIBS/Coastlines.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - http://map1.vis.earthdata.nasa.gov/wmts-geo/Coastlines/default/2013-08-21/EPSG4326_250m/${z}/${y}/${x}.png - - - -180.0 - 90 - 396.0 - -198 - 9 - 2 - 1 - top - - EPSG:4326 - 512 - 512 - 4 - \ No newline at end of file diff --git a/data/scene/lodearth/map_service_configs/GIBS/GIBS_Aqua_MODIS_true.xml b/data/scene/lodearth/map_service_configs/GIBS/GIBS_Aqua_MODIS_true.xml deleted file mode 100644 index 8d3196deff..0000000000 --- a/data/scene/lodearth/map_service_configs/GIBS/GIBS_Aqua_MODIS_true.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - http://map1.vis.earthdata.nasa.gov/wmts-geo/MODIS_Aqua_CorrectedReflectance_TrueColor/default/2013-08-21/EPSG4326_250m/${z}/${y}/${x}.jpg - - - -180.0 - 90 - 396.0 - -198 - 8 - 2 - 1 - top - - EPSG:4326 - 512 - 512 - 3 - \ No newline at end of file diff --git a/data/scene/lodearth/map_service_configs/GIBS/MODIS_Terra_Brightness_Temp_Band31_Day.xml b/data/scene/lodearth/map_service_configs/GIBS/MODIS_Terra_Brightness_Temp_Band31_Day.xml deleted file mode 100644 index c63f815618..0000000000 --- a/data/scene/lodearth/map_service_configs/GIBS/MODIS_Terra_Brightness_Temp_Band31_Day.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - http://map1.vis.earthdata.nasa.gov/wmts-geo/MODIS_Terra_Brightness_Temp_Band31_Day/default/2013-08-21/EPSG4326_1km/${z}/${y}/${x}.png - - - -180.0 - 90 - 396.0 - -198 - 8 - 2 - 1 - top - - EPSG:4326 - 512 - 512 - 4 - \ No newline at end of file diff --git a/data/scene/lodearth/map_service_configs/GIBS/MODIS_Terra_CorrectedReflectance_TrueColor.xml b/data/scene/lodearth/map_service_configs/GIBS/MODIS_Terra_CorrectedReflectance_TrueColor.xml deleted file mode 100644 index faf07ccced..0000000000 --- a/data/scene/lodearth/map_service_configs/GIBS/MODIS_Terra_CorrectedReflectance_TrueColor.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - http://map1.vis.earthdata.nasa.gov/wmts-geo/MODIS_Terra_CorrectedReflectance_TrueColor/default/2016-05-16/EPSG4326_250m/${z}/${y}/${x}.jpg - - - -180.0 - 90 - 396.0 - -198 - 8 - 2 - 1 - top - - EPSG:4326 - 512 - 512 - 3 - \ No newline at end of file diff --git a/data/scene/lodearth/map_service_configs/GIBS/MODIS_Terra_CorrectedReflectance_TrueColor_temporal.xml b/data/scene/lodearth/map_service_configs/GIBS/MODIS_Terra_CorrectedReflectance_TrueColor_temporal.xml deleted file mode 100644 index 36013e4a3a..0000000000 --- a/data/scene/lodearth/map_service_configs/GIBS/MODIS_Terra_CorrectedReflectance_TrueColor_temporal.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - http://map1.vis.earthdata.nasa.gov/wmts-geo/MODIS_Terra_CorrectedReflectance_TrueColor/default/${t}/EPSG4326_250m/${z}/${y}/${x}.jpg - - - -180.0 - 90 - 396.0 - -198 - 8 - 2 - 1 - top - - EPSG:4326 - 512 - 512 - 3 - \ No newline at end of file diff --git a/data/scene/lodearth/map_service_configs/GIBS/MODIS_Water_Mask.xml b/data/scene/lodearth/map_service_configs/GIBS/MODIS_Water_Mask.xml deleted file mode 100644 index 0f9c24b540..0000000000 --- a/data/scene/lodearth/map_service_configs/GIBS/MODIS_Water_Mask.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - http://map1.vis.earthdata.nasa.gov/wmts-geo/MODIS_Water_Mask/default/2013-08-21/EPSG4326_250m/${z}/${y}/${x}.png - - - -180.0 - 90 - 396.0 - -198 - 7 - 2 - 1 - top - - EPSG:4326 - 512 - 512 - 4 - \ No newline at end of file diff --git a/data/scene/lodearth/map_service_configs/GIBS/Reference_Features.xml b/data/scene/lodearth/map_service_configs/GIBS/Reference_Features.xml deleted file mode 100644 index 6cc0348f36..0000000000 --- a/data/scene/lodearth/map_service_configs/GIBS/Reference_Features.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - http://map1.vis.earthdata.nasa.gov/wmts-geo/Reference_Features/default/2013-08-21/EPSG4326_250m/${z}/${y}/${x}.png - - - -180.0 - 90 - 396.0 - -198 - 9 - 2 - 1 - top - - EPSG:4326 - 512 - 512 - 4 - \ No newline at end of file diff --git a/data/scene/lodearth/map_service_configs/GIBS/Reference_Labels.xml b/data/scene/lodearth/map_service_configs/GIBS/Reference_Labels.xml deleted file mode 100644 index 0a13e11f23..0000000000 --- a/data/scene/lodearth/map_service_configs/GIBS/Reference_Labels.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - http://map1.vis.earthdata.nasa.gov/wmts-geo/Reference_Labels/default/2013-08-21/EPSG4326_250m/${z}/${y}/${x}.png - - - -180.0 - 90 - 396.0 - -198 - 9 - 2 - 1 - top - - EPSG:4326 - 512 - 512 - 4 - \ No newline at end of file diff --git a/data/scene/lodearth/map_service_configs/GIBS/TERRA_CR_B143_2016-04-12.wms b/data/scene/lodearth/map_service_configs/GIBS/TERRA_CR_B143_2016-04-12.wms deleted file mode 100644 index 974c7da85f..0000000000 --- a/data/scene/lodearth/map_service_configs/GIBS/TERRA_CR_B143_2016-04-12.wms +++ /dev/null @@ -1,8 +0,0 @@ - - - http://map1.vis.earthdata.nasa.gov/twms-geo/twms.cgi? - MODIS TERRA tileset - 2016-04-12 - - 20 - diff --git a/data/scene/lodearth/map_service_configs/GIBS/Temporal_Aqua_Orbit_Asc.xml b/data/scene/lodearth/map_service_configs/GIBS/Temporal_Aqua_Orbit_Asc.xml deleted file mode 100644 index e2253fabc9..0000000000 --- a/data/scene/lodearth/map_service_configs/GIBS/Temporal_Aqua_Orbit_Asc.xml +++ /dev/null @@ -1,36 +0,0 @@ - - 2012-05-08 - - 1d - YYYY-MM-DD - - - 1.1.1 - http://map2.vis.earthdata.nasa.gov/wms/wms.php?TIME=${OpenSpaceTimeId} - EPSG:4326 - image/png - TRUE - Aqua_Orbit_Asc - - - -180.0 - 90 - 396.0 - -198 - 8 - 2 - 1 - top - - EPSG:4326 - 512 - 512 - 3 - - - diff --git a/data/scene/lodearth/map_service_configs/GIBS/Temporal_VIIRS_SNPP_CorrectedReflectance_TrueColor.xml b/data/scene/lodearth/map_service_configs/GIBS/Temporal_VIIRS_SNPP_CorrectedReflectance_TrueColor.xml deleted file mode 100644 index 311f2ec097..0000000000 --- a/data/scene/lodearth/map_service_configs/GIBS/Temporal_VIIRS_SNPP_CorrectedReflectance_TrueColor.xml +++ /dev/null @@ -1,25 +0,0 @@ - - 2015-11-24 - - 1d - YYYY-MM-DD - - - http://map1.vis.earthdata.nasa.gov/wmts-geo/VIIRS_SNPP_CorrectedReflectance_TrueColor/default/${OpenSpaceTimeId}/EPSG4326_250m/${z}/${y}/${x}.jpg - - - -180.0 - 90 - 396.0 - -198 - 8 - 2 - 1 - top - - EPSG:4326 - 512 - 512 - 3 - - \ No newline at end of file diff --git a/data/scene/lodearth/map_service_configs/GIBS/VIIRS_CityLights_2012.xml b/data/scene/lodearth/map_service_configs/GIBS/VIIRS_CityLights_2012.xml deleted file mode 100644 index cf0c6a1866..0000000000 --- a/data/scene/lodearth/map_service_configs/GIBS/VIIRS_CityLights_2012.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - http://map1.vis.earthdata.nasa.gov/wmts-geo/VIIRS_CityLights_2012/default/2012-01-01/EPSG4326_500m/${z}/${y}/${x}.jpg - - - -180.0 - 90 - 396.0 - -198 - 8 - 2 - 1 - top - - EPSG:4326 - 512 - 512 - 4 - \ No newline at end of file diff --git a/data/scene/lodearth/map_service_configs/other/ASTER_GDEM_Greyscale_Shaded_Relief.xml b/data/scene/lodearth/map_service_configs/other/ASTER_GDEM_Greyscale_Shaded_Relief.xml deleted file mode 100644 index 8666bd37cc..0000000000 --- a/data/scene/lodearth/map_service_configs/other/ASTER_GDEM_Greyscale_Shaded_Relief.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - http://map1.vis.earthdata.nasa.gov/wmts-geo/ASTER_GDEM_Greyscale_Shaded_Relief/default/2016-05-16/EPSG4326_31m/${z}/${y}/${x}.jpg - - - -180.0 - 90 - 396.0 - -198 - 12 - 2 - 1 - top - - EPSG:4326 - 512 - 512 - 1 - \ No newline at end of file diff --git a/data/scene/lodearth/map_service_configs/other/Landsat_WELD_CorrectedReflectance_TrueColor_Global_Monthly_v3_STD_temporal.xml b/data/scene/lodearth/map_service_configs/other/Landsat_WELD_CorrectedReflectance_TrueColor_Global_Monthly_v3_STD_temporal.xml deleted file mode 100644 index 3dcf166656..0000000000 --- a/data/scene/lodearth/map_service_configs/other/Landsat_WELD_CorrectedReflectance_TrueColor_Global_Monthly_v3_STD_temporal.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - https://gibs.earthdata.nasa.gov/wmts/epsg4326/std/wmts.cgi? - MODIS TERRA tileset - ${t} - Landsat_WELD_CorrectedReflectance_TrueColor_Global_Monthly_v3_STD - image/jpeg - - 20 - \ No newline at end of file diff --git a/data/scene/lodearth/map_service_configs/other/MLS_O3_46hPa_Day.xml b/data/scene/lodearth/map_service_configs/other/MLS_O3_46hPa_Day.xml deleted file mode 100644 index e0dd1d4b7e..0000000000 --- a/data/scene/lodearth/map_service_configs/other/MLS_O3_46hPa_Day.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - http://map1.vis.earthdata.nasa.gov/wmts-geo/MLS_O3_46hPa_Day/default/2013-08-21/EPSG4326_2km/${z}/${y}/${x}.png - - - -180.0 - 90 - 396.0 - -198 - 5 - 2 - 1 - top - - EPSG:4326 - 512 - 512 - 4 - \ No newline at end of file diff --git a/data/scene/lodearth/map_service_configs/other/OpenStreetMap.xml b/data/scene/lodearth/map_service_configs/other/OpenStreetMap.xml deleted file mode 100644 index 450aab0cd6..0000000000 --- a/data/scene/lodearth/map_service_configs/other/OpenStreetMap.xml +++ /dev/null @@ -1,20 +0,0 @@ - - -http://tile.openstreetmap.org/${z}/${x}/${y}.png - - --180 -90 -180 --90 -18 -1 -1 -top - -EPSG:4326 -256 -256 -3 - - \ No newline at end of file diff --git a/data/scene/lodearth/map_service_configs/other/frmt_wms_virtualearth.xml b/data/scene/lodearth/map_service_configs/other/frmt_wms_virtualearth.xml deleted file mode 100644 index 3b628e9a89..0000000000 --- a/data/scene/lodearth/map_service_configs/other/frmt_wms_virtualearth.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - http://a${server_num}.ortho.tiles.virtualearth.net/tiles/a${quadkey}.jpeg?g=90 - - 4 - - diff --git a/data/scene/lodearth/map_service_configs/other/test.wms b/data/scene/lodearth/map_service_configs/other/test.wms deleted file mode 100644 index 7ee62a7fc7..0000000000 --- a/data/scene/lodearth/map_service_configs/other/test.wms +++ /dev/null @@ -1,79 +0,0 @@ - - - http://192.168.1.167/OnMars/wms.cgi? - CTX Mosaic - - - -180.0 - 90.0 - 180.0 - -90.0 - bottom - - 1 - - - - - \ No newline at end of file diff --git a/data/scene/lodearth/textures/test_tile.png b/data/scene/lodearth/textures/test_tile.png deleted file mode 100644 index cb16c0952f..0000000000 Binary files a/data/scene/lodearth/textures/test_tile.png and /dev/null differ diff --git a/data/scene/lodesritest/earth/BmngJan.wms b/data/scene/lodesritest/earth/BmngJan.wms deleted file mode 100644 index dd52266ba7..0000000000 --- a/data/scene/lodesritest/earth/BmngJan.wms +++ /dev/null @@ -1,20 +0,0 @@ - - - http://planetarydev-1803629091.us-west-2.elb.amazonaws.com/Earth/Bmng/tile/0/${z}/${y}/${x} - - - -180.0 - 90.0 - 180.0 - -90.0 - 86400 - 43200 - 8 - top - - EPSG:4326 - 240 - 240 - 3 - 10 - diff --git a/data/scene/lodesritest/earth/BmngJanBathy.wms b/data/scene/lodesritest/earth/BmngJanBathy.wms deleted file mode 100644 index 4bbc61d6eb..0000000000 --- a/data/scene/lodesritest/earth/BmngJanBathy.wms +++ /dev/null @@ -1,20 +0,0 @@ - - - http://planetarydev-1803629091.us-west-2.elb.amazonaws.com/Earth/Bmng/tile/2/${z}/${y}/${x} - - - -180.0 - 90.0 - 180.0 - -90.0 - 86400 - 43200 - 8 - top - - EPSG:4326 - 240 - 240 - 3 - 10 - diff --git a/data/scene/lodesritest/lodesritest.mod b/data/scene/lodesritest/lodesritest.mod deleted file mode 100644 index db213b3e6c..0000000000 --- a/data/scene/lodesritest/lodesritest.mod +++ /dev/null @@ -1,291 +0,0 @@ -return { - -- Earth barycenter module - { - Name = "EarthBarycenter", - Parent = "SolarSystemBarycenter", - }, - -- EarthTrail module - { - Name = "EarthTrail", - Parent = "SolarSystemBarycenter", - Renderable = { - Type = "RenderableTrail", - Body = "EARTH", - Frame = "GALACTIC", - Observer = "SUN", - RGB = { 0.5, 0.8, 1.0}, - TropicalOrbitPeriod = 365.242, - EarthOrbitRatio = 1, - DayLength = 24 - }, - GuiName = "/Solar/EarthTrail" - }, - -- RenderableGlobe module - { - Name = "LodEarth", - Parent = "EarthBarycenter", - Ephemeris = { - Type = "Spice", - Body = "EARTH", - Observer = "SUN", - Kernels = "${OPENSPACE_DATA}/spice/de430.bsp" - }, - Rotation = { - Type = "Spice", - Frame = "IAU_EARTH", - Reference = "ECLIPJ2000" - }, - Renderable = { - Type = "RenderableGlobe", - Frame = "IAU_EARTH", - Body = "EARTH", - Radii = {6378137.0, 6378137.0, 6356752.314245}, -- Earth's radii - CameraMinHeight = 300, - InteractionDepthBelowEllipsoid = 0, -- Useful when having negative height map values - SegmentsPerPatch = 64, - TextureInitData = { - ColorTextureMinimumSize = 512,--512, - OverlayMinimumSize = 512, - HeightMapMinimumSize = 64, - }, - Textures = { - ColorTextures = { - { - Name = "Black Marble Next Generation (January)", - FilePath = "earth/BmngJan.wms", - Enabled = true - }, - { - Name = "Black Marble Next Generation Bathymetry (January)", - FilePath = "earth/BmngJanBathy.wms", - }, - - }, - GrayScaleOverlays = { - - }, - NightTextures = { - }, - WaterMasks = { - }, - Overlays = { - }, - HeightMaps = { - { - Name = "Black Marble Next Generation (Januray)", - FilePath = "earth/BmngJanTopo.wms", - Enabled = true, - }, - }, - HeightMapOverlays = { - }, - }, - } - }, - { - Name = "LodMoon", - Parent = "EarthBarycenter", - Ephemeris = { - Type = "Spice", - Body = "MOON", - Observer = "SUN", - Kernels = "${OPENSPACE_DATA}/spice/de430.bsp" - }, - Rotation = { - Type = "Spice", - Frame = "IAU_MOON", - Reference = "ECLIPJ2000" - }, - Renderable = { - Type = "RenderableGlobe", - Frame = "IAU_MOON", - Body = "MOON", - Radii = {1737000.0, 1737000.0, 1737000.0}, -- Earth's radii - CameraMinHeight = 300, - InteractionDepthBelowEllipsoid = 0, -- Useful when having negative height map values - SegmentsPerPatch = 64, - TextureInitData = { - ColorTextureMinimumSize = 512,--512, - OverlayMinimumSize = 512, - HeightMapMinimumSize = 64, - }, - Textures = { - ColorTextures = { - { - Name = "ClemUvvis", - FilePath = "moon/ClemUvvis.wms", - Enabled = true, - }, - { - Name = "Gebco", - FilePath = "moon/Gebco.wms", - }, - { - Name = "Kaguya", - FilePath = "moon/Kaguya.wms", - }, - -- { - -- Name = "LolaClrShade", - -- FilePath = "moon/LolaClrShade.wms", - -- }, - -- { - -- Name = "LolaShade", - -- FilePath = "moon/LolaShade.wms", - -- }, - { - Name = "UvvisHybrid", - FilePath = "moon/UvvisHybrid.wms", - }, - { - Name = "Wac", - FilePath = "moon/Wac.wms", - }, - - }, - GrayScaleOverlays = { - - }, - NightTextures = { - }, - WaterMasks = { - }, - Overlays = { - }, - HeightMaps = { - { - Name = "LolaDem", - FilePath = "moon/LolaDem.wms", - Enabled = true, - }, - }, - HeightMapOverlays = { - - }, - }, - }, - }, - { - Name = "LodMars", - Parent = "EarthBarycenter", - Ephemeris = { - Type = "Spice", - Body = "MARS", - Observer = "SUN", - Kernels = "${OPENSPACE_DATA}/spice/MAR063.BSP" - }, - Rotation = { - Type = "Spice", - Frame = "IAU_MARS", - Reference = "ECLIPJ2000" - }, - Renderable = { - Type = "RenderableGlobe", - Frame = "IAU_MARS", - Body = "MARS", - Radii = {3390000.0, 3390000.0, 3390000.0}, -- Earth's radii - CameraMinHeight = 300, - InteractionDepthBelowEllipsoid = 0, -- Useful when having negative height map values - SegmentsPerPatch = 64, - TextureInitData = { - ColorTextureMinimumSize = 512,--512, - OverlayMinimumSize = 512, - HeightMapMinimumSize = 64, - }, - Textures = { - ColorTextures = { - { - Name = "MDIM", - FilePath = "mars/Mdim.wms", - Enabled = true, - }, - { - Name = "MolaPseudoColor", - FilePath = "mars/MolaPseudoColor.wms", - }, - }, - GrayScaleOverlays = { - { - Name = "ThemisIRDay", - FilePath = "mars/ThemisIRDay.wms", - }, - { - Name = "ThemisIRNight", - FilePath = "mars/ThemisIRNight.xml", - }, - - }, - NightTextures = { - }, - WaterMasks = { - }, - Overlays = { - }, - HeightMaps = { - { - Name = "MolaElevation", - FilePath = "mars/MolaElevation.wms", - Enabled = true, - }, - }, - HeightMapOverlays = { - }, - }, - } - }, - { - Name = "LodMercury", - Parent = "EarthBarycenter", - Ephemeris = { - Type = "Spice", - Body = "MERCURY", - Observer = "SUN", - Kernels = "${OPENSPACE_DATA}/spice/de430.bsp" - }, - Rotation = { - Type = "Spice", - Frame = "IAU_MERCURY", - Reference = "ECLIPJ2000" - }, - Renderable = { - Type = "RenderableGlobe", - Frame = "IAU_MERCURY", - Body = "MERCURY", - Radii = {2440000.0, 2440000.0, 2440000.0}, -- Earth's radii - CameraMinHeight = 300, - InteractionDepthBelowEllipsoid = 0, -- Useful when having negative height map values - SegmentsPerPatch = 64, - TextureInitData = { - ColorTextureMinimumSize = 512,--512, - OverlayMinimumSize = 512, - HeightMapMinimumSize = 64, - }, - Textures = { - ColorTextures = { - { - Name = "MessengerMdis", - FilePath = "mercury/MessengerMdis.wms", - Enabled = true - }, - { - Name = "MessengerMosaic", - FilePath = "mercury/MessengerMosaic.wms", - } - }, - GrayScaleOverlays = { - - }, - NightTextures = { - }, - WaterMasks = { - }, - Overlays = { - }, - HeightMaps = { - }, - HeightMapOverlays = { - - }, - }, - } - }, -} diff --git a/data/scene/debugglobe/textures/arrows.png b/data/scene/lodglobes/arrows.png similarity index 100% rename from data/scene/debugglobe/textures/arrows.png rename to data/scene/lodglobes/arrows.png diff --git a/data/scene/debugglobe/earth.data b/data/scene/lodglobes/earth/earth.data similarity index 84% rename from data/scene/debugglobe/earth.data rename to data/scene/lodglobes/earth/earth.data index 240c1d5212..e168d4c8be 100644 --- a/data/scene/debugglobe/earth.data +++ b/data/scene/lodglobes/earth/earth.data @@ -1,5 +1,5 @@ return { FileRequest = { - { Identifier = "earth_textures", Destination = "textures", Version = 1 } + { Identifier = "earth_textures", Destination = "textures", Version = 2 } }, -} \ No newline at end of file +} diff --git a/data/scene/lodearth/lodearth.mod b/data/scene/lodglobes/earth/earth.mod similarity index 51% rename from data/scene/lodearth/lodearth.mod rename to data/scene/lodglobes/earth/earth.mod index f7ca2e8291..1df4498c85 100644 --- a/data/scene/lodearth/lodearth.mod +++ b/data/scene/lodglobes/earth/earth.mod @@ -6,7 +6,7 @@ return { Parent = "SolarSystemBarycenter", Transform = { Translation = { - Type = "SpiceEphemeris", + Type = "SpiceTranslation", Body = "EARTH", Observer = "SUN", Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" @@ -18,15 +18,20 @@ return { Name = "EarthTrail", Parent = "SolarSystemBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "EARTH", - Frame = "GALACTIC", - Observer = "SUN", - RGB = { 0.5, 0.8, 1.0}, - TropicalOrbitPeriod = 365.242, - EarthOrbitRatio = 1, - DayLength = 24 - } + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "EARTH", + Observer = "SUN" + }, + Color = { 0.5, 0.8, 1.0 }, + -- StartTime = "2016 JUN 01 12:00:00.000", + -- EndTime = "2017 JAN 01 12:00:00.000", + -- SampleInterval = 3600 + Period = 365.242, + Resolution = 1000 + }, + GuiName = "/Solar/EarthTrail" }, -- RenderableGlobe module { @@ -49,54 +54,69 @@ return { CameraMinHeight = 300, InteractionDepthBelowEllipsoid = 0, -- Useful when having negative height map values SegmentsPerPatch = 64, - TextureInitData = { - ColorTextureMinimumSize = 512,--512, - OverlayMinimumSize = 512, - HeightMapMinimumSize = 64, - }, - Textures = { - ColorTextures = { + Layers = { + ColorLayers = { + { + Name = "ESRI VIIRS Combo", + Type = "ByLevel", + LevelTileProviders = { + { + MaxLevel = 7, + TileProvider = { FilePath = "map_service_configs/GIBS/VIIRS_SNPP_CorrectedReflectance_TrueColor.xml", }, + }, + { + MaxLevel = 22, + TileProvider = { FilePath = "map_service_configs/ESRI/ESRI_Imagery_World_2D.wms" }, + }, + }, + Enabled = true, + }, { Type = "Temporal", Name = "Temporal VIIRS SNPP", FilePath = "map_service_configs/GIBS/Temporal_VIIRS_SNPP_CorrectedReflectance_TrueColor.xml", }, - { - Type = "SingleImage", - Name = "Debug Tiles", - FilePath = "textures/test_tile.png", - }, { Type = "Temporal", - Name = "Temporal MODIS Aqua CorrectedRecflectance TrueColor", - FilePath = "map_service_configs/GIBS/Temporal_MODIS_Aqua_CorrectedReflectance_TrueColor.xml", + Name = "Temporal_GHRSST_L4_MUR_Sea_Surface_Temperature", + FilePath = "map_service_configs/GIBS/Temporal_GHRSST_L4_MUR_Sea_Surface_Temperature.xml", }, + -- { + -- Type = "SingleImage", + -- Name = "Debug Tiles", + -- FilePath = "../../debugglobe/textures/test_tile.png", + -- }, { - Name = "MODIS_Terra_CorrectedReflectance_TrueColor", - FilePath = "map_service_configs/GIBS/MODIS_Terra_CorrectedReflectance_TrueColor.xml", - }, - { - Name = "ESRI Imagery World 2D", - FilePath = "map_service_configs/ESRI/ESRI_Imagery_World_2D.wms", - Enabled = true, + Name = "BMNG", + FilePath = "map_service_configs/Utah/Bmng.wms" } + -- { + -- Type = "Temporal", + -- Name = "NOAA RT", + -- FilePath = "map_service_configs/other/noaa_rt.xml" + -- } }, - GrayScaleOverlays = { - - }, - NightTextures = { + GrayScaleLayers = { }, + GrayScaleColorOverlays = { }, + NightLayers = { { Name = "Earth at Night 2012", FilePath = "map_service_configs/GIBS/VIIRS_CityLights_2012.xml", + Enabled = true, }, }, WaterMasks = { { Name = "MODIS_Water_Mask", FilePath = "map_service_configs/GIBS/MODIS_Water_Mask.xml", + Enabled = true, }, + { + Name = "GEBCO", + FilePath = "map_service_configs/Utah/Gebco.wms", + } }, - Overlays = { + ColorOverlays = { { Name = "Coastlines", FilePath = "map_service_configs/GIBS/Coastlines.xml", @@ -109,19 +129,37 @@ return { Name = "Reference_Labels", FilePath = "map_service_configs/GIBS/Reference_Labels.xml", }, + { + Type = "TileIndex", + Name = "Tile Indices", + }, { Type = "SizeReference", Name = "Size Reference", Radii = earthEllipsoid, - BackgroundImagePath = "../debugglobe/textures/arrows.png", + BackgroundImagePath = "../arrows.png", }, + --[[{ + Name = "Test", + Type = "LevelSpecific", + LevelTileProviders = { + { + MaxLevel = 5, + TileProvider = { Type = "TileIndex" }, + }, + { + MaxLevel = 7, + TileProvider = { Type = "SingleImage", FilePath = "../../debugglobe/textures/test_tile.png",}, + }, + }, + },]] }, - HeightMaps = { + HeightLayers = { { Name = "Terrain tileset", FilePath = "map_service_configs/ESRI/TERRAIN.wms", Enabled = true, - MinimumPixelSize = 90, + MinimumPixelSize = 64, DoPreProcessing = true, }, }, diff --git a/data/scene/debugglobe/map_service_configs/earth/ESRI_Imagery_World_2D.wms b/data/scene/lodglobes/earth/map_service_configs/ESRI/ESRI_Imagery_World_2D.wms similarity index 83% rename from data/scene/debugglobe/map_service_configs/earth/ESRI_Imagery_World_2D.wms rename to data/scene/lodglobes/earth/map_service_configs/ESRI/ESRI_Imagery_World_2D.wms index ef90f48509..dfaa82712b 100644 --- a/data/scene/debugglobe/map_service_configs/earth/ESRI_Imagery_World_2D.wms +++ b/data/scene/lodglobes/earth/map_service_configs/ESRI/ESRI_Imagery_World_2D.wms @@ -13,12 +13,10 @@ 512 3 5 - + false \ No newline at end of file diff --git a/data/scene/lodearth/map_service_configs/ESRI/TERRAIN.wms b/data/scene/lodglobes/earth/map_service_configs/ESRI/TERRAIN.wms similarity index 94% rename from data/scene/lodearth/map_service_configs/ESRI/TERRAIN.wms rename to data/scene/lodglobes/earth/map_service_configs/ESRI/TERRAIN.wms index 6782144c50..86f039232e 100644 --- a/data/scene/lodearth/map_service_configs/ESRI/TERRAIN.wms +++ b/data/scene/lodglobes/earth/map_service_configs/ESRI/TERRAIN.wms @@ -10,4 +10,5 @@ -90.0 bottom + 2 diff --git a/data/scene/debugglobe/map_service_configs/earth/Coastlines.xml b/data/scene/lodglobes/earth/map_service_configs/GIBS/Coastlines.xml similarity index 100% rename from data/scene/debugglobe/map_service_configs/earth/Coastlines.xml rename to data/scene/lodglobes/earth/map_service_configs/GIBS/Coastlines.xml diff --git a/data/scene/debugglobe/map_service_configs/earth/GIBS_Aqua_MODIS_true.xml b/data/scene/lodglobes/earth/map_service_configs/GIBS/GIBS_Aqua_MODIS_true.xml similarity index 100% rename from data/scene/debugglobe/map_service_configs/earth/GIBS_Aqua_MODIS_true.xml rename to data/scene/lodglobes/earth/map_service_configs/GIBS/GIBS_Aqua_MODIS_true.xml diff --git a/data/scene/debugglobe/map_service_configs/earth/MODIS_Terra_Brightness_Temp_Band31_Day.xml b/data/scene/lodglobes/earth/map_service_configs/GIBS/MODIS_Terra_Brightness_Temp_Band31_Day.xml similarity index 100% rename from data/scene/debugglobe/map_service_configs/earth/MODIS_Terra_Brightness_Temp_Band31_Day.xml rename to data/scene/lodglobes/earth/map_service_configs/GIBS/MODIS_Terra_Brightness_Temp_Band31_Day.xml diff --git a/data/scene/debugglobe/map_service_configs/earth/MODIS_Terra_CorrectedReflectance_TrueColor.xml b/data/scene/lodglobes/earth/map_service_configs/GIBS/MODIS_Terra_CorrectedReflectance_TrueColor.xml similarity index 100% rename from data/scene/debugglobe/map_service_configs/earth/MODIS_Terra_CorrectedReflectance_TrueColor.xml rename to data/scene/lodglobes/earth/map_service_configs/GIBS/MODIS_Terra_CorrectedReflectance_TrueColor.xml diff --git a/data/scene/debugglobe/map_service_configs/earth/MODIS_Terra_CorrectedReflectance_TrueColor_temporal.xml b/data/scene/lodglobes/earth/map_service_configs/GIBS/MODIS_Terra_CorrectedReflectance_TrueColor_temporal.xml similarity index 100% rename from data/scene/debugglobe/map_service_configs/earth/MODIS_Terra_CorrectedReflectance_TrueColor_temporal.xml rename to data/scene/lodglobes/earth/map_service_configs/GIBS/MODIS_Terra_CorrectedReflectance_TrueColor_temporal.xml diff --git a/data/scene/debugglobe/map_service_configs/earth/MODIS_Water_Mask.xml b/data/scene/lodglobes/earth/map_service_configs/GIBS/MODIS_Water_Mask.xml similarity index 100% rename from data/scene/debugglobe/map_service_configs/earth/MODIS_Water_Mask.xml rename to data/scene/lodglobes/earth/map_service_configs/GIBS/MODIS_Water_Mask.xml diff --git a/data/scene/debugglobe/map_service_configs/earth/Reference_Features.xml b/data/scene/lodglobes/earth/map_service_configs/GIBS/Reference_Features.xml similarity index 100% rename from data/scene/debugglobe/map_service_configs/earth/Reference_Features.xml rename to data/scene/lodglobes/earth/map_service_configs/GIBS/Reference_Features.xml diff --git a/data/scene/debugglobe/map_service_configs/earth/Reference_Labels.xml b/data/scene/lodglobes/earth/map_service_configs/GIBS/Reference_Labels.xml similarity index 100% rename from data/scene/debugglobe/map_service_configs/earth/Reference_Labels.xml rename to data/scene/lodglobes/earth/map_service_configs/GIBS/Reference_Labels.xml diff --git a/data/scene/debugglobe/map_service_configs/earth/TERRA_CR_B143_2016-04-12.wms b/data/scene/lodglobes/earth/map_service_configs/GIBS/TERRA_CR_B143_2016-04-12.wms similarity index 100% rename from data/scene/debugglobe/map_service_configs/earth/TERRA_CR_B143_2016-04-12.wms rename to data/scene/lodglobes/earth/map_service_configs/GIBS/TERRA_CR_B143_2016-04-12.wms diff --git a/data/scene/debugglobe/map_service_configs/earth/Temporal_Aqua_Orbit_Asc.xml b/data/scene/lodglobes/earth/map_service_configs/GIBS/Temporal_Aqua_Orbit_Asc.xml similarity index 100% rename from data/scene/debugglobe/map_service_configs/earth/Temporal_Aqua_Orbit_Asc.xml rename to data/scene/lodglobes/earth/map_service_configs/GIBS/Temporal_Aqua_Orbit_Asc.xml diff --git a/data/scene/lodearth/map_service_configs/GIBS/Temporal_MODIS_Aqua_CorrectedReflectance_TrueColor.xml b/data/scene/lodglobes/earth/map_service_configs/GIBS/Temporal_GHRSST_L4_MUR_Sea_Surface_Temperature.xml similarity index 80% rename from data/scene/lodearth/map_service_configs/GIBS/Temporal_MODIS_Aqua_CorrectedReflectance_TrueColor.xml rename to data/scene/lodglobes/earth/map_service_configs/GIBS/Temporal_GHRSST_L4_MUR_Sea_Surface_Temperature.xml index d09c0e9615..2a4f525511 100644 --- a/data/scene/lodearth/map_service_configs/GIBS/Temporal_MODIS_Aqua_CorrectedReflectance_TrueColor.xml +++ b/data/scene/lodglobes/earth/map_service_configs/GIBS/Temporal_GHRSST_L4_MUR_Sea_Surface_Temperature.xml @@ -1,11 +1,11 @@ - 2012-05-08 + 2002-06-01 1d YYYY-MM-DD - http://map1.vis.earthdata.nasa.gov/wmts-geo/MODIS_Aqua_CorrectedReflectance_TrueColor/default/${OpenSpaceTimeId}/EPSG4326_250m/${z}/${y}/${x}.jpg + http://map1.vis.earthdata.nasa.gov/wmts-geo/GHRSST_L4_MUR_Sea_Surface_Temperature/default/${OpenSpaceTimeId}/EPSG4326_1km/${z}/${y}/${x}.png -180.0 @@ -20,6 +20,6 @@ EPSG:4326 512 512 - 3 + 4 \ No newline at end of file diff --git a/data/scene/debugglobe/map_service_configs/earth/Temporal_MODIS_Aqua_CorrectedReflectance_TrueColor.xml b/data/scene/lodglobes/earth/map_service_configs/GIBS/Temporal_MODIS_Aqua_CorrectedReflectance_TrueColor.xml similarity index 100% rename from data/scene/debugglobe/map_service_configs/earth/Temporal_MODIS_Aqua_CorrectedReflectance_TrueColor.xml rename to data/scene/lodglobes/earth/map_service_configs/GIBS/Temporal_MODIS_Aqua_CorrectedReflectance_TrueColor.xml diff --git a/data/scene/debugglobe/map_service_configs/earth/Temporal_VIIRS_SNPP_CorrectedReflectance_TrueColor.xml b/data/scene/lodglobes/earth/map_service_configs/GIBS/Temporal_VIIRS_SNPP_CorrectedReflectance_TrueColor.xml similarity index 100% rename from data/scene/debugglobe/map_service_configs/earth/Temporal_VIIRS_SNPP_CorrectedReflectance_TrueColor.xml rename to data/scene/lodglobes/earth/map_service_configs/GIBS/Temporal_VIIRS_SNPP_CorrectedReflectance_TrueColor.xml diff --git a/data/scene/debugglobe/map_service_configs/earth/VIIRS_CityLights_2012.xml b/data/scene/lodglobes/earth/map_service_configs/GIBS/VIIRS_CityLights_2012.xml similarity index 100% rename from data/scene/debugglobe/map_service_configs/earth/VIIRS_CityLights_2012.xml rename to data/scene/lodglobes/earth/map_service_configs/GIBS/VIIRS_CityLights_2012.xml diff --git a/data/scene/lodearth/map_service_configs/GIBS/VIIRS_SNPP_CorrectedReflectance_TrueColor.xml b/data/scene/lodglobes/earth/map_service_configs/GIBS/VIIRS_SNPP_CorrectedReflectance_TrueColor.xml similarity index 90% rename from data/scene/lodearth/map_service_configs/GIBS/VIIRS_SNPP_CorrectedReflectance_TrueColor.xml rename to data/scene/lodglobes/earth/map_service_configs/GIBS/VIIRS_SNPP_CorrectedReflectance_TrueColor.xml index 881dce3e58..28499cabbd 100644 --- a/data/scene/lodearth/map_service_configs/GIBS/VIIRS_SNPP_CorrectedReflectance_TrueColor.xml +++ b/data/scene/lodglobes/earth/map_service_configs/GIBS/VIIRS_SNPP_CorrectedReflectance_TrueColor.xml @@ -1,6 +1,6 @@ - http://map1.vis.earthdata.nasa.gov/wmts-geo/VIIRS_SNPP_CorrectedReflectance_TrueColor/default/2016-05-16/EPSG4326_250m/${z}/${y}/${x}.jpg + http://map1.vis.earthdata.nasa.gov/wmts-geo/VIIRS_SNPP_CorrectedReflectance_TrueColor/default/2016-10-01/EPSG4326_250m/${z}/${y}/${x}.jpg -180.0 diff --git a/data/scene/lodesritest/earth/BmngJanTopo.wms b/data/scene/lodglobes/earth/map_service_configs/Utah/Bmng.wms similarity index 75% rename from data/scene/lodesritest/earth/BmngJanTopo.wms rename to data/scene/lodglobes/earth/map_service_configs/Utah/Bmng.wms index 0cdfad8e92..3a82a1011b 100644 --- a/data/scene/lodesritest/earth/BmngJanTopo.wms +++ b/data/scene/lodglobes/earth/map_service_configs/Utah/Bmng.wms @@ -1,14 +1,14 @@ - http://planetarydev-1803629091.us-west-2.elb.amazonaws.com/Earth/Bmng/tile/1/${z}/${y}/${x} + http://asgard.sci.utah.edu/Earth/Bmng/tile/${z}/${y}/${x} -180.0 90.0 180.0 -90.0 - 86400 - 43200 + 86400 + 43200 8 top @@ -17,4 +17,4 @@ 240 3 10 - + \ No newline at end of file diff --git a/data/scene/lodesritest/moon/Gebco.wms b/data/scene/lodglobes/earth/map_service_configs/Utah/Gebco.wms similarity index 72% rename from data/scene/lodesritest/moon/Gebco.wms rename to data/scene/lodglobes/earth/map_service_configs/Utah/Gebco.wms index c9d1b4ce90..98af78a869 100644 --- a/data/scene/lodesritest/moon/Gebco.wms +++ b/data/scene/lodglobes/earth/map_service_configs/Utah/Gebco.wms @@ -1,14 +1,14 @@ - http://planetarydev-1803629091.us-west-2.elb.amazonaws.com/Earth/Gebco/tile/${z}/${y}/${x} + http://asgard.sci.utah.edu/Earth/Gebco/tile/${z}/${y}/${x} -180.0 90.0 180.0 -90.0 - 43200 - 21600 + 43200 + 21600 6 top @@ -16,6 +16,5 @@ 360 360 1 - Int16 10 - + \ No newline at end of file diff --git a/data/scene/debugglobe/map_service_configs/earth/ASTER_GDEM_Greyscale_Shaded_Relief.xml b/data/scene/lodglobes/earth/map_service_configs/other/ASTER_GDEM_Greyscale_Shaded_Relief.xml similarity index 100% rename from data/scene/debugglobe/map_service_configs/earth/ASTER_GDEM_Greyscale_Shaded_Relief.xml rename to data/scene/lodglobes/earth/map_service_configs/other/ASTER_GDEM_Greyscale_Shaded_Relief.xml diff --git a/data/scene/debugglobe/map_service_configs/earth/Landsat_WELD_CorrectedReflectance_TrueColor_Global_Monthly_v3_STD_temporal.xml b/data/scene/lodglobes/earth/map_service_configs/other/Landsat_WELD_CorrectedReflectance_TrueColor_Global_Monthly_v3_STD_temporal.xml similarity index 100% rename from data/scene/debugglobe/map_service_configs/earth/Landsat_WELD_CorrectedReflectance_TrueColor_Global_Monthly_v3_STD_temporal.xml rename to data/scene/lodglobes/earth/map_service_configs/other/Landsat_WELD_CorrectedReflectance_TrueColor_Global_Monthly_v3_STD_temporal.xml diff --git a/data/scene/debugglobe/map_service_configs/earth/MLS_O3_46hPa_Day.xml b/data/scene/lodglobes/earth/map_service_configs/other/MLS_O3_46hPa_Day.xml similarity index 100% rename from data/scene/debugglobe/map_service_configs/earth/MLS_O3_46hPa_Day.xml rename to data/scene/lodglobes/earth/map_service_configs/other/MLS_O3_46hPa_Day.xml diff --git a/data/scene/debugglobe/map_service_configs/earth/OpenStreetMap.xml b/data/scene/lodglobes/earth/map_service_configs/other/OpenStreetMap.xml similarity index 100% rename from data/scene/debugglobe/map_service_configs/earth/OpenStreetMap.xml rename to data/scene/lodglobes/earth/map_service_configs/other/OpenStreetMap.xml diff --git a/data/scene/debugglobe/map_service_configs/earth/frmt_wms_virtualearth.xml b/data/scene/lodglobes/earth/map_service_configs/other/frmt_wms_virtualearth.xml similarity index 100% rename from data/scene/debugglobe/map_service_configs/earth/frmt_wms_virtualearth.xml rename to data/scene/lodglobes/earth/map_service_configs/other/frmt_wms_virtualearth.xml diff --git a/data/scene/lodglobes/earth/map_service_configs/other/noaa_rt.xml b/data/scene/lodglobes/earth/map_service_configs/other/noaa_rt.xml new file mode 100644 index 0000000000..717aab0070 --- /dev/null +++ b/data/scene/lodglobes/earth/map_service_configs/other/noaa_rt.xml @@ -0,0 +1,8 @@ + + 2016-11-28T05:00:00 + 2016-12-06T04:30:00 + 30m + YYYY-MM-DDThh_mm_ssZ + + D:/NOAA/rt/imergert_composite.${OpenSpaceTimeId}.png + diff --git a/data/scene/debugglobe/map_service_configs/test.wms b/data/scene/lodglobes/earth/map_service_configs/other/test.wms similarity index 100% rename from data/scene/debugglobe/map_service_configs/test.wms rename to data/scene/lodglobes/earth/map_service_configs/other/test.wms diff --git a/data/scene/newhorizons/jupiter/callisto/callisto.data b/data/scene/lodglobes/jupiter/callisto/callisto.data similarity index 100% rename from data/scene/newhorizons/jupiter/callisto/callisto.data rename to data/scene/lodglobes/jupiter/callisto/callisto.data diff --git a/data/scene/lodglobes/jupiter/callisto/callisto.mod b/data/scene/lodglobes/jupiter/callisto/callisto.mod new file mode 100644 index 0000000000..8aa1bda8f0 --- /dev/null +++ b/data/scene/lodglobes/jupiter/callisto/callisto.mod @@ -0,0 +1,63 @@ +return { + -- RenderableGlobe module + { + Name = "Callisto", + Parent = "JupiterBarycenter", + Transform = { + Rotation = { + Type = "SpiceRotation", + SourceFrame = "IAU_CALLISTO", + DestinationFrame = "GALACTIC", + }, + Translation = { + Type = "SpiceTranslation", + Body = "CALLISTO", + Observer = "JUPITER BARYCENTER", + Kernels = "${OPENSPACE_DATA}/spice/jup260.bsp" + }, + Scale = { + Type = "StaticScale", + Scale = 1, + }, + }, + Renderable = { + Type = "RenderableGlobe", + Radii = {2631000, 2631000, 2631000}, + CameraMinHeight = 300, + InteractionDepthBelowEllipsoid = 0, -- Useful when having negative height map values + SegmentsPerPatch = 64, + Layers = { + ColorLayers = { + { + Name = "Callisto Texture", + FilePath = "textures/callisto.jpg", + Enabled = true, + MinimumPixelSize = 112, + }, + }, + GrayScaleLayers = { }, + GrayScaleColorOverlays = { }, + NightLayers = { }, + WaterMasks = { }, + ColorOverlays = { }, + HeightLayers = { }, + }, + } + }, + -- Trail module + { + Name = "CallistoTrail", + Parent = "JupiterBarycenter", + Renderable = { + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "CALLISTO", + Observer = "JUPITER BARYCENTER", + }, + Color = { 0.4, 0.3, 0.01 }, + Period = 17, + Resolution = 1000 + } + } +} diff --git a/data/scene/newhorizons/jupiter/europa/europa.data b/data/scene/lodglobes/jupiter/europa/europa.data similarity index 100% rename from data/scene/newhorizons/jupiter/europa/europa.data rename to data/scene/lodglobes/jupiter/europa/europa.data diff --git a/data/scene/lodglobes/jupiter/europa/europa.mod b/data/scene/lodglobes/jupiter/europa/europa.mod new file mode 100644 index 0000000000..cd32cdd332 --- /dev/null +++ b/data/scene/lodglobes/jupiter/europa/europa.mod @@ -0,0 +1,64 @@ +return { + -- RenderableGlobe module + { + Name = "Europa", + Parent = "JupiterBarycenter", + Transform = { + Rotation = { + Type = "SpiceRotation", + SourceFrame = "IAU_EUROPA", + DestinationFrame = "GALACTIC", + }, + Translation = { + Type = "SpiceTranslation", + Body = "EUROPA", + Observer = "JUPITER BARYCENTER", + Kernels = "${OPENSPACE_DATA}/spice/jup260.bsp" + }, + Scale = { + Type = "StaticScale", + Scale = 1, + }, + }, + Renderable = { + Type = "RenderableGlobe", + Radii = {1561000, 1561000, 1561000}, + CameraMinHeight = 300, + InteractionDepthBelowEllipsoid = 0, -- Useful when having negative height map values + SegmentsPerPatch = 64, + Layers = { + ColorLayers = { + { + Name = "Europa Texture", + FilePath = "textures/europa.jpg", + Enabled = true, + MinimumPixelSize = 256, + }, + }, + GrayScaleLayers = { }, + GrayScaleColorOverlays = { }, + NightLayers = { }, + WaterMasks = { }, + ColorOverlays = { }, + HeightLayers = { }, + }, + } + }, + + -- Trail module + { + Name = "EuropaTrail", + Parent = "JupiterBarycenter", + Renderable = { + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "EUROPA", + Observer = "JUPITER BARYCENTER", + }, + Color = { 0.5, 0.3, 0.3 }, + Period = 85 / 24, + Resolution = 1000 + } + } +} diff --git a/data/scene/newhorizons/jupiter/ganymede/ganymede.data b/data/scene/lodglobes/jupiter/ganymede/ganymede.data similarity index 100% rename from data/scene/newhorizons/jupiter/ganymede/ganymede.data rename to data/scene/lodglobes/jupiter/ganymede/ganymede.data diff --git a/data/scene/lodglobes/jupiter/ganymede/ganymede.mod b/data/scene/lodglobes/jupiter/ganymede/ganymede.mod new file mode 100644 index 0000000000..be1bb1274c --- /dev/null +++ b/data/scene/lodglobes/jupiter/ganymede/ganymede.mod @@ -0,0 +1,63 @@ +return { + -- RenderableGlobe module + { + Name = "Ganymede", + Parent = "JupiterBarycenter", + Transform = { + Rotation = { + Type = "SpiceRotation", + SourceFrame = "IAU_GANYMEDE", + DestinationFrame = "GALACTIC", + }, + Translation = { + Type = "SpiceTranslation", + Body = "GANYMEDE", + Observer = "JUPITER BARYCENTER", + Kernels = "${OPENSPACE_DATA}/spice/jup260.bsp" + }, + Scale = { + Type = "StaticScale", + Scale = 1, + }, + }, + Renderable = { + Type = "RenderableGlobe", + Radii = {2631000, 2631000, 2631000}, + CameraMinHeight = 300, + InteractionDepthBelowEllipsoid = 0, -- Useful when having negative height map values + SegmentsPerPatch = 64, + Layers = { + ColorLayers = { + { + Name = "Ganymede Texture", + FilePath = "textures/ganymede.jpg", + Enabled = true, + MinimumPixelSize = 112, + }, + }, + GrayScaleLayers = { }, + GrayScaleColorOverlays = { }, + NightLayers = { }, + WaterMasks = { }, + ColorOverlays = { }, + HeightLayers = { }, + }, + } + }, + -- Trail module + { + Name = "GanymedeTrail", + Parent = "JupiterBarycenter", + Renderable = { + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "GANYMEDE", + Observer = "JUPITER BARYCENTER", + }, + Color = { 0.4, 0.3, 0.3 }, + Period = 172 / 24, + Resolution = 1000 + } + } +} diff --git a/data/scene/newhorizons/jupiter/io/io.data b/data/scene/lodglobes/jupiter/io/io.data similarity index 100% rename from data/scene/newhorizons/jupiter/io/io.data rename to data/scene/lodglobes/jupiter/io/io.data diff --git a/data/scene/lodglobes/jupiter/io/io.mod b/data/scene/lodglobes/jupiter/io/io.mod new file mode 100644 index 0000000000..0deb7fae71 --- /dev/null +++ b/data/scene/lodglobes/jupiter/io/io.mod @@ -0,0 +1,62 @@ +return { + -- RenderableGlobe module + { + Name = "Io", + Parent = "JupiterBarycenter", + Transform = { + Rotation = { + Type = "SpiceRotation", + SourceFrame = "IAU_IO", + DestinationFrame = "GALACTIC", + }, + Translation = { + Type = "SpiceTranslation", + Body = "IO", + Observer = "JUPITER BARYCENTER", + Kernels = "${OPENSPACE_DATA}/spice/jup260.bsp" + }, + Scale = { + Type = "StaticScale", + Scale = 1, + }, + }, + Renderable = { + Type = "RenderableGlobe", + Radii = {1821300, 1821300, 1821300}, + CameraMinHeight = 300, + InteractionDepthBelowEllipsoid = 0, -- Useful when having negative height map values + SegmentsPerPatch = 64, + Layers = { + ColorLayers = { + { + Name = "Io Texture", + FilePath = "textures/io.jpg", + Enabled = true, + }, + }, + GrayScaleLayers = { }, + GrayScaleColorOverlays = { }, + NightLayers = { }, + WaterMasks = { }, + ColorOverlays = { }, + HeightLayers = { }, + }, + } + }, + -- Trail module + { + Name = "IoTrail", + Parent = "JupiterBarycenter", + Renderable = { + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "IO", + Observer = "JUPITER BARYCENTER", + }, + Color = { 0.4, 0.4, 0.2 }, + Period = 42 / 24, + Resolution = 1000 + } + } +} diff --git a/data/scene/lodglobes/jupiter/jupiter/jup260.bsp.torrent b/data/scene/lodglobes/jupiter/jupiter/jup260.bsp.torrent new file mode 100644 index 0000000000..0c82073d38 Binary files /dev/null and b/data/scene/lodglobes/jupiter/jupiter/jup260.bsp.torrent differ diff --git a/data/scene/lodglobes/jupiter/jupiter/jupiter.data b/data/scene/lodglobes/jupiter/jupiter/jupiter.data new file mode 100644 index 0000000000..b22e81119b --- /dev/null +++ b/data/scene/lodglobes/jupiter/jupiter/jupiter.data @@ -0,0 +1,8 @@ +return { + FileRequest = { + { Identifier = "jupiter_textures", Destination = "textures", Version = 1 } + }, + TorrentFiles = { + { File = "jup260.bsp.torrent", Destination = "${SPICE}" }, + } +} \ No newline at end of file diff --git a/data/scene/lodglobes/jupiter/jupiter/jupiter.mod b/data/scene/lodglobes/jupiter/jupiter/jupiter.mod new file mode 100644 index 0000000000..d8a50af4a5 --- /dev/null +++ b/data/scene/lodglobes/jupiter/jupiter/jupiter.mod @@ -0,0 +1,73 @@ +return { + -- Barycenter module + { + Name = "JupiterBarycenter", + Parent = "SolarSystemBarycenter", + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "JUPITER BARYCENTER", + Observer = "SUN", + Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" + }, + }, + }, + -- RenderableGlobe module + { + Name = "Jupiter", + Parent = "JupiterBarycenter", + Transform = { + Rotation = { + Type = "SpiceRotation", + SourceFrame = "IAU_JUPITER", + DestinationFrame = "GALACTIC", + }, + Translation = { + Type = "StaticTranslation", + Position = {0, 0, 0}, -- jupiter is at its barycenter + }, + Scale = { + Type = "StaticScale", + Scale = 1, + }, + }, + Renderable = { + Type = "RenderableGlobe", + Radii = {71492000, 71492000, 66854000}, + CameraMinHeight = 300, + InteractionDepthBelowEllipsoid = 0, -- Useful when having negative height map values + SegmentsPerPatch = 64, + Layers = { + ColorLayers = { + { + Name = "Jupiter Texture", + FilePath = "textures/jupiter.jpg", + Enabled = true, + }, + }, + GrayScaleLayers = { }, + GrayScaleColorOverlays = { }, + NightLayers = { }, + WaterMasks = { }, + ColorOverlays = { }, + HeightLayers = { }, + }, + } + }, + -- Trail module + { + Name = "JupiterTrail", + Parent = "SolarSystemBarycenter", + Renderable = { + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "JUPITER BARYCENTER", + Observer = "SUN", + }, + Color = { 0.8, 0.7, 0.7 }, + Period = 4330.595, + Resolution = 1000 + } + } +} \ No newline at end of file diff --git a/data/scene/lodglobes/mars/MAR063.BSP.torrent b/data/scene/lodglobes/mars/MAR063.BSP.torrent new file mode 100644 index 0000000000..50cab2e6bf Binary files /dev/null and b/data/scene/lodglobes/mars/MAR063.BSP.torrent differ diff --git a/data/scene/debugglobe/map_service_configs/mars/CTX_Mosaic.xml b/data/scene/lodglobes/mars/map_service_configs/CTX_Mosaic.xml similarity index 65% rename from data/scene/debugglobe/map_service_configs/mars/CTX_Mosaic.xml rename to data/scene/lodglobes/mars/map_service_configs/CTX_Mosaic.xml index 9f7a65afb5..51fd81ce11 100644 --- a/data/scene/debugglobe/map_service_configs/mars/CTX_Mosaic.xml +++ b/data/scene/lodglobes/mars/map_service_configs/CTX_Mosaic.xml @@ -1,6 +1,6 @@ - http://192.168.1.167/OnMars/wms.cgi? + http://wms.itn.liu.se/OnMars/wms.cgi? CTX Mosaic TRUE @@ -12,4 +12,10 @@ 256 256 + + ./GDAL_CTX_cache + 3 + .png + + false \ No newline at end of file diff --git a/data/scene/lodglobes/mars/map_service_configs/MARS_Viking.xml b/data/scene/lodglobes/mars/map_service_configs/MARS_Viking.xml new file mode 100644 index 0000000000..7197faf38e --- /dev/null +++ b/data/scene/lodglobes/mars/map_service_configs/MARS_Viking.xml @@ -0,0 +1,10 @@ + + http://webgis3.wr.usgs.gov/arcgis/rest/services/Mars_color/MapServer/WMTS/1.0.0/WMTSCapabilities.xml + + -180.0 + 90 + 180.0 + -90 + + 3 + \ No newline at end of file diff --git a/data/scene/lodmars/map_service_configs/MARS_Viking_MDIM21.xml b/data/scene/lodglobes/mars/map_service_configs/MARS_Viking_MDIM21.xml similarity index 50% rename from data/scene/lodmars/map_service_configs/MARS_Viking_MDIM21.xml rename to data/scene/lodglobes/mars/map_service_configs/MARS_Viking_MDIM21.xml index f4952b7ed1..405fc03065 100644 --- a/data/scene/lodmars/map_service_configs/MARS_Viking_MDIM21.xml +++ b/data/scene/lodglobes/mars/map_service_configs/MARS_Viking_MDIM21.xml @@ -1,17 +1,15 @@ - http://dzw9r5p966egh.cloudfront.net/catalog/Mars_Viking_MDIM21_ClrMosaic_global_232m/1.0.0//default/default028mm/${z}/${y}/${x}.jpg + http://d1poygwgh8gv6r.cloudfront.net/catalog/Mars_Viking_MDIM21_ClrMosaic_global_232m/1.0.0//default/default028mm/${z}/${y}/${x}.jpg + image/jpg - -180.0 - 90 - 180.0 - -90 8 2 1 top + EPSG:4326 256 256 3 diff --git a/data/scene/lodglobes/mars/map_service_configs/MDIM21_color.xml b/data/scene/lodglobes/mars/map_service_configs/MDIM21_color.xml new file mode 100644 index 0000000000..caaa46437f --- /dev/null +++ b/data/scene/lodglobes/mars/map_service_configs/MDIM21_color.xml @@ -0,0 +1,22 @@ + + + 1.3.0 + http://planetarymaps.usgs.gov/cgi-bin/mapserv?map=/maps/mars/mars_simp_cyl.map + EPSG:4326 + image/png + MDIM21_color + TRUE + + + -180.0 + 90.0 + 180.0 + -90.0 + 2048 + 1024 + bottom + + + \ No newline at end of file diff --git a/data/scene/lodglobes/mars/map_service_configs/Mars_MGS_MOLA_DEM.xml b/data/scene/lodglobes/mars/map_service_configs/Mars_MGS_MOLA_DEM.xml new file mode 100644 index 0000000000..fbf695ecbd --- /dev/null +++ b/data/scene/lodglobes/mars/map_service_configs/Mars_MGS_MOLA_DEM.xml @@ -0,0 +1,17 @@ + + + http://d1poygwgh8gv6r.cloudfront.net/catalog/Mars_MGS_MOLA_DEM_mosaic_global_463m_8/1.0.0//default/default028mm/${z}/${y}/${x}.png + image/png + + + 5 + 2 + 1 + top + + Byte + EPSG:4326 + 256 + 256 + 2 + \ No newline at end of file diff --git a/data/scene/lodmars/map_service_configs/Mola_Elevation.xml b/data/scene/lodglobes/mars/map_service_configs/Mola_Elevation.xml similarity index 60% rename from data/scene/lodmars/map_service_configs/Mola_Elevation.xml rename to data/scene/lodglobes/mars/map_service_configs/Mola_Elevation.xml index b79223c4af..9c440826b0 100644 --- a/data/scene/lodmars/map_service_configs/Mola_Elevation.xml +++ b/data/scene/lodglobes/mars/map_service_configs/Mola_Elevation.xml @@ -1,6 +1,6 @@ - http://192.168.1.167/OnMars/wms.cgi? + http://wms.itn.liu.se/OnMars/wms.cgi? Mola Elevation @@ -10,4 +10,10 @@ -90.0 bottom + + ./GDAL_MOLA_cache + 3 + .png + + false \ No newline at end of file diff --git a/data/scene/lodglobes/mars/map_service_configs/Utah/CTX_Mosaic.xml b/data/scene/lodglobes/mars/map_service_configs/Utah/CTX_Mosaic.xml new file mode 100644 index 0000000000..6135ce51b0 --- /dev/null +++ b/data/scene/lodglobes/mars/map_service_configs/Utah/CTX_Mosaic.xml @@ -0,0 +1,20 @@ + + + http://asgard.sci.utah.edu/Mars/CTX/tile/${z}/${y}/${x} + + + -180.0 + 90.0 + 180.0 + -90.0 + 4194304 + 2097152 + 13 + top + + GEOGCS["Mars 2000", DATUM["D_Mars_2000", SPHEROID["MARS_2000_IAU_IAG",3396190.0,169.894447222361179]],PRIMEM["Greenwich"0],UNIT["Decimal_Degree",0.0174532925199433]] + 256 + 256 + 2 + 10 + \ No newline at end of file diff --git a/data/scene/lodesritest/mars/Mdim.wms b/data/scene/lodglobes/mars/map_service_configs/Utah/Mdim.xml similarity index 79% rename from data/scene/lodesritest/mars/Mdim.wms rename to data/scene/lodglobes/mars/map_service_configs/Utah/Mdim.xml index 6bdbe1c994..acaaedae86 100644 --- a/data/scene/lodesritest/mars/Mdim.wms +++ b/data/scene/lodglobes/mars/map_service_configs/Utah/Mdim.xml @@ -1,14 +1,14 @@ - http://planetarydev-1803629091.us-west-2.elb.amazonaws.com/Mars/Mdim/tile/${z}/${y}/${x} + http://asgard.sci.utah.edu/Mars/Mdim/tile/${z}/${y}/${x} -180.0 90.0 180.0 -90.0 - 92160 - 46080 + 92160 + 46080 7 top @@ -17,4 +17,4 @@ 360 3 10 - + \ No newline at end of file diff --git a/data/scene/debugglobe/map_service_configs/mars/Mola_Elevation.xml b/data/scene/lodglobes/mars/map_service_configs/Utah/MolaCTX_Elevation.xml similarity index 58% rename from data/scene/debugglobe/map_service_configs/mars/Mola_Elevation.xml rename to data/scene/lodglobes/mars/map_service_configs/Utah/MolaCTX_Elevation.xml index b79223c4af..96c96f84d7 100644 --- a/data/scene/debugglobe/map_service_configs/mars/Mola_Elevation.xml +++ b/data/scene/lodglobes/mars/map_service_configs/Utah/MolaCTX_Elevation.xml @@ -1,6 +1,6 @@ - http://192.168.1.167/OnMars/wms.cgi? + http://asgard.sci.utah.edu/MolaCTX/tile/${z}/${y}/${x} Mola Elevation @@ -10,4 +10,10 @@ -90.0 bottom + + ./GDAL_MOLA_cache + 3 + .png + + false \ No newline at end of file diff --git a/data/scene/lodesritest/mars/MolaPseudoColor.wms b/data/scene/lodglobes/mars/map_service_configs/Utah/MolaPseudoColor.xml similarity index 74% rename from data/scene/lodesritest/mars/MolaPseudoColor.wms rename to data/scene/lodglobes/mars/map_service_configs/Utah/MolaPseudoColor.xml index 5827227f80..494d21c5e4 100644 --- a/data/scene/lodesritest/mars/MolaPseudoColor.wms +++ b/data/scene/lodglobes/mars/map_service_configs/Utah/MolaPseudoColor.xml @@ -1,14 +1,14 @@ - http://planetarydev-1803629091.us-west-2.elb.amazonaws.com/Mars/MolaPseudoColor/tile/${z}/${y}/${x} + http://asgard.sci.utah.edu/Mars/MolaPseudoColor/tile/${z}/${y}/${x} - -180.0 + -180.0 90.0 180.0 -90.0 - 46080 - 23040 + 46080 + 23040 6 top @@ -17,4 +17,4 @@ 360 3 10 - + \ No newline at end of file diff --git a/data/scene/lodesritest/mars/MolaElevation.wms b/data/scene/lodglobes/mars/map_service_configs/Utah/Mola_Elevation.xml similarity index 72% rename from data/scene/lodesritest/mars/MolaElevation.wms rename to data/scene/lodglobes/mars/map_service_configs/Utah/Mola_Elevation.xml index 54dd409ee6..a0294879cf 100644 --- a/data/scene/lodesritest/mars/MolaElevation.wms +++ b/data/scene/lodglobes/mars/map_service_configs/Utah/Mola_Elevation.xml @@ -1,14 +1,14 @@ - http://planetarydev-1803629091.us-west-2.elb.amazonaws.com/Mars/MolaElevation/tile/${z}/${y}/${x} + http://asgard.sci.utah.edu/Mars/MolaElevation/tile/${z}/${y}/${x} - -180.0 + -180.0 90.0 180.0 -90.0 - 46080 - 23040 + 46080 + 23040 6 top @@ -16,6 +16,5 @@ 360 360 1 - Int16 10 - + \ No newline at end of file diff --git a/data/scene/lodesritest/mars/ThemisIRDay.wms b/data/scene/lodglobes/mars/map_service_configs/Utah/ThemisIRDay.xml similarity index 72% rename from data/scene/lodesritest/mars/ThemisIRDay.wms rename to data/scene/lodglobes/mars/map_service_configs/Utah/ThemisIRDay.xml index 4e51901771..3b7641214b 100644 --- a/data/scene/lodesritest/mars/ThemisIRDay.wms +++ b/data/scene/lodglobes/mars/map_service_configs/Utah/ThemisIRDay.xml @@ -1,14 +1,14 @@ - http://planetarydev-1803629091.us-west-2.elb.amazonaws.com/Mars/ThemisIRDay/tile/${z}/${y}/${x} + http://asgard.sci.utah.edu/Mars/ThemisIRDay/tile/${z}/${y}/${x} - - -180.0 + + -180.0 90.0 180.0 -90.0 - 213390 - 106695 + 213390 + 106695 9 top @@ -17,4 +17,4 @@ 256 1 10 - + \ No newline at end of file diff --git a/data/scene/lodesritest/mars/ThemisIRNight.wms b/data/scene/lodglobes/mars/map_service_configs/Utah/ThemisIRNight.xml similarity index 71% rename from data/scene/lodesritest/mars/ThemisIRNight.wms rename to data/scene/lodglobes/mars/map_service_configs/Utah/ThemisIRNight.xml index dd93321655..3b7641214b 100644 --- a/data/scene/lodesritest/mars/ThemisIRNight.wms +++ b/data/scene/lodglobes/mars/map_service_configs/Utah/ThemisIRNight.xml @@ -1,14 +1,14 @@ - http://planetarydev-1803629091.us-west-2.elb.amazonaws.com/Mars/ThemisIRNight/tile/${z}/${y}/${x} + http://asgard.sci.utah.edu/Mars/ThemisIRDay/tile/${z}/${y}/${x} - - -180.0 + + -180.0 90.0 180.0 -90.0 - 213388 - 71130 + 213390 + 106695 9 top @@ -17,4 +17,4 @@ 256 1 10 - + \ No newline at end of file diff --git a/data/scene/lodglobes/mars/mars.data b/data/scene/lodglobes/mars/mars.data new file mode 100644 index 0000000000..afaf7ab69d --- /dev/null +++ b/data/scene/lodglobes/mars/mars.data @@ -0,0 +1,8 @@ +return { + FileRequest = { + { Identifier = "mars_textures", Destination = "textures", Version = 1 } + }, + TorrentFiles = { + -- { File = "MAR063.BSP.torrent", Destination = "${SPICE}" } + } +} \ No newline at end of file diff --git a/data/scene/lodmars/lodmars.mod b/data/scene/lodglobes/mars/mars.mod similarity index 59% rename from data/scene/lodmars/lodmars.mod rename to data/scene/lodglobes/mars/mars.mod index dce7bf881b..040fc570e8 100644 --- a/data/scene/lodmars/lodmars.mod +++ b/data/scene/lodglobes/mars/mars.mod @@ -1,12 +1,12 @@ local marsEllipsoid = {3396190.0, 3396190.0, 3376200.0} return { - -- Mars barycenter module + -- Barycenter module { Name = "MarsBarycenter", Parent = "SolarSystemBarycenter", Transform = { Translation = { - Type = "SpiceEphemeris", + Type = "SpiceTranslation", Body = "MARS BARYCENTER", Observer = "SUN", Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" @@ -31,46 +31,64 @@ return { Renderable = { Type = "RenderableGlobe", Radii = marsEllipsoid, - CameraMinHeight = 1000, + CameraMinHeight = 10, InteractionDepthBelowEllipsoid = 10000, -- Useful when having negative height map values - SegmentsPerPatch = 90, - TextureInitData = { - ColorTextureMinimumSize = 512, - OverlayMinimumSize = 512, - HeightMapMinimumSize = 90, - }, - Textures = { - ColorTextures = { + SegmentsPerPatch = 64, + Layers = { + ColorLayers = { + -- { + -- Type = "SingleImage", + -- Name = "Debug Tiles", + -- FilePath = "../../debugglobe/textures/test_tile.png", + -- }, { - Type = "SingleImage", - Name = "Debug Tiles", - FilePath = "../debugglobe/textures/test_tile.png", - }, - { - Name = "MARS_Viking_MDIM21", + Name = "MARS_Viking", FilePath = "map_service_configs/MARS_Viking_MDIM21.xml", + Enabled = true, }, + { + Name = "MOLA Pseudo Color", + FilePath = "map_service_configs/Utah/MolaPseudoColor.xml", + -- Enabled = true, + }, + --[[ { Name = "Mars Viking Clr", FilePath = "map_datasets/Viking/Mars_Viking_ClrMosaic_global_925m_longlat_full.vrt", Enabled = true, }, + ]] }, - GrayScaleOverlays = { + GrayScaleLayers = { + + }, + GrayScaleColorOverlays = { { - Name = "CTX Mosaic", + Name = "CTX Mosaic [Europe]", FilePath = "map_service_configs/CTX_Mosaic.xml", Enabled = true, - }, - { - Name = "West Candor Chasma", - FilePath = "map_datasets/CTX/West_Candor_Chasma_longlat_global.vrt", - --Enabled = true, + }, { + Name = "CTX Mosaic [Utah]", + FilePath = "map_service_configs/Utah/CTX_Mosaic.xml", }, { Name = "Layered Rock Outcrops in Southwest Candor Chasma", FilePath = "map_datasets/HiRISE/Layered_Rock_Outcrops_in_Southwest_Candor_Chasma_Texture.vrt", }, + { + Name = "Themis IR Day", + FilePath = "map_service_configs/Utah/ThemisIRDay.xml", + }, + { + Name = "Themis IR Night", + FilePath = "map_service_configs/Utah/ThemisIRNight.xml", + }, + --[[ + { + Name = "West Candor Chasma", + FilePath = "map_datasets/CTX/West_Candor_Chasma_longlat_global.vrt", + --Enabled = true, + }, { Name = "MER_Meridianni_Endeavor_Basemap_25cm", FilePath = "map_datasets/Basemap/MER_Meridianni_Endeavor_Basemap_25cm.vrt", @@ -79,37 +97,34 @@ return { Name = "Part of Area Traversed by the Mars Exploration Rover", FilePath = "map_datasets/HiRISE/Part_of_Area_Traversed_by_the_Mars_Exploration_Rover_Texture.vrt", }, + ]] }, - NightTextures = { - - }, - WaterMasks = { - - }, - Overlays = { + NightLayers = { }, + WaterMasks = { }, + ColorOverlays = { { - Type = "ChunkIndex", + Type = "TileIndex", Name = "Indices", }, { Type = "SizeReference", Name = "Size Reference", Radii = marsEllipsoid, - BackgroundImagePath = "../debugglobe/textures/arrows.png", + BackgroundImagePath = "../arrows.png", }, }, - HeightMaps = { + HeightLayers = { { Name = "Mola Elevation", - FilePath = "map_service_configs/Mola_Elevation.xml", + FilePath = "map_service_configs/Utah/Mola_Elevation.xml", Enabled = true, MinimumPixelSize = 90, DoPreProcessing = true, }, { - Name = "West Candor Chasma", - FilePath = "map_datasets/CTX/West_Candor_Chasma_DEM_longlat_global.vrt", - --Enabled = true, + Name = "Mola Elevation CTX", + FilePath = "map_service_configs/Utah/MolaCTX_Elevation.xml", + -- Enabled = true, MinimumPixelSize = 90, DoPreProcessing = true, }, @@ -119,27 +134,45 @@ return { MinimumPixelSize = 90, DoPreProcessing = true, }, + --[[ + { + Name = "Mola Elevation", + FilePath = "map_service_configs/Mars_MGS_MOLA_DEM.xml", + Enabled = true, + MinimumPixelSize = 64, + DoPreProcessing = true, + }, +--]] +--[[ { + Name = "West Candor Chasma", + FilePath = "map_datasets/CTX/West_Candor_Chasma_DEM_longlat_global.vrt", + --Enabled = true, + MinimumPixelSize = 90, + DoPreProcessing = true, + }, { Name = "Part of Area Traversed by the Mars Exploration Rover", FilePath = "map_datasets/HiRISE/Part_of_Area_Traversed_by_the_Mars_Exploration_Rover_Heightmap.vrt", }, + ]] }, }, } }, - -- MarsTrail module + -- Trail module { Name = "MarsTrail", - Parent = "Sun", + Parent = "SolarSystemBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "MARS BARYCENTER", - Frame = "GALACTIC", - Observer = "SUN", - RGB = { 1, 0.8, 0.5 }, - TropicalOrbitPeriod = 686.973, - EarthOrbitRatio = 1.881, - DayLength = 24.6597, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "MARS BARYCENTER", + Observer = "SUN", + }, + Color = { 0.814, 0.305, 0.220 }, + Period = 686.973, + Resolution = 1000 } } } diff --git a/data/scene/lodmercury/lodmercury.mod b/data/scene/lodglobes/mercury/lodmercury.mod similarity index 59% rename from data/scene/lodmercury/lodmercury.mod rename to data/scene/lodglobes/mercury/lodmercury.mod index f949495ff1..8e211d3c5e 100644 --- a/data/scene/lodmercury/lodmercury.mod +++ b/data/scene/lodglobes/mercury/lodmercury.mod @@ -1,18 +1,17 @@ return { - -- Mercury barycenter module + -- Barycenter module { Name = "MercuryBarycenter", Parent = "SolarSystemBarycenter", Transform = { Translation = { - Type = "SpiceEphemeris", + Type = "SpiceTranslation", Body = "MERCURY", Observer = "SUN", Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" }, }, }, - -- RenderableGlobe module { Name = "Mercury", @@ -37,13 +36,19 @@ return { CameraMinHeight = 300, InteractionDepthBelowEllipsoid = 0, -- Useful when having negative height map values SegmentsPerPatch = 64, - TextureInitData = { - ColorTextureMinimumSize = 512, - OverlayMinimumSize = 512, - HeightMapMinimumSize = 64, - }, - Textures = { - ColorTextures = { + Layers = { + ColorLayers = { + { + Name = "Simple Texture", + FilePath = "textures/mercury.jpg", + Enabled = true, + MinimumPixelSize = 256, + }, + { + Name = "Messenger_Mosaic", + FilePath = "map_service_configs/Utah/MessengerMosaic.wms" + } + --[[ { Name = "On Mercury Color", FilePath = "map_service_configs/OnMercuryColor.xml", @@ -53,35 +58,44 @@ return { Name = "On Mercury Image", FilePath = "map_service_configs/OnMercuryImage.xml", }, + ]] }, - GrayScaleOverlays = { }, - NightTextures = { }, + GrayScaleLayers = { + { + Name = "Messenger_MDIS", + FilePath = "map_service_configs/Utah/MessengerMDIS.wms" + } + }, + GrayScaleColorOverlays = { }, + NightLayers = { }, WaterMasks = { }, - Overlays = { }, - HeightMaps = { + ColorOverlays = { }, + HeightLayers = { + --[[ { Name = "On Mercury Height", FilePath = "map_service_configs/OnMercuryElevationGaskell.xml", Enabled = true, }, + ]] }, }, }, }, - - -- MercuryTrail module + -- Trail module { Name = "MercuryTrail", Parent = "SolarSystemBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "MERCURY", - Frame = "GALACTIC", - Observer = "SUN", - RGB = {0.6, 0.5, 0.5 }, - TropicalOrbitPeriod = 87.968 , - EarthOrbitRatio = 0.241, - DayLength = 4222.6, - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "MERCURY", + Observer = "SUN", + }, + Color = {0.6, 0.5, 0.5 }, + Period = 87.968, + Resolution = 100 + } } } diff --git a/data/scene/debugglobe/map_service_configs/mercury/OnMercuryColor.xml b/data/scene/lodglobes/mercury/map_service_configs/OnMercuryColor.xml similarity index 100% rename from data/scene/debugglobe/map_service_configs/mercury/OnMercuryColor.xml rename to data/scene/lodglobes/mercury/map_service_configs/OnMercuryColor.xml diff --git a/data/scene/debugglobe/map_service_configs/mercury/OnMercuryElevationGaskell.xml b/data/scene/lodglobes/mercury/map_service_configs/OnMercuryElevationGaskell.xml similarity index 100% rename from data/scene/debugglobe/map_service_configs/mercury/OnMercuryElevationGaskell.xml rename to data/scene/lodglobes/mercury/map_service_configs/OnMercuryElevationGaskell.xml diff --git a/data/scene/debugglobe/map_service_configs/mercury/OnMercuryImage.xml b/data/scene/lodglobes/mercury/map_service_configs/OnMercuryImage.xml similarity index 100% rename from data/scene/debugglobe/map_service_configs/mercury/OnMercuryImage.xml rename to data/scene/lodglobes/mercury/map_service_configs/OnMercuryImage.xml diff --git a/data/scene/lodesritest/mercury/MessengerMdis.wms b/data/scene/lodglobes/mercury/map_service_configs/Utah/MessengerMdis.wms similarity index 78% rename from data/scene/lodesritest/mercury/MessengerMdis.wms rename to data/scene/lodglobes/mercury/map_service_configs/Utah/MessengerMdis.wms index bafca5ca07..5b5a765ef4 100644 --- a/data/scene/lodesritest/mercury/MessengerMdis.wms +++ b/data/scene/lodglobes/mercury/map_service_configs/Utah/MessengerMdis.wms @@ -1,14 +1,14 @@ - http://planetarydev-1803629091.us-west-2.elb.amazonaws.com/Mercury/MessengerMdis/tile/${z}/${y}/${x} + http://asgard.sci.utah.edu/Mercury/MessengerMdis/tile/${z}/${y}/${x} -180.0 90.0 180.0 -90.0 - 61324 - 30662 + 61324 + 30662 7 top @@ -17,4 +17,4 @@ 256 1 10 - + \ No newline at end of file diff --git a/data/scene/lodesritest/mercury/MessengerMosaic.wms b/data/scene/lodglobes/mercury/map_service_configs/Utah/MessengerMosaic.wms similarity index 78% rename from data/scene/lodesritest/mercury/MessengerMosaic.wms rename to data/scene/lodglobes/mercury/map_service_configs/Utah/MessengerMosaic.wms index 89415f373e..9152deb1e0 100644 --- a/data/scene/lodesritest/mercury/MessengerMosaic.wms +++ b/data/scene/lodglobes/mercury/map_service_configs/Utah/MessengerMosaic.wms @@ -1,14 +1,14 @@ - http://planetarydev-1803629091.us-west-2.elb.amazonaws.com/Mercury/MessengerMosaic/tile/${z}/${y}/${x} + http://asgard.sci.utah.edu/Mercury/MessengerMosaic/tile/${z}/${y}/${x} -180.0 90.0 180.0 -90.0 - 23054 - 11527 + 23054 + 11527 6 top @@ -17,4 +17,4 @@ 256 3 10 - + \ No newline at end of file diff --git a/data/scene/lodglobes/mercury/mercury.data b/data/scene/lodglobes/mercury/mercury.data new file mode 100644 index 0000000000..f2df36620b --- /dev/null +++ b/data/scene/lodglobes/mercury/mercury.data @@ -0,0 +1,5 @@ +return { + FileRequest = { + { Identifier = "mercury_textures", Destination = "textures", Version = 1 } + }, +} \ No newline at end of file diff --git a/data/scene/debugglobe/map_service_configs/moon/OnMoonColor.xml b/data/scene/lodglobes/moon/map_service_configs/OnMoonColor.xml similarity index 100% rename from data/scene/debugglobe/map_service_configs/moon/OnMoonColor.xml rename to data/scene/lodglobes/moon/map_service_configs/OnMoonColor.xml diff --git a/data/scene/debugglobe/map_service_configs/moon/OnMoonHeight.xml b/data/scene/lodglobes/moon/map_service_configs/OnMoonHeight.xml similarity index 90% rename from data/scene/debugglobe/map_service_configs/moon/OnMoonHeight.xml rename to data/scene/lodglobes/moon/map_service_configs/OnMoonHeight.xml index 4c19299b75..9fe0516d15 100644 --- a/data/scene/debugglobe/map_service_configs/moon/OnMoonHeight.xml +++ b/data/scene/lodglobes/moon/map_service_configs/OnMoonHeight.xml @@ -16,6 +16,4 @@ 1 top - 512 - 512 \ No newline at end of file diff --git a/data/scene/lodesritest/moon/ClemUvvis.wms b/data/scene/lodglobes/moon/map_service_configs/Utah/ClemUvvis.wms similarity index 78% rename from data/scene/lodesritest/moon/ClemUvvis.wms rename to data/scene/lodglobes/moon/map_service_configs/Utah/ClemUvvis.wms index 720b1d84f8..3340bb4fe7 100644 --- a/data/scene/lodesritest/moon/ClemUvvis.wms +++ b/data/scene/lodglobes/moon/map_service_configs/Utah/ClemUvvis.wms @@ -1,14 +1,14 @@ - http://planetarydev-1803629091.us-west-2.elb.amazonaws.com/Moon/ClemUvvis/tile/${z}/${y}/${x} + http://asgard.sci.utah.edu/Moon/ClemUvvis/tile/${z}/${y}/${x} -180.0 90.0 180.0 -90.0 - 92160 - 46080 + 92160 + 46080 7 top @@ -17,4 +17,4 @@ 360 1 10 - + \ No newline at end of file diff --git a/data/scene/lodesritest/moon/Kaguya.wms b/data/scene/lodglobes/moon/map_service_configs/Utah/Kaguya.wms similarity index 74% rename from data/scene/lodesritest/moon/Kaguya.wms rename to data/scene/lodglobes/moon/map_service_configs/Utah/Kaguya.wms index 943f19c400..2e64c499ef 100644 --- a/data/scene/lodesritest/moon/Kaguya.wms +++ b/data/scene/lodglobes/moon/map_service_configs/Utah/Kaguya.wms @@ -1,14 +1,14 @@ - http://planetarydev-1803629091.us-west-2.elb.amazonaws.com/Moon/Kaguya/tile/${z}/${y}/${x} + http://asgard.sci.utah.edu/Moon/Kaguya/tile/${z}/${y}/${x} - -180.0 + -180.0 90.0 180.0 -90.0 - 1474560 - 737280 + 1474560 + 737280 11 top @@ -17,4 +17,4 @@ 360 1 10 - + \ No newline at end of file diff --git a/data/scene/lodesritest/moon/LolaClrShade.wms b/data/scene/lodglobes/moon/map_service_configs/Utah/LolaClrShade.wms similarity index 78% rename from data/scene/lodesritest/moon/LolaClrShade.wms rename to data/scene/lodglobes/moon/map_service_configs/Utah/LolaClrShade.wms index 5183f19b9e..82f9289f36 100644 --- a/data/scene/lodesritest/moon/LolaClrShade.wms +++ b/data/scene/lodglobes/moon/map_service_configs/Utah/LolaClrShade.wms @@ -1,14 +1,14 @@ - http://planetarydev-1803629091.us-west-2.elb.amazonaws.com/Moon/LolaClrShade/tile/${z}/${y}/${x} + http://asgard.sci.utah.edu/Moon/LolaClrShade/tile/${z}/${y}/${x} -180.0 90.0 180.0 -90.0 - 92160 - 46080 + 92160 + 46080 7 top @@ -17,4 +17,4 @@ 360 3 10 - + \ No newline at end of file diff --git a/data/scene/lodesritest/moon/LolaDem.wms b/data/scene/lodglobes/moon/map_service_configs/Utah/LolaDem.wms similarity index 76% rename from data/scene/lodesritest/moon/LolaDem.wms rename to data/scene/lodglobes/moon/map_service_configs/Utah/LolaDem.wms index 7e590c7de6..1ef0f4be0e 100644 --- a/data/scene/lodesritest/moon/LolaDem.wms +++ b/data/scene/lodglobes/moon/map_service_configs/Utah/LolaDem.wms @@ -1,14 +1,14 @@ - http://planetarydev-1803629091.us-west-2.elb.amazonaws.com/Moon/LolaDem/tile/${z}/${y}/${x} + http://asgard.sci.utah.edu/Moon/LolaDem/tile/${z}/${y}/${x} -180.0 90.0 180.0 -90.0 - 92160 - 46080 + 92160 + 46080 7 top @@ -16,6 +16,5 @@ 360 360 1 - Int16 10 - + \ No newline at end of file diff --git a/data/scene/lodesritest/moon/LolaShade.wms b/data/scene/lodglobes/moon/map_service_configs/Utah/LolaShade.wms similarity index 78% rename from data/scene/lodesritest/moon/LolaShade.wms rename to data/scene/lodglobes/moon/map_service_configs/Utah/LolaShade.wms index 7fc994d1fb..4d25cf262f 100644 --- a/data/scene/lodesritest/moon/LolaShade.wms +++ b/data/scene/lodglobes/moon/map_service_configs/Utah/LolaShade.wms @@ -1,14 +1,14 @@ - http://planetarydev-1803629091.us-west-2.elb.amazonaws.com/Moon/LolaShade/tile/${z}/${y}/${x} + http://asgard.sci.utah.edu/Moon/LolaShade/tile/${z}/${y}/${x} -180.0 90.0 180.0 -90.0 - 92160 - 46080 + 92160 + 46080 7 top @@ -17,4 +17,4 @@ 360 1 10 - + \ No newline at end of file diff --git a/data/scene/lodesritest/moon/UvvisHybrid.wms b/data/scene/lodglobes/moon/map_service_configs/Utah/UvvisHybrid.wms similarity index 78% rename from data/scene/lodesritest/moon/UvvisHybrid.wms rename to data/scene/lodglobes/moon/map_service_configs/Utah/UvvisHybrid.wms index 579cfe5f63..2b9a199ba6 100644 --- a/data/scene/lodesritest/moon/UvvisHybrid.wms +++ b/data/scene/lodglobes/moon/map_service_configs/Utah/UvvisHybrid.wms @@ -1,14 +1,14 @@ - http://planetarydev-1803629091.us-west-2.elb.amazonaws.com/Moon/UvvisHybrid/tile/${z}/${y}/${x} + http://asgard.sci.utah.edu/Moon/UvvisHybrid/tile/${z}/${y}/${x} -180.0 90.0 180.0 -90.0 - 184320 - 92160 + 184320 + 92160 8 top @@ -17,4 +17,4 @@ 360 1 10 - + \ No newline at end of file diff --git a/data/scene/lodesritest/moon/Wac.wms b/data/scene/lodglobes/moon/map_service_configs/Utah/Wac.wms similarity index 79% rename from data/scene/lodesritest/moon/Wac.wms rename to data/scene/lodglobes/moon/map_service_configs/Utah/Wac.wms index 498a6dcf18..1085bbda66 100644 --- a/data/scene/lodesritest/moon/Wac.wms +++ b/data/scene/lodglobes/moon/map_service_configs/Utah/Wac.wms @@ -1,14 +1,14 @@ - http://planetarydev-1803629091.us-west-2.elb.amazonaws.com/Moon/Wac/tile/${z}/${y}/${x} + http://asgard.sci.utah.edu/Moon/Wac/tile/${z}/${y}/${x} -180.0 90.0 180.0 -90.0 - 109164 - 54582 + 109164 + 54582 8 top @@ -17,4 +17,4 @@ 256 1 10 - + \ No newline at end of file diff --git a/data/scene/lodglobes/moon/moon.data b/data/scene/lodglobes/moon/moon.data new file mode 100644 index 0000000000..f8c7094165 --- /dev/null +++ b/data/scene/lodglobes/moon/moon.data @@ -0,0 +1,5 @@ +return { + FileRequest = { + { Identifier = "moon_textures", Destination = "textures", Version = 1 } + }, +} \ No newline at end of file diff --git a/data/scene/lodmoon/lodmoon.mod b/data/scene/lodglobes/moon/moon.mod similarity index 50% rename from data/scene/lodmoon/lodmoon.mod rename to data/scene/lodglobes/moon/moon.mod index d295f114f9..54c525ea6d 100644 --- a/data/scene/lodmoon/lodmoon.mod +++ b/data/scene/lodglobes/moon/moon.mod @@ -5,7 +5,7 @@ return { Parent = "EarthBarycenter", Transform = { Translation = { - Type = "SpiceEphemeris", + Type = "SpiceTranslation", Body = "MOON", Observer = "EARTH BARYCENTER", Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" @@ -18,42 +18,56 @@ return { }, Renderable = { Type = "RenderableGlobe", - Radii = {1737000, 1737000, 1737000}, -- Moons's radius + Radii = {1738140, 1738140, 1735970}, -- Moons's radius CameraMinHeight = 300, InteractionDepthBelowEllipsoid = 5000, -- Useful when having negative height map values SegmentsPerPatch = 64, - TextureInitData = { - ColorTextureMinimumSize = 512,--512, - OverlayMinimumSize = 512, - HeightMapMinimumSize = 64, - }, - Textures = { - ColorTextures = { + Layers = { + ColorLayers = { + }, - GrayScaleOverlays = { - --[[ + GrayScaleColorOverlays = { + + }, + GrayScaleLayers = { { Name = "OnMoonColorGrayscale", - FilePath = "map_service_configs/OnMoonGrayscaleOverlay.vrt", + FilePath = "map_service_configs/OnMoonColor.xml", Enabled = true, }, - ]] + { + Name = "ClemUvvis", + FilePath = "map_service_configs/Utah/ClemUvvis.wms" + }, + { + Name = "Kaguya", + FilePath = "map_service_configs/Utah/Kaguya.wms" + }, + { + Name = "WAC", + FilePath = "map_service_configs/Utah/Wac.wms" + } }, - NightTextures = { + NightLayers = { }, WaterMasks = { }, - Overlays = { + ColorOverlays = { }, - HeightMaps = { + HeightLayers = { { Name = "OnMoonHeight", FilePath = "map_service_configs/OnMoonHeight.xml", Enabled = true, + DoPreProcessing = true, }, + { + Name = "LolaDem", + FilePath = "map_service_configs/Utah/LolaDem.wms" + } }, }, } @@ -63,14 +77,15 @@ return { Name = "MoonTrail", Parent = "EarthBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "MOON", - Frame = "GALACTIC", - Observer = "EARTH BARYCENTER", - RGB = { 0.5, 0.3, 0.3 }, - TropicalOrbitPeriod = 60, - EarthOrbitRatio = 0.01, - DayLength = 1.0, - } + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "MOON", + Observer = "EARTH BARYCENTER", + }, + Color = { 0.5, 0.3, 0.3 }, + Period = 27, + Resolution = 1000 + }, } } diff --git a/data/scene/lodglobes/neptune/neptune.data b/data/scene/lodglobes/neptune/neptune.data new file mode 100644 index 0000000000..60b294047e --- /dev/null +++ b/data/scene/lodglobes/neptune/neptune.data @@ -0,0 +1,5 @@ +return { + FileRequest = { + { Identifier = "neptune_textures", Destination = "textures", Version = 1 } + }, +} \ No newline at end of file diff --git a/data/scene/lodglobes/neptune/neptune.mod b/data/scene/lodglobes/neptune/neptune.mod new file mode 100644 index 0000000000..9f3c9f854f --- /dev/null +++ b/data/scene/lodglobes/neptune/neptune.mod @@ -0,0 +1,71 @@ +return { + -- Barycenter module + { + Name = "NeptuneBarycenter", + Parent = "SolarSystemBarycenter", + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "NEPTUNE BARYCENTER", + Observer = "SUN", + Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" + }, + }, + }, + -- RenderableGlobe module + { + Name = "Neptune", + Parent = "NeptuneBarycenter", + Transform = { + Rotation = { + Type = "SpiceRotation", + SourceFrame = "IAU_NEPTUNE", + DestinationFrame = "GALACTIC", + }, + Scale = { + Type = "StaticScale", + Scale = 1, + }, + -- No translation, Neptune is in its barycenter + }, + Renderable = { + Type = "RenderableGlobe", + Radii = {24764000, 24764000, 24314000}, + CameraMinHeight = 300, + InteractionDepthBelowEllipsoid = 0, -- Useful when having negative height map values + SegmentsPerPatch = 64, + Layers = { + ColorLayers = { + { + Name = "Texture", + FilePath = "textures/neptune.jpg", + Enabled = true, + MinimumPixelSize = 256, + }, + }, + GrayScaleLayers = { }, + GrayScaleColorOverlays = { }, + NightLayers = { }, + WaterMasks = { }, + ColorOverlays = { }, + HeightLayers = { }, + }, + }, + }, + -- Trail module + { + Name = "NeptuneTrail", + Parent = "SolarSystemBarycenter", + Renderable = { + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "NEPTUNE BARYCENTER", + Observer = "SUN", + }, + Color = {0.2, 0.5, 1.0 }, + Period = 60200, + Resolution = 1000 + }, + } +} diff --git a/data/scene/saturn/saturn.data b/data/scene/lodglobes/saturn/saturn.data similarity index 55% rename from data/scene/saturn/saturn.data rename to data/scene/lodglobes/saturn/saturn.data index 49ba7a71da..cf0748dfc1 100644 --- a/data/scene/saturn/saturn.data +++ b/data/scene/lodglobes/saturn/saturn.data @@ -2,4 +2,7 @@ return { FileRequest = { { Identifier = "saturn_textures", Destination = "textures", Version = 2 } }, + TorrentFiles = { + { File = "sat375.bsp.torrent", Destination = "${SPICE}" }, + } } \ No newline at end of file diff --git a/data/scene/lodglobes/saturn/saturn.mod b/data/scene/lodglobes/saturn/saturn.mod new file mode 100644 index 0000000000..6ce3287d0e --- /dev/null +++ b/data/scene/lodglobes/saturn/saturn.mod @@ -0,0 +1,81 @@ +return { + -- Barycenter module + { + Name = "SaturnBarycenter", + Parent = "SolarSystemBarycenter", + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "SATURN BARYCENTER", + Observer = "SUN", + Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" + }, + }, + }, + -- RenderableGlobe module + { + Name = "Saturn", + Parent = "SaturnBarycenter", + Transform = { + Rotation = { + Type = "SpiceRotation", + SourceFrame = "IAU_SATURN", + DestinationFrame = "GALACTIC", + }, + Scale = { + Type = "StaticScale", + Scale = 1, + }, + -- No translation, Saturn is in its barycenter + }, + Renderable = { + Type = "RenderableGlobe", + Radii = {60268000, 60268000, 54364000}, + CameraMinHeight = 300, + InteractionDepthBelowEllipsoid = 0, -- Useful when having negative height map values + SegmentsPerPatch = 64, + Layers = { + ColorLayers = { + { + Name = "Saturn Texture", + FilePath = "textures/saturn.jpg", + Enabled = true, + MinimumPixelSize = 256, + }, + }, + GrayScaleLayers = { }, + GrayScaleColorOverlays = { }, + NightLayers = { }, + WaterMasks = { }, + ColorOverlays = { }, + HeightLayers = { }, + }, + }, + }, + { + Name = "SaturnRings", + Parent = "Saturn", + Renderable = { + Type = "RenderableRings", + Texture = "textures/saturn_rings.png", + Size = 140220000, + Offset = { 74500 / 140445.100671159, 1.0 } -- min / max extend + }, + }, + -- Trail module + { + Name = "SaturnTrail", + Parent = "SolarSystemBarycenter", + Renderable = { + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "SATURN BARYCENTER", + Observer = "SUN", + }, + Color = {0.85,0.75,0.51 }, + Period = 10746.94, + Resolution = 1000 + }, + } +} diff --git a/data/scene/lodglobes/uranus/uranus.data b/data/scene/lodglobes/uranus/uranus.data new file mode 100644 index 0000000000..1260617597 --- /dev/null +++ b/data/scene/lodglobes/uranus/uranus.data @@ -0,0 +1,5 @@ +return { + FileRequest = { + { Identifier = "uranus_textures", Destination = "textures", Version = 1 } + }, +} \ No newline at end of file diff --git a/data/scene/lodglobes/uranus/uranus.mod b/data/scene/lodglobes/uranus/uranus.mod new file mode 100644 index 0000000000..9825a16459 --- /dev/null +++ b/data/scene/lodglobes/uranus/uranus.mod @@ -0,0 +1,71 @@ +return { + -- Barycenter module + { + Name = "UranusBarycenter", + Parent = "SolarSystemBarycenter", + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "URANUS BARYCENTER", + Observer = "SUN", + Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" + }, + }, + }, + -- RenderableGlobe module + { + Name = "Uranus", + Parent = "UranusBarycenter", + Transform = { + Rotation = { + Type = "SpiceRotation", + SourceFrame = "IAU_URANUS", + DestinationFrame = "GALACTIC", + }, + Scale = { + Type = "StaticScale", + Scale = 1, + }, + -- No translation, Uranus is in its barycenter + }, + Renderable = { + Type = "RenderableGlobe", + Radii = {25559000, 25559000, 24973000}, + CameraMinHeight = 300, + InteractionDepthBelowEllipsoid = 0, -- Useful when having negative height map values + SegmentsPerPatch = 64, + Layers = { + ColorLayers = { + { + Name = "Texture", + FilePath = "textures/uranus.jpg", + Enabled = true, + MinimumPixelSize = 256, + }, + }, + GrayScaleLayers = { }, + GrayScaleColorOverlays = { }, + NightLayers = { }, + WaterMasks = { }, + ColorOverlays = { }, + HeightLayers = { }, + }, + }, + }, + -- Trail module + { + Name = "UranusTrail", + Parent = "SolarSystemBarycenter", + Renderable = { + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "URANUS BARYCENTER", + Observer = "SUN", + }, + Color = {0.60, 0.95, 1.00 }, + Period = 30588.740, + Resolution = 1000 + }, + } +} diff --git a/data/scene/lodglobes/venus/venus.data b/data/scene/lodglobes/venus/venus.data new file mode 100644 index 0000000000..07753359f6 --- /dev/null +++ b/data/scene/lodglobes/venus/venus.data @@ -0,0 +1,5 @@ +return { + FileRequest = { + { Identifier = "venus_textures", Destination = "textures", Version = 1 } + }, +} \ No newline at end of file diff --git a/data/scene/lodglobes/venus/venus.mod b/data/scene/lodglobes/venus/venus.mod new file mode 100644 index 0000000000..ba6e050a33 --- /dev/null +++ b/data/scene/lodglobes/venus/venus.mod @@ -0,0 +1,76 @@ +return { + -- Barycenter module + { + Name = "VenusBarycenter", + Parent = "SolarSystemBarycenter", + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "VENUS BARYCENTER", + Observer = "SUN", + Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" + }, + }, + }, + -- RenderableGlobe module + { + Name = "Venus", + Parent = "VenusBarycenter", + Transform = { + Rotation = { + Type = "SpiceRotation", + SourceFrame = "IAU_VENUS", + DestinationFrame = "GALACTIC", + }, + Scale = { + Type = "StaticScale", + Scale = 1, + }, + Translation = { + Type = "SpiceTranslation", + Body = "VENUS", + Observer = "VENUS BARYCENTER", + Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" + }, + }, + Renderable = { + Type = "RenderableGlobe", + Radii = {6051900, 6051900, 6051800}, + CameraMinHeight = 300, + InteractionDepthBelowEllipsoid = 0, -- Useful when having negative height map values + SegmentsPerPatch = 64, + Layers = { + ColorLayers = { + { + Name = "Venus Texture", + FilePath = "textures/venus.jpg", + Enabled = true, + MinimumPixelSize = 256, + }, + }, + GrayScaleLayers = { }, + GrayScaleColorOverlays = { }, + NightLayers = { }, + WaterMasks = { }, + ColorOverlays = { }, + HeightLayers = { }, + }, + }, + }, + -- Trail module + { + Name = "VenusTrail", + Parent = "SolarSystemBarycenter", + Renderable = { + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "VENUS BARYCENTER", + Observer = "SUN", + }, + Color = { 1.0, 0.5, 0.2 }, + Period = 224.695, + Resolution = 1000 + }, + } +} diff --git a/data/scene/lodmars/map_service_configs/CTX_Mosaic.xml b/data/scene/lodmars/map_service_configs/CTX_Mosaic.xml deleted file mode 100644 index 9f7a65afb5..0000000000 --- a/data/scene/lodmars/map_service_configs/CTX_Mosaic.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - http://192.168.1.167/OnMars/wms.cgi? - CTX Mosaic - TRUE - - - -180.0 - 90.0 - 180.0 - -90.0 - 256 - 256 - - \ No newline at end of file diff --git a/data/scene/lodmercury/map_service_configs/OnMercuryColor.xml b/data/scene/lodmercury/map_service_configs/OnMercuryColor.xml deleted file mode 100644 index d53cb3ad5e..0000000000 --- a/data/scene/lodmercury/map_service_configs/OnMercuryColor.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - http://192.168.1.167/OnMercury/wms.cgi? - Color 665m - - - - -180.0 - 90 - 180.0 - -90 - 20 - 2 - 1 - top - - 512 - 512 - \ No newline at end of file diff --git a/data/scene/lodmercury/map_service_configs/OnMercuryElevationGaskell.xml b/data/scene/lodmercury/map_service_configs/OnMercuryElevationGaskell.xml deleted file mode 100644 index 0563b2d018..0000000000 --- a/data/scene/lodmercury/map_service_configs/OnMercuryElevationGaskell.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - http://192.168.1.167/OnMercury/wms.cgi? - - Elevation 16bit, Gaskell - - - -180.0 - 90 - 180.0 - -90 - 8 - 2 - 1 - top - - 512 - 512 - \ No newline at end of file diff --git a/data/scene/lodmercury/map_service_configs/OnMercuryImage.xml b/data/scene/lodmercury/map_service_configs/OnMercuryImage.xml deleted file mode 100644 index d50931e40e..0000000000 --- a/data/scene/lodmercury/map_service_configs/OnMercuryImage.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - http://192.168.1.167/OnMercury/wms.cgi? - Mercury Image - - - - -180.0 - 90 - 180.0 - -90 - 20 - 2 - 1 - top - - 512 - 512 - \ No newline at end of file diff --git a/data/scene/lodmoon/map_service_configs/OnMoonColor.xml b/data/scene/lodmoon/map_service_configs/OnMoonColor.xml deleted file mode 100644 index 5ba619a141..0000000000 --- a/data/scene/lodmoon/map_service_configs/OnMoonColor.xml +++ /dev/null @@ -1,65 +0,0 @@ - - - http://onmoon.lmmp.nasa.gov/wms.cgi? - LRO WAC Mosaic, LMMP - - - - - - -180.0 - 90 - 180.0 - -90 - 20 - 2 - 1 - top - - 512 - 512 - \ No newline at end of file diff --git a/data/scene/lodmoon/map_service_configs/OnMoonGrayscaleOverlay.vrt b/data/scene/lodmoon/map_service_configs/OnMoonGrayscaleOverlay.vrt deleted file mode 100644 index 6959072a78..0000000000 --- a/data/scene/lodmoon/map_service_configs/OnMoonGrayscaleOverlay.vrt +++ /dev/null @@ -1,28 +0,0 @@ - - GEOGCS["GCS_Moon_2000",DATUM["D_Moon_2000",SPHEROID["Moon_2000_IAU_IAG",1737400.0,0.0]],PRIMEM["Reference_Meridian",0.0],UNIT["Degree",0.0174532925199433]] - -1.8000000000000000e+02, 2.1972656250000000e-03, 0.0000000000000000e+00, 9.0000000000000000e+01, 0.0000000000000000e+00, -2.1972656250000000e-03 - - 0 - 1 - Gray - - OnMoonColor.xml - 1 - - - - 0 - - - - Alpha - - white_geo.tif - 1 - - - - - - - diff --git a/data/scene/lodmoon/map_service_configs/OnMoonHeight.xml b/data/scene/lodmoon/map_service_configs/OnMoonHeight.xml deleted file mode 100644 index 4c19299b75..0000000000 --- a/data/scene/lodmoon/map_service_configs/OnMoonHeight.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - http://onmoon.lmmp.nasa.gov/raw/wms.cgi? - Lunar Elevation v2, half meters - - - - -180.0 - 90 - 180.0 - -90 - 24 - 2 - 1 - top - - 512 - 512 - \ No newline at end of file diff --git a/data/scene/lodmoon/map_service_configs/OnMoonNight.vrt b/data/scene/lodmoon/map_service_configs/OnMoonNight.vrt deleted file mode 100644 index 0741ac74c3..0000000000 --- a/data/scene/lodmoon/map_service_configs/OnMoonNight.vrt +++ /dev/null @@ -1,49 +0,0 @@ - - GEOGCS["GCS_Moon_2000",DATUM["D_Moon_2000",SPHEROID["Moon_2000_IAU_IAG",1737400.0,0.0]],PRIMEM["Reference_Meridian",0.0],UNIT["Degree",0.0174532925199433]] - -1.8000000000000000e+02, 2.1972656250000000e-03, 0.0000000000000000e+00, 9.0000000000000000e+01, 0.0000000000000000e+00, -2.1972656250000000e-03 - - 0 - 1 - Red - - OnMoonColor.xml - 1 - - - - 0 - 16 - 0 - - - - 0 - 1 - Green - - OnMoonColor.xml - 1 - - - - 0 - 16 - 0 - - - - 0 - 1 - Blue - - OnMoonColor.xml - 1 - - - - 0 - 16 - 0 - - - diff --git a/data/scene/mars/mars.mod b/data/scene/mars/mars.mod index 20dc40c5ea..54e33cbd6c 100644 --- a/data/scene/mars/mars.mod +++ b/data/scene/mars/mars.mod @@ -3,6 +3,14 @@ return { { Name = "MarsBarycenter", Parent = "SolarSystemBarycenter", + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "MARS BARYCENTER", + Observer = "SUN", + Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" + } + } }, -- Mars module { @@ -28,41 +36,27 @@ return { } }, Transform = { - Translation = { - Type = "SpiceEphemeris", - Body = "MARS BARYCENTER", - Observer = "SUN", - Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" - }, Rotation = { Type = "SpiceRotation", SourceFrame = "IAU_MARS", - DestinationFrame = "ECLIPJ2000", - }, - Scale = { - Type = "StaticScale", - Scale = 1, + DestinationFrame = "GALACTIC", }, } }, -- MarsTrail module { Name = "MarsTrail", - Parent = "MarsBarycenter", + Parent = "SolarSystemBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "MARS BARYCENTER", - Frame = "GALACTIC", - Observer = "SUN", - RGB = { 1, 0.8, 0.5 }, - TropicalOrbitPeriod = 686.973, - EarthOrbitRatio = 1.881, - DayLength = 24.6597, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "MARS BARYCENTER", + Observer = "SUN", + }, + Color = { 0.814, 0.305, 0.220 }, + Period = 686.973, + Resolution = 1000 } } } diff --git a/data/scene/mercury/mercury.mod b/data/scene/mercury/mercury.mod index caacb59af8..75bf33560e 100644 --- a/data/scene/mercury/mercury.mod +++ b/data/scene/mercury/mercury.mod @@ -3,6 +3,14 @@ return { { Name = "MercuryBarycenter", Parent = "SolarSystemBarycenter", + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "MERCURY BARYCENTER", + Observer = "SUN", + Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" + }, + } }, -- Mercury module { @@ -28,12 +36,6 @@ return { } }, Transform = { - Translation = { - Type = "SpiceEphemeris", - Body = "MERCURY", - Observer = "SUN", - Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" - }, Rotation = { Type = "SpiceRotation", SourceFrame = "IAU_MERCURY", @@ -48,21 +50,17 @@ return { -- MercuryTrail module { Name = "MercuryTrail", - Parent = "MercuryBarycenter", + Parent = "SolarSystemBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "MERCURY", - Frame = "GALACTIC", - Observer = "SUN", - RGB = {0.6, 0.5, 0.5 }, - TropicalOrbitPeriod = 87.968 , - EarthOrbitRatio = 0.241, - DayLength = 4222.6, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "MERCURY", + Observer = "SUN", + }, + Color = {0.6, 0.5, 0.5 }, + Period = 87.968, + Resolution = 100 } } } diff --git a/data/scene/milkyway-eso/milkyway-eso.mod b/data/scene/milkyway-eso/milkyway-eso.mod index 0a080a28d5..86902a48e7 100644 --- a/data/scene/milkyway-eso/milkyway-eso.mod +++ b/data/scene/milkyway-eso/milkyway-eso.mod @@ -1,6 +1,6 @@ return { { - Name = "MilkyWay", + Name = "MilkyWay (ESO)", Parent = "SolarSystem", Renderable = { Type = "RenderableSphere", diff --git a/data/scene/milkyway/milkyway.data b/data/scene/milkyway/milkyway.data index 0c5cc5bcd6..c877e629c9 100644 --- a/data/scene/milkyway/milkyway.data +++ b/data/scene/milkyway/milkyway.data @@ -1,5 +1,5 @@ return { FileRequest = { - { Identifier = "milkyway_textures", Destination = "textures", Version = 1 } + { Identifier = "milkyway_textures", Destination = "textures", Version = 2 } }, } \ No newline at end of file diff --git a/data/scene/dawn/ceres/DawnKernels.torrent b/data/scene/missions/dawn/ceres/DawnKernels.torrent similarity index 100% rename from data/scene/dawn/ceres/DawnKernels.torrent rename to data/scene/missions/dawn/ceres/DawnKernels.torrent diff --git a/data/scene/dawn/ceres/ceres.data b/data/scene/missions/dawn/ceres/ceres.data similarity index 100% rename from data/scene/dawn/ceres/ceres.data rename to data/scene/missions/dawn/ceres/ceres.data diff --git a/data/scene/dawn/ceres/ceres.mod b/data/scene/missions/dawn/ceres/ceres.mod similarity index 100% rename from data/scene/dawn/ceres/ceres.mod rename to data/scene/missions/dawn/ceres/ceres.mod diff --git a/data/scene/dawn/dawn/DawnKernels.torrent b/data/scene/missions/dawn/dawn/DawnKernels.torrent similarity index 100% rename from data/scene/dawn/dawn/DawnKernels.torrent rename to data/scene/missions/dawn/dawn/DawnKernels.torrent diff --git a/data/scene/dawn/dawn/dawn.data b/data/scene/missions/dawn/dawn/dawn.data similarity index 100% rename from data/scene/dawn/dawn/dawn.data rename to data/scene/missions/dawn/dawn/dawn.data diff --git a/data/scene/dawn/dawn/dawn.mod b/data/scene/missions/dawn/dawn/dawn.mod similarity index 99% rename from data/scene/dawn/dawn/dawn.mod rename to data/scene/missions/dawn/dawn/dawn.mod index 65e003ac47..3d4a14e917 100644 --- a/data/scene/dawn/dawn/dawn.mod +++ b/data/scene/missions/dawn/dawn/dawn.mod @@ -698,24 +698,18 @@ return { -- Dawn Trail Module { Name = "DawnTrail2", - Parent = "Root", + Parent = "SolarSystemBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "DAWN", - Frame = "GALACTIC", - Observer = "SUN", - -- 3 Dummy values for compilation: - TropicalOrbitPeriod = 10000.0, - EarthOrbitRatio = 1, - DayLength = 50, - -- End of Dummy values - RGB = { 0.7, 0.4, 0.9 }, - Textures = { - Type = "simple", - Color = "textures/glare.png" - }, + Type = "RenderableTrailTrajectory", + Translation = { + Type = "SpiceTranslation", + Body = "DAWN", + Observer = "SUN", + }, + Color = { 0.7, 0.4, 0.9 }, StartTime = "2007 SEP 26 13:28:00", - EndTime = "2012 SEP 12 12:00:00" + EndTime = "2012 SEP 12 12:00:00", + SampleInterval = 3600 * 24 }, }, -- diff --git a/data/scene/dawn/vestaprojection/VestaComet.torrent b/data/scene/missions/dawn/vestaprojection/VestaComet.torrent similarity index 100% rename from data/scene/dawn/vestaprojection/VestaComet.torrent rename to data/scene/missions/dawn/vestaprojection/VestaComet.torrent diff --git a/data/scene/dawn/vestaprojection/vestaprojection.data b/data/scene/missions/dawn/vestaprojection/vestaprojection.data similarity index 100% rename from data/scene/dawn/vestaprojection/vestaprojection.data rename to data/scene/missions/dawn/vestaprojection/vestaprojection.data diff --git a/data/scene/dawn/vestaprojection/vestaprojection.mod b/data/scene/missions/dawn/vestaprojection/vestaprojection.mod similarity index 87% rename from data/scene/dawn/vestaprojection/vestaprojection.mod rename to data/scene/missions/dawn/vestaprojection/vestaprojection.mod index 4de4d75dee..f0b8cc87b6 100644 --- a/data/scene/dawn/vestaprojection/vestaprojection.mod +++ b/data/scene/missions/dawn/vestaprojection/vestaprojection.mod @@ -100,24 +100,16 @@ return { Name = "VestaTrail", Parent = "SolarSystemBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "VESTA", - Frame = "GALACTIC", - Observer = "SUN", - - -- 3 Dummy values for compilation: - TropicalOrbitPeriod = 500.0, - EarthOrbitRatio = 0.2, - DayLength = 2, - -- End of Dummy values - - RGB = { 0.7, 0.8, 0.7 }, - Textures = { - Type = "simple", - Color = "textures/glare.png" - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "VESTA", + Observer = "SUN", + }, + Color = { 0.7, 0.8, 0.7 }, StartTime = "2007 JUL 20 12:00:00", - EndTime = "2018 JAN 22 12:00:00" + EndTime = "2018 JAN 22 12:00:00", + SampleInterval = 3600 * 24 } } } diff --git a/data/scene/juno/juno/juno.mod b/data/scene/missions/juno/juno/juno.mod similarity index 98% rename from data/scene/juno/juno/juno.mod rename to data/scene/missions/juno/juno/juno.mod index ec95c0c83f..12c2d45131 100644 --- a/data/scene/juno/juno/juno.mod +++ b/data/scene/missions/juno/juno/juno.mod @@ -1,144 +1,144 @@ -return { - -- New Horizons Body module - { - Name = "Juno", - -- Parent = "PlutoBarycenter", - -- Parent = "JupiterBarycenter", - Parent = "JupiterBarycenter", - Renderable = { - Type = "RenderableModel", - Body = "JUNO", - Geometry = { - Type = "MultiModelGeometry", - GeometryFile = "Juno.obj", - Magnification = 4, - }, - Textures = { - Type = "simple", - Color = "textures/gray.png", - }, - Rotation = { - Source = "JUNO_SPACECRAFT", - Destination = "GALACTIC", - ModelTransform = { - 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, - 0.0, -1.0, 0.0 - } - }, - }, - - Ephemeris = { - Type = "Spice", - Body = "JUNO", - Observer = "JUPITER BARYCENTER", - Kernels = { - "spice/JNO_SCLKSCET.00039.tsc", - "spice/juno_jade_v00.ti", - "spice/juno_jedi_v00.ti", - "spice/juno_jiram_v01.ti", - "spice/juno_junocam_v00.ti", - "spice/juno_mag_v00.ti", - "spice/juno_mwr_v01.ti", - "spice/juno_struct_v01.ti", - "spice/juno_uvs_v00.ti", - "spice/juno_v08.tf", - "spice/juno_waves_v00.ti", - "spice/juno_mwr_v01.ti", - "spice/spk_merge_110805_171017_130515.bsp", - "spice/ck/juno_sc_prl_110930_111028_jc003c01_v01.bc", - "spice/ck/juno_sc_prl_111028_111125_jc004b00_v01.bc", - "spice/ck/juno_sc_prl_111125_111223_jc005b00_v01.bc", - "spice/ck/juno_sc_prl_111223_120127_jc006a02_v01.bc", - "spice/ck/juno_sc_prl_120127_120217_jc007a00_v01.bc", - "spice/ck/juno_sc_prl_120217_120316_jc008b00_v02.bc", - "spice/ck/juno_sc_prl_120316_120413_jc009a00_v01.bc", - "spice/ck/juno_sc_prl_120413_120511_jc010a04_v01.bc", - "spice/ck/juno_sc_prl_120511_120608_jc011a01_v02.bc", - "spice/ck/juno_sc_prl_120608_120706_jc012b01_v01.bc", - "spice/ck/juno_sc_prl_120706_120802_jc013a01_v01.bc", - "spice/ck/juno_sc_prl_120802_120824_jc014b01_v01.bc", - "spice/ck/juno_sc_prl_120824_120928_jc015m00_v01.bc", - "spice/ck/juno_sc_prl_120919_120928_jc015o00_v01.bc", - "spice/ck/juno_sc_prl_120928_121026_jc016c03_v01.bc", - "spice/ck/juno_sc_prl_121026_121123_jc017a01_v01.bc", - "spice/ck/juno_sc_prl_121123_121221_jc018b01_v01.bc", - "spice/ck/juno_sc_prl_121221_130118_jc019a01_v01.bc", - "spice/ck/juno_sc_prl_130118_130215_jc020b01_v01.bc", - "spice/ck/juno_sc_prl_130315_130412_jc022b01_v01.bc", - "spice/ck/juno_sc_prl_130412_130510_jc023b03_v01.bc", - "spice/ck/juno_sc_prl_130510_130607_jc024a01_v01.bc", - "spice/ck/juno_sc_prl_130607_130705_jc025a00_v01.bc", - "spice/ck/juno_sc_prl_130705_130802_jc026a01_v01.bc", - "spice/ck/juno_sc_prl_130726_131020_jx024a02_EFB_v03.bc", - "spice/ck/juno_sc_prl_130802_130830_jc027a02_v01.bc", - "spice/ck/juno_sc_prl_130830_130927_jc028a01_v01.bc", - "spice/ck/juno_sc_prl_130926_131025_jc029a00_v01.bc", - "spice/ck/juno_sc_prl_130927_131025_jc029c01_v01.bc", - "spice/ck/juno_sc_prl_131022_131025_jc029f00_v01.bc", - "spice/ck/juno_sc_prl_131025_131122_jc030b04_v01.bc", - "spice/ck/juno_sc_prl_131122_131220_jc031b01_v01.bc", - "spice/ck/juno_sc_prl_131220_140124_jc032a01_v01.bc", - "spice/ck/juno_sc_prl_140124_140214_jc033a01_v01.bc", - "spice/ck/juno_sc_prl_140214_140314_jc034b01_v01.bc", - "spice/ck/juno_sc_prl_140314_140411_jc035a01_v01.bc", - "spice/ck/juno_sc_prl_140411_140509_jc036b01_v01.bc", - "spice/ck/juno_sc_prl_140509_140606_jc037b02_v01.bc", - "spice/ck/juno_sc_prl_140606_140704_jc038a01_v01.bc", - "spice/ck/juno_sc_prl_140704_140801_jc039b01_v01.bc", - "spice/ck/juno_sc_prl_140801_140829_jc040a01_v01.bc", - "spice/ck/juno_sc_prl_140829_140926_jc041a01_v01.bc", - "spice/ck/juno_sc_prl_140926_141024_jc042a01_v01.bc", - "spice/ck/juno_sc_prl_141024_141121_jc043a01_v01.bc", - "spice/ck/juno_sc_prl_141105_141121_jc043m01_v01.bc", - "spice/ck/juno_sc_prl_141107_141121_jc043s01_v01.bc", - "spice/ck/juno_sc_prl_141121_141219_jc044a01_v01.bc", - "spice/ck/juno_sc_prl_141219_150123_jc045a01_v01.bc", - "spice/ck/juno_sc_prl_150123_150213_jc046a01_v01.bc", - "spice/ck/juno_sc_prl_150213_150313_jc047a01_v01.bc", - "spice/ck/juno_sc_prl_150312_150409_jc048a01_v01.bc", - "spice/ck/juno_sc_prl_150410_150508_jc049a01_v01.bc", - "spice/ck/juno_sc_prl_150508_150605_jc050a01_v01.bc", - "spice/ck/juno_sc_prl_150605_150703_jc051a01_v01.bc", - "spice/ck/juno_sc_prl_150703_150731_jc052a01_v01.bc", - "spice/ck/juno_sc_prl_150731_150828_jc053a01_v01.bc", - "spice/ck/juno_sc_prl_150805_150828_jc053m00_v01.bc", - "spice/ck/juno_sc_prl_150807_150828_jc053s00_v01.bc", - "spice/ck/juno_sc_prl_150828_150924_jc054a00_v01.bc", - "spice/ck/juno_sc_prl_150924_151023_jc055a00_v01.bc", - "spice/ck/juno_sc_prl_151023_151120_jc056a00_v01.bc", - "spice/ck/juno_sc_prl_151120_151218_jc057a00_v01.bc", - "spice/ck/juno_sc_prl_151218_160115_jc058a00_v01.bc", - "spice/ck/juno_sc_prl_160115_160212_jc059a00_v01.bc", - "spice/ck/juno_sc_prl_160212_160311_jc060a00_v01.bc", - "spice/ck/juno_sc_prl_160311_160408_jc061a00_v01.bc", - "spice/ck/juno_sc_prl_160408_160506_jc062a00_v01.bc", - "spice/ck/juno_sc_prl_160506_160603_jc063a00_v01.bc", - "spice/ck/juno_sc_prl_160603_160630_jc064a00_v01.bc", - "spice/ck/juno_sc_prl_160708_160729_jm0001rp_v02.bc", - "spice/ck/juno_sc_prl_160729_160826_jm0002rp_v01.bc", - "spice/ck/juno_sc_prl_161115_161213_jx0405rp_v01.bc" - } - } - }, - --NewHorizonsTrail module - { - Name = "JunoTrail", - Parent = "JupiterBarycenter", - Renderable = { - Type = "RenderableTrail", - Body = "JUNO", - Frame = "GALACTIC", - Observer = "JUPITER BARYCENTER", - RGB = { 0.70,0.50,0.20 }, - TropicalOrbitPeriod = 394250.0, - EarthOrbitRatio = 4.5, - DayLength = 9.9259, - TimeStamps = false, - Textures = { - Type = "simple", - Color = "textures/glare_blue.png", - }, - }, - }, - } +return { + -- New Horizons Body module + { + Name = "Juno", + -- Parent = "PlutoBarycenter", + -- Parent = "JupiterBarycenter", + Parent = "JupiterBarycenter", + Renderable = { + Type = "RenderableModel", + Body = "JUNO", + Geometry = { + Type = "MultiModelGeometry", + GeometryFile = "Juno.obj", + Magnification = 4, + }, + Textures = { + Type = "simple", + Color = "textures/gray.png", + }, + Rotation = { + Source = "JUNO_SPACECRAFT", + Destination = "GALACTIC", + ModelTransform = { + 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, + 0.0, -1.0, 0.0 + } + }, + }, + + Ephemeris = { + Type = "Spice", + Body = "JUNO", + Observer = "JUPITER BARYCENTER", + Kernels = { + "spice/JNO_SCLKSCET.00039.tsc", + "spice/juno_jade_v00.ti", + "spice/juno_jedi_v00.ti", + "spice/juno_jiram_v01.ti", + "spice/juno_junocam_v00.ti", + "spice/juno_mag_v00.ti", + "spice/juno_mwr_v01.ti", + "spice/juno_struct_v01.ti", + "spice/juno_uvs_v00.ti", + "spice/juno_v08.tf", + "spice/juno_waves_v00.ti", + "spice/juno_mwr_v01.ti", + "spice/spk_merge_110805_171017_130515.bsp", + "spice/ck/juno_sc_prl_110930_111028_jc003c01_v01.bc", + "spice/ck/juno_sc_prl_111028_111125_jc004b00_v01.bc", + "spice/ck/juno_sc_prl_111125_111223_jc005b00_v01.bc", + "spice/ck/juno_sc_prl_111223_120127_jc006a02_v01.bc", + "spice/ck/juno_sc_prl_120127_120217_jc007a00_v01.bc", + "spice/ck/juno_sc_prl_120217_120316_jc008b00_v02.bc", + "spice/ck/juno_sc_prl_120316_120413_jc009a00_v01.bc", + "spice/ck/juno_sc_prl_120413_120511_jc010a04_v01.bc", + "spice/ck/juno_sc_prl_120511_120608_jc011a01_v02.bc", + "spice/ck/juno_sc_prl_120608_120706_jc012b01_v01.bc", + "spice/ck/juno_sc_prl_120706_120802_jc013a01_v01.bc", + "spice/ck/juno_sc_prl_120802_120824_jc014b01_v01.bc", + "spice/ck/juno_sc_prl_120824_120928_jc015m00_v01.bc", + "spice/ck/juno_sc_prl_120919_120928_jc015o00_v01.bc", + "spice/ck/juno_sc_prl_120928_121026_jc016c03_v01.bc", + "spice/ck/juno_sc_prl_121026_121123_jc017a01_v01.bc", + "spice/ck/juno_sc_prl_121123_121221_jc018b01_v01.bc", + "spice/ck/juno_sc_prl_121221_130118_jc019a01_v01.bc", + "spice/ck/juno_sc_prl_130118_130215_jc020b01_v01.bc", + "spice/ck/juno_sc_prl_130315_130412_jc022b01_v01.bc", + "spice/ck/juno_sc_prl_130412_130510_jc023b03_v01.bc", + "spice/ck/juno_sc_prl_130510_130607_jc024a01_v01.bc", + "spice/ck/juno_sc_prl_130607_130705_jc025a00_v01.bc", + "spice/ck/juno_sc_prl_130705_130802_jc026a01_v01.bc", + "spice/ck/juno_sc_prl_130726_131020_jx024a02_EFB_v03.bc", + "spice/ck/juno_sc_prl_130802_130830_jc027a02_v01.bc", + "spice/ck/juno_sc_prl_130830_130927_jc028a01_v01.bc", + "spice/ck/juno_sc_prl_130926_131025_jc029a00_v01.bc", + "spice/ck/juno_sc_prl_130927_131025_jc029c01_v01.bc", + "spice/ck/juno_sc_prl_131022_131025_jc029f00_v01.bc", + "spice/ck/juno_sc_prl_131025_131122_jc030b04_v01.bc", + "spice/ck/juno_sc_prl_131122_131220_jc031b01_v01.bc", + "spice/ck/juno_sc_prl_131220_140124_jc032a01_v01.bc", + "spice/ck/juno_sc_prl_140124_140214_jc033a01_v01.bc", + "spice/ck/juno_sc_prl_140214_140314_jc034b01_v01.bc", + "spice/ck/juno_sc_prl_140314_140411_jc035a01_v01.bc", + "spice/ck/juno_sc_prl_140411_140509_jc036b01_v01.bc", + "spice/ck/juno_sc_prl_140509_140606_jc037b02_v01.bc", + "spice/ck/juno_sc_prl_140606_140704_jc038a01_v01.bc", + "spice/ck/juno_sc_prl_140704_140801_jc039b01_v01.bc", + "spice/ck/juno_sc_prl_140801_140829_jc040a01_v01.bc", + "spice/ck/juno_sc_prl_140829_140926_jc041a01_v01.bc", + "spice/ck/juno_sc_prl_140926_141024_jc042a01_v01.bc", + "spice/ck/juno_sc_prl_141024_141121_jc043a01_v01.bc", + "spice/ck/juno_sc_prl_141105_141121_jc043m01_v01.bc", + "spice/ck/juno_sc_prl_141107_141121_jc043s01_v01.bc", + "spice/ck/juno_sc_prl_141121_141219_jc044a01_v01.bc", + "spice/ck/juno_sc_prl_141219_150123_jc045a01_v01.bc", + "spice/ck/juno_sc_prl_150123_150213_jc046a01_v01.bc", + "spice/ck/juno_sc_prl_150213_150313_jc047a01_v01.bc", + "spice/ck/juno_sc_prl_150312_150409_jc048a01_v01.bc", + "spice/ck/juno_sc_prl_150410_150508_jc049a01_v01.bc", + "spice/ck/juno_sc_prl_150508_150605_jc050a01_v01.bc", + "spice/ck/juno_sc_prl_150605_150703_jc051a01_v01.bc", + "spice/ck/juno_sc_prl_150703_150731_jc052a01_v01.bc", + "spice/ck/juno_sc_prl_150731_150828_jc053a01_v01.bc", + "spice/ck/juno_sc_prl_150805_150828_jc053m00_v01.bc", + "spice/ck/juno_sc_prl_150807_150828_jc053s00_v01.bc", + "spice/ck/juno_sc_prl_150828_150924_jc054a00_v01.bc", + "spice/ck/juno_sc_prl_150924_151023_jc055a00_v01.bc", + "spice/ck/juno_sc_prl_151023_151120_jc056a00_v01.bc", + "spice/ck/juno_sc_prl_151120_151218_jc057a00_v01.bc", + "spice/ck/juno_sc_prl_151218_160115_jc058a00_v01.bc", + "spice/ck/juno_sc_prl_160115_160212_jc059a00_v01.bc", + "spice/ck/juno_sc_prl_160212_160311_jc060a00_v01.bc", + "spice/ck/juno_sc_prl_160311_160408_jc061a00_v01.bc", + "spice/ck/juno_sc_prl_160408_160506_jc062a00_v01.bc", + "spice/ck/juno_sc_prl_160506_160603_jc063a00_v01.bc", + "spice/ck/juno_sc_prl_160603_160630_jc064a00_v01.bc", + "spice/ck/juno_sc_prl_160708_160729_jm0001rp_v02.bc", + "spice/ck/juno_sc_prl_160729_160826_jm0002rp_v01.bc", + "spice/ck/juno_sc_prl_161115_161213_jx0405rp_v01.bc" + } + } + }, + --NewHorizonsTrail module + { + Name = "JunoTrail", + Parent = "JupiterBarycenter", + Renderable = { + Type = "RenderableTrail", + Body = "JUNO", + Frame = "GALACTIC", + Observer = "JUPITER BARYCENTER", + RGB = { 0.70,0.50,0.20 }, + TropicalOrbitPeriod = 394250.0, + EarthOrbitRatio = 4.5, + DayLength = 9.9259, + TimeStamps = false, + Textures = { + Type = "simple", + Color = "textures/glare_blue.png", + }, + }, + }, + } diff --git a/data/scene/missions/newhorizons/jupiter/callisto/callisto.data b/data/scene/missions/newhorizons/jupiter/callisto/callisto.data new file mode 100644 index 0000000000..9c381ecce7 --- /dev/null +++ b/data/scene/missions/newhorizons/jupiter/callisto/callisto.data @@ -0,0 +1,5 @@ +return { + FileRequest = { + { Identifier = "callisto_textures", Destination = "textures", Version = 1 } + }, +} \ No newline at end of file diff --git a/data/scene/newhorizons/jupiter/callisto/callisto.mod b/data/scene/missions/newhorizons/jupiter/callisto/callisto.mod similarity index 63% rename from data/scene/newhorizons/jupiter/callisto/callisto.mod rename to data/scene/missions/newhorizons/jupiter/callisto/callisto.mod index c00cd996e1..acf03fd873 100644 --- a/data/scene/newhorizons/jupiter/callisto/callisto.mod +++ b/data/scene/missions/newhorizons/jupiter/callisto/callisto.mod @@ -22,24 +22,26 @@ return { Observer = "NEW HORIZONS", Target = "CALLISTO", Aberration = "NONE", - AspectRatio = 2 + AspectRatio = 2, + + Instrument = { + Name = "NH_LORRI", + Method = "ELLIPSOID", + Aberration = "NONE", + Fovy = 0.2907, + Aspect = 1, + Near = 0.2, + Far = 10000, + }, + + PotentialTargets = { + "JUPITER", "IO", "EUROPA", "GANYMEDE", "CALLISTO" + } }, - Instrument = { - Name = "NH_LORRI", - Method = "ELLIPSOID", - Aberration = "NONE", - Fovy = 0.2907, - Aspect = 1, - Near = 0.2, - Far = 10000, - }, - PotentialTargets = { - "JUPITER", "IO", "EUROPA", "GANYMEDE", "CALLISTO" - } }, Transform = { Translation = { - Type = "SpiceEphemeris", + Type = "SpiceTranslation", Body = "CALLISTO", Observer = "JUPITER BARYCENTER", Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" @@ -70,30 +72,25 @@ return { ]] Transform = { Translation = { - Type = "StaticEphemeris", + Type = "StaticTranslation", Position = {0, -10000000, 0} }, }, - }, + }, -- CallistoTrail module { Name = "CallistoTrail", Parent = "JupiterBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "CALLISTO", - Frame = "GALACTIC", - Observer = "JUPITER BARYCENTER", - RGB = { 0.7, 0.4, 0.2 }, - TropicalOrbitPeriod = 80 , - EarthOrbitRatio = 0.04, - DayLength = 9.9259, - LineFade = 2.0, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "CALLISTO", + Observer = "JUPITER BARYCENTER", + }, + Color = { 0.4, 0.3, 0.01 }, + Period = 17, + Resolution = 1000 + } } } diff --git a/data/scene/newhorizons/jupiter/callisto/textures/Callisto-Text.png b/data/scene/missions/newhorizons/jupiter/callisto/textures/Callisto-Text.png similarity index 100% rename from data/scene/newhorizons/jupiter/callisto/textures/Callisto-Text.png rename to data/scene/missions/newhorizons/jupiter/callisto/textures/Callisto-Text.png diff --git a/data/scene/newhorizons/jupiter/callisto/textures/defaultProj.png b/data/scene/missions/newhorizons/jupiter/callisto/textures/defaultProj.png similarity index 100% rename from data/scene/newhorizons/jupiter/callisto/textures/defaultProj.png rename to data/scene/missions/newhorizons/jupiter/callisto/textures/defaultProj.png diff --git a/data/scene/missions/newhorizons/jupiter/europa/europa.data b/data/scene/missions/newhorizons/jupiter/europa/europa.data new file mode 100644 index 0000000000..4364fcbc49 --- /dev/null +++ b/data/scene/missions/newhorizons/jupiter/europa/europa.data @@ -0,0 +1,5 @@ +return { + FileRequest = { + { Identifier = "europa_textures", Destination = "textures", Version = 1 } + }, +} \ No newline at end of file diff --git a/data/scene/newhorizons/jupiter/europa/europa.mod b/data/scene/missions/newhorizons/jupiter/europa/europa.mod similarity index 64% rename from data/scene/newhorizons/jupiter/europa/europa.mod rename to data/scene/missions/newhorizons/jupiter/europa/europa.mod index fc7c032a2b..1bec7e5c9b 100644 --- a/data/scene/newhorizons/jupiter/europa/europa.mod +++ b/data/scene/missions/newhorizons/jupiter/europa/europa.mod @@ -22,24 +22,26 @@ return { Observer = "NEW HORIZONS", Target = "EUROPA", Aberration = "NONE", - AspectRatio = 2 + AspectRatio = 2, + + Instrument = { + Name = "NH_LORRI", + Method = "ELLIPSOID", + Aberration = "NONE", + Fovy = 0.2907, + Aspect = 1, + Near = 0.2, + Far = 10000, + }, + + PotentialTargets = { + "JUPITER", "IO", "EUROPA", "GANYMEDE", "CALLISTO" + } }, - Instrument = { - Name = "NH_LORRI", - Method = "ELLIPSOID", - Aberration = "NONE", - Fovy = 0.2907, - Aspect = 1, - Near = 0.2, - Far = 10000, - }, - PotentialTargets = { - "JUPITER", "IO", "EUROPA", "GANYMEDE", "CALLISTO" - } }, Transform = { Translation = { - Type = "SpiceEphemeris", + Type = "SpiceTranslation", Body = "EUROPA", Observer = "JUPITER BARYCENTER", Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" @@ -70,7 +72,7 @@ return { ]] Transform = { Translation = { - Type = "StaticEphemeris", + Type = "StaticTranslation", Position = {0, -10000000, 0} }, }, @@ -80,20 +82,15 @@ return { Name = "EuropaTrail", Parent = "JupiterBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "EUROPA", - Frame = "GALACTIC", - Observer = "JUPITER BARYCENTER", - RGB = { 0.7, 0.4, 0.2 }, - TropicalOrbitPeriod = 80 , - EarthOrbitRatio = 0.009, - DayLength = 9.9259, - LineFade = 2.0, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "EUROPA", + Observer = "JUPITER BARYCENTER", + }, + Color = { 0.5, 0.3, 0.3 }, + Period = 85 / 24, + Resolution = 1000 + } } } diff --git a/data/scene/newhorizons/jupiter/europa/textures/Europa-Text.png b/data/scene/missions/newhorizons/jupiter/europa/textures/Europa-Text.png similarity index 100% rename from data/scene/newhorizons/jupiter/europa/textures/Europa-Text.png rename to data/scene/missions/newhorizons/jupiter/europa/textures/Europa-Text.png diff --git a/data/scene/newhorizons/jupiter/europa/textures/defaultProj.png b/data/scene/missions/newhorizons/jupiter/europa/textures/defaultProj.png similarity index 100% rename from data/scene/newhorizons/jupiter/europa/textures/defaultProj.png rename to data/scene/missions/newhorizons/jupiter/europa/textures/defaultProj.png diff --git a/data/scene/missions/newhorizons/jupiter/ganymede/ganymede.data b/data/scene/missions/newhorizons/jupiter/ganymede/ganymede.data new file mode 100644 index 0000000000..4ae2714582 --- /dev/null +++ b/data/scene/missions/newhorizons/jupiter/ganymede/ganymede.data @@ -0,0 +1,5 @@ +return { + FileRequest = { + { Identifier = "ganymede_textures", Destination = "textures", Version = 1 } + }, +} \ No newline at end of file diff --git a/data/scene/newhorizons/jupiter/ganymede/ganymede.mod b/data/scene/missions/newhorizons/jupiter/ganymede/ganymede.mod similarity index 62% rename from data/scene/newhorizons/jupiter/ganymede/ganymede.mod rename to data/scene/missions/newhorizons/jupiter/ganymede/ganymede.mod index 3f14d6495f..401babcca6 100644 --- a/data/scene/newhorizons/jupiter/ganymede/ganymede.mod +++ b/data/scene/missions/newhorizons/jupiter/ganymede/ganymede.mod @@ -22,24 +22,26 @@ return { Observer = "NEW HORIZONS", Target = "GANYMEDE", Aberration = "NONE", - AspectRatio = 2 + AspectRatio = 2, + + Instrument = { + Name = "NH_LORRI", + Method = "ELLIPSOID", + Aberration = "NONE", + Fovy = 0.2907, + Aspect = 1, + Near = 0.2, + Far = 10000, + }, + + PotentialTargets = { + "JUPITER", "IO", "EUROPA", "GANYMEDE", "CALLISTO" + } }, - Instrument = { - Name = "NH_LORRI", - Method = "ELLIPSOID", - Aberration = "NONE", - Fovy = 0.2907, - Aspect = 1, - Near = 0.2, - Far = 10000, - }, - PotentialTargets = { - "JUPITER", "IO", "EUROPA", "GANYMEDE", "CALLISTO" - } }, Transform = { Translation = { - Type = "SpiceEphemeris", + Type = "SpiceTranslation", Body = "GANYMEDE", Observer = "JUPITER BARYCENTER", Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" @@ -64,7 +66,7 @@ return { }, Transform = { Translation = { - Type = "StaticEphemeris", + Type = "StaticTranslation", Position = {0, -10000000, 0} }, }, @@ -74,20 +76,15 @@ return { Name = "GanymedeTrail", Parent = "JupiterBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "GANYMEDE", - Frame = "GALACTIC", - Observer = "JUPITER BARYCENTER", - RGB = { 0.7, 0.4, 0.2 }, - TropicalOrbitPeriod = 80 , - EarthOrbitRatio = 0.018, - DayLength = 9.9259, - LineFade = 2.0, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "GANYMEDE", + Observer = "JUPITER BARYCENTER", + }, + Color = { 0.4, 0.3, 0.3 }, + Period = 172 / 24, + Resolution = 1000 + } } } diff --git a/data/scene/newhorizons/jupiter/ganymede/textures/Ganymede-Text.png b/data/scene/missions/newhorizons/jupiter/ganymede/textures/Ganymede-Text.png similarity index 100% rename from data/scene/newhorizons/jupiter/ganymede/textures/Ganymede-Text.png rename to data/scene/missions/newhorizons/jupiter/ganymede/textures/Ganymede-Text.png diff --git a/data/scene/newhorizons/jupiter/ganymede/textures/defaultProj.png b/data/scene/missions/newhorizons/jupiter/ganymede/textures/defaultProj.png similarity index 100% rename from data/scene/newhorizons/jupiter/ganymede/textures/defaultProj.png rename to data/scene/missions/newhorizons/jupiter/ganymede/textures/defaultProj.png diff --git a/data/scene/missions/newhorizons/jupiter/io/io.data b/data/scene/missions/newhorizons/jupiter/io/io.data new file mode 100644 index 0000000000..baca863e4b --- /dev/null +++ b/data/scene/missions/newhorizons/jupiter/io/io.data @@ -0,0 +1,5 @@ +return { + FileRequest = { + { Identifier = "io_textures", Destination = "textures", Version = 1 } + }, +} \ No newline at end of file diff --git a/data/scene/newhorizons/jupiter/io/io.mod b/data/scene/missions/newhorizons/jupiter/io/io.mod similarity index 66% rename from data/scene/newhorizons/jupiter/io/io.mod rename to data/scene/missions/newhorizons/jupiter/io/io.mod index 7fde7e5650..c41b45f29b 100644 --- a/data/scene/newhorizons/jupiter/io/io.mod +++ b/data/scene/missions/newhorizons/jupiter/io/io.mod @@ -22,24 +22,26 @@ return { Observer = "NEW HORIZONS", Target = "IO", Aberration = "NONE", - AspectRatio = 2 + AspectRatio = 2, + + Instrument = { + Name = "NH_LORRI", + Method = "ELLIPSOID", + Aberration = "NONE", + Fovy = 0.2907, + Aspect = 1, + Near = 0.2, + Far = 10000, + }, + + PotentialTargets = { + "JUPITER", "IO", "EUROPA", "GANYMEDE", "CALLISTO" + } }, - Instrument = { - Name = "NH_LORRI", - Method = "ELLIPSOID", - Aberration = "NONE", - Fovy = 0.2907, - Aspect = 1, - Near = 0.2, - Far = 10000, - }, - PotentialTargets = { - "JUPITER", "IO", "EUROPA", "GANYMEDE", "CALLISTO" - } }, Transform = { Translation = { - Type = "SpiceEphemeris", + Type = "SpiceTranslation", Body = "IO", Observer = "JUPITER BARYCENTER", Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" @@ -80,7 +82,7 @@ return { }, Transform = { Translation = { - Type = "StaticEphemeris", + Type = "StaticTranslation", Position = {0, -10000000, 0} }, }, @@ -90,20 +92,15 @@ return { Name = "IoTrail", Parent = "JupiterBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "IO", - Frame = "GALACTIC", - Observer = "JUPITER BARYCENTER", - RGB = { 0.7, 0.4, 0.2 }, - TropicalOrbitPeriod = 100 , - EarthOrbitRatio = 0.0045, - DayLength = 9.9259, - LineFade = 2.0, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "IO", + Observer = "JUPITER BARYCENTER", + }, + Color = { 0.4, 0.4, 0.2 }, + Period = 42 / 24, + Resolution = 1000 + } } } diff --git a/data/scene/newhorizons/jupiter/io/textures/Io-Text.png b/data/scene/missions/newhorizons/jupiter/io/textures/Io-Text.png similarity index 100% rename from data/scene/newhorizons/jupiter/io/textures/Io-Text.png rename to data/scene/missions/newhorizons/jupiter/io/textures/Io-Text.png diff --git a/data/scene/newhorizons/jupiter/jupiter/ProjectionsOfInterest.torrent b/data/scene/missions/newhorizons/jupiter/jupiter/ProjectionsOfInterest.torrent similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/ProjectionsOfInterest.torrent rename to data/scene/missions/newhorizons/jupiter/jupiter/ProjectionsOfInterest.torrent diff --git a/data/scene/newhorizons/jupiter/jupiter/jupiter.data b/data/scene/missions/newhorizons/jupiter/jupiter/jupiter.data similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/jupiter.data rename to data/scene/missions/newhorizons/jupiter/jupiter/jupiter.data diff --git a/data/scene/missions/newhorizons/jupiter/jupiter/jupiter.mod b/data/scene/missions/newhorizons/jupiter/jupiter/jupiter.mod new file mode 100644 index 0000000000..079357b2ad --- /dev/null +++ b/data/scene/missions/newhorizons/jupiter/jupiter/jupiter.mod @@ -0,0 +1,134 @@ +return { + -- Jupiter barycenter module + { + Name = "JupiterBarycenter", + Parent = "SolarSystemBarycenter", + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "JUPITER BARYCENTER", + Observer = "SUN", + Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" + }, + }, + }, + -- JupiterProjection module + { + Name = "JupiterProjection", + Parent = "JupiterBarycenter", + Renderable = { + Type = "RenderablePlanetProjection", + Frame = "IAU_JUPITER", + Body = "JUPITER", + Geometry = { + Type = "SimpleSphere", + Radius = { 0.71492, 8 }, + Segments = 200, + }, + Textures = { + Type = "simple", + Color = "textures/jupiterFlipped_low.jpg", + Project = "textures/lorriTest1.jpg", + Sequencing = "true", + }, + Projection = { + --Sequence = "F:/JupiterFullSequence", + Sequence = "${OPENSPACE_DATA}/scene/missions/newhorizons/jupiter/jupiter/ProjectionsOfInterest", + SequenceType = "image-sequence", + Observer = "NEW HORIZONS", + Target = "JUPITER", + Aberration = "NONE", + AspectRatio = 2, + + DataInputTranslation = { + Instrument = { + LORRI = { + DetectorType = "Camera", + Spice = {"NH_LORRI"}, + }, + }, + Target ={ + Read = { + "TARGET_NAME", + "INSTRUMENT_HOST_NAME", + "INSTRUMENT_ID", + "START_TIME", + "STOP_TIME", + "DETECTOR_TYPE", + --"SEQUENCE_ID", + }, + Convert = { + JRINGS = {"IMAGE-PLANE" }, + J1IO = {"IO" }, + J2EUROPA = {"EUROPA" }, + J6HIMALIA = {"IMAGE-PLANE" }, + J7ELARA = {"IMAGE-PLANE" }, + CALIBRATION = {"CALIBRATION" }, + JUPITER = {"JUPITER" }, + CALLISTO = {"CALLISTO" }, + GANYMEDE = {"GANYMEDE" }, + EARTH = {"EARTH" }, + NEWHORIZONS = {"NEW HORIZONS"}, + CCD = {"CAMERA" }, + FRAMECCD = {"SCANNER" }, + }, + }, + }, + Instrument = { + Name = "NH_LORRI", + Method = "ELLIPSOID", + Aberration = "NONE", + Fovy = 0.2907, + Aspect = 1, + Near = 0.2, + Far = 10000, + }, + PotentialTargets = { + "JUPITER", "IO", "EUROPA", "GANYMEDE", "CALLISTO" + } + } + }, + Transform = { + Rotation = { + Type = "SpiceRotation", + SourceFrame = "IAU_JUPITER", + DestinationFrame = "GALACTIC", + }, + }, + }, + { + Name = "JupiterText", + Parent = "JupiterProjection", + Renderable = { + Type = "RenderablePlane", + Size = {1.0, 7.5}, + Origin = "Center", + Billboard = true, + Texture = "textures/Jupiter-text.png", + BlendMode = "Additive" + }, + Transform = { + Translation = { + Type = "StaticTranslation", + Position = {0, -100000000, 0} + }, + }, + }, + -- JupiterTrail module + { + Name = "JupiterTrail", + Parent = "SolarSystemBarycenter", + Renderable = { + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "JUPITER BARYCENTER", + Observer = "SUN", + }, + Color = { 0.8, 0.7, 0.7 }, + Period = 4330.595, + Resolution = 1000 + } + } + +} diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/1.jpg b/data/scene/missions/newhorizons/jupiter/jupiter/textures/1.jpg similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/1.jpg rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/1.jpg diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/2.jpg b/data/scene/missions/newhorizons/jupiter/jupiter/textures/2.jpg similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/2.jpg rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/2.jpg diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/3.jpg b/data/scene/missions/newhorizons/jupiter/jupiter/textures/3.jpg similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/3.jpg rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/3.jpg diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/Jupiter-text.png b/data/scene/missions/newhorizons/jupiter/jupiter/textures/Jupiter-text.png similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/Jupiter-text.png rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/Jupiter-text.png diff --git a/data/scene/newhorizons/jupiter/io/textures/defaultProj.png b/data/scene/missions/newhorizons/jupiter/jupiter/textures/defaultProj.png similarity index 100% rename from data/scene/newhorizons/jupiter/io/textures/defaultProj.png rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/defaultProj.png diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/defaultProj2.png b/data/scene/missions/newhorizons/jupiter/jupiter/textures/defaultProj2.png similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/defaultProj2.png rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/defaultProj2.png diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/europaRise1.jpg b/data/scene/missions/newhorizons/jupiter/jupiter/textures/europaRise1.jpg similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/europaRise1.jpg rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/europaRise1.jpg diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/europaRise2.jpg b/data/scene/missions/newhorizons/jupiter/jupiter/textures/europaRise2.jpg similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/europaRise2.jpg rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/europaRise2.jpg diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/grid.jpg b/data/scene/missions/newhorizons/jupiter/jupiter/textures/grid.jpg similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/grid.jpg rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/grid.jpg diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/jupiter.jpg b/data/scene/missions/newhorizons/jupiter/jupiter/textures/jupiter.jpg similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/jupiter.jpg rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/jupiter.jpg diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/jupiterFlipped.jpg b/data/scene/missions/newhorizons/jupiter/jupiter/textures/jupiterFlipped.jpg similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/jupiterFlipped.jpg rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/jupiterFlipped.jpg diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/jupiterFlipped_low.jpg b/data/scene/missions/newhorizons/jupiter/jupiter/textures/jupiterFlipped_low.jpg similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/jupiterFlipped_low.jpg rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/jupiterFlipped_low.jpg diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/lor_0034817584_0x630_sci_1.fit.jpg b/data/scene/missions/newhorizons/jupiter/jupiter/textures/lor_0034817584_0x630_sci_1.fit.jpg similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/lor_0034817584_0x630_sci_1.fit.jpg rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/lor_0034817584_0x630_sci_1.fit.jpg diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/lor_0034817654_0x630_sci_1.fit.jpg b/data/scene/missions/newhorizons/jupiter/jupiter/textures/lor_0034817654_0x630_sci_1.fit.jpg similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/lor_0034817654_0x630_sci_1.fit.jpg rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/lor_0034817654_0x630_sci_1.fit.jpg diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/lor_0034817724_0x630_sci_1.jpg b/data/scene/missions/newhorizons/jupiter/jupiter/textures/lor_0034817724_0x630_sci_1.jpg similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/lor_0034817724_0x630_sci_1.jpg rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/lor_0034817724_0x630_sci_1.jpg diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/lor_0034817794_0x630_sci_1.fit.jpg b/data/scene/missions/newhorizons/jupiter/jupiter/textures/lor_0034817794_0x630_sci_1.fit.jpg similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/lor_0034817794_0x630_sci_1.fit.jpg rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/lor_0034817794_0x630_sci_1.fit.jpg diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/lorriTest1.jpg b/data/scene/missions/newhorizons/jupiter/jupiter/textures/lorriTest1.jpg similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/lorriTest1.jpg rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/lorriTest1.jpg diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/lorriTest2.jpg b/data/scene/missions/newhorizons/jupiter/jupiter/textures/lorriTest2.jpg similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/lorriTest2.jpg rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/lorriTest2.jpg diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/scope.png b/data/scene/missions/newhorizons/jupiter/jupiter/textures/scope.png similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/scope.png rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/scope.png diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/show.jpg b/data/scene/missions/newhorizons/jupiter/jupiter/textures/show.jpg similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/show.jpg rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/show.jpg diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/show_3072.jpg b/data/scene/missions/newhorizons/jupiter/jupiter/textures/show_3072.jpg similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/show_3072.jpg rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/show_3072.jpg diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/small.jpg b/data/scene/missions/newhorizons/jupiter/jupiter/textures/small.jpg similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/small.jpg rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/small.jpg diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/small.png b/data/scene/missions/newhorizons/jupiter/jupiter/textures/small.png similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/small.png rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/small.png diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/test.jpg b/data/scene/missions/newhorizons/jupiter/jupiter/textures/test.jpg similarity index 100% rename from data/scene/newhorizons/jupiter/jupiter/textures/test.jpg rename to data/scene/missions/newhorizons/jupiter/jupiter/textures/test.jpg diff --git a/data/scene/newhorizons/newhorizons/NewHorizonsKernels.torrent b/data/scene/missions/newhorizons/newhorizons/NewHorizonsKernels.torrent similarity index 100% rename from data/scene/newhorizons/newhorizons/NewHorizonsKernels.torrent rename to data/scene/missions/newhorizons/newhorizons/NewHorizonsKernels.torrent diff --git a/data/scene/missions/newhorizons/newhorizons/jup260.bsp.torrent b/data/scene/missions/newhorizons/newhorizons/jup260.bsp.torrent new file mode 100644 index 0000000000..0c82073d38 Binary files /dev/null and b/data/scene/missions/newhorizons/newhorizons/jup260.bsp.torrent differ diff --git a/data/scene/newhorizons/newhorizons/newhorizons.data b/data/scene/missions/newhorizons/newhorizons/newhorizons.data similarity index 100% rename from data/scene/newhorizons/newhorizons/newhorizons.data rename to data/scene/missions/newhorizons/newhorizons/newhorizons.data diff --git a/data/scene/newhorizons/newhorizons/newhorizons.mod b/data/scene/missions/newhorizons/newhorizons/newhorizons.mod similarity index 88% rename from data/scene/newhorizons/newhorizons/newhorizons.mod rename to data/scene/missions/newhorizons/newhorizons/newhorizons.mod index a4ba9124f4..40368d7efc 100644 --- a/data/scene/newhorizons/newhorizons/newhorizons.mod +++ b/data/scene/missions/newhorizons/newhorizons/newhorizons.mod @@ -78,19 +78,35 @@ else end return { - -- New Horizons Body module - { + { + Name = "NewHorizonsPosition", + Parent = "SolarSystemBarycenter", + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "NEW HORIZONS", + Observer = "SUN", + Kernels = NewHorizonsKernels + }, + Rotation = { + Type = "SpiceRotation", + SourceFrame = "NH_SPACECRAFT", + DestinationFrame = "GALACTIC", + }, + } + }, + { Name = "NewHorizons", -- Parent = "PlutoBarycenter", -- Parent = "JupiterBarycenter", - Parent = "SolarSystemBarycenter", + Parent = "NewHorizonsPosition", Renderable = { Type = "RenderableModel", Body = "NEW HORIZONS", Geometry = { Type = "MultiModelGeometry", GeometryFile = "models/NewHorizonsCleanModel.obj", - Magnification = 4, + -- Magnification = 4, }, Textures = { Type = "simple", @@ -103,17 +119,10 @@ return { }, }, Transform = { - Translation = { - Type = "SpiceEphemeris", - Body = "NEW HORIZONS", - Observer = "SUN", - Kernels = NewHorizonsKernels - }, - Rotation = { - Type = "SpiceRotation", - SourceFrame = "NH_SPACECRAFT", - DestinationFrame = "GALACTIC", - }, + Scale = { + Type = "StaticScale", + Scale = 100 + } }, }, --NewHorizonsTrail module @@ -150,7 +159,7 @@ return { Geometry = { Type = "MultiModelGeometry", GeometryFile = "models/Labels.obj", - Magnification = 4, + -- Magnification = 4, }, Textures = { Type = "simple", @@ -166,33 +175,27 @@ return { Fadeable = false, Ghosting = false, }, - }, + } }, - - { + { Name = "NewHorizonsTrailPluto", Parent = "PlutoBarycenter", Renderable = { - Type = "RenderableTrailNew", - -- Spice - Body = "NEW HORIZONS", - Frame = "GALACTIC", - Observer = "PLUTO BARYCENTER", - -- Optional rendering properties - LineColor = { 1.0, 0.8, 0.4 }, - PointColor = { 1.0, 0.8, 0.4 }, - LineFade = 0.0, -- [0,1] - RenderPart = 1, - LineWidth = 2, - ShowTimeStamps = true, - RenderFullTrail = true, - -- Time interval - TimeRange = { - Start = "2015 JUL 07 12:00:00", - End = "2015 JUL 17 12:00:00" + Type = "RenderableTrailTrajectory", + Translation = { + Type = "SpiceTranslation", + Body = "NEW HORIZONS", + Observer = "PLUTO BARYCENTER" }, - SampleDeltaTime = 3600, -- Seconds between each point - SubSamples = 3, + Color = { 1.0, 0.8, 0.4 }, + ShowFullTrail = true, + StartTime = "2015 JUL 07 12:00:00", + EndTime = "2015 JUL 17 12:00:00", + PointSize = 5, + SampleInterval = 3600, + TimeStampSubsampleFactor = 4, + EnableFade = false, + Rendering = "Lines+Points" }, }, --[[ diff --git a/data/scene/newhorizons/newhorizonsfov/newhorizonsfov.mod b/data/scene/missions/newhorizons/newhorizonsfov/newhorizonsfov.mod similarity index 95% rename from data/scene/newhorizons/newhorizonsfov/newhorizonsfov.mod rename to data/scene/missions/newhorizons/newhorizonsfov/newhorizonsfov.mod index f2b4fab3f5..7fdccdf6cc 100644 --- a/data/scene/newhorizons/newhorizonsfov/newhorizonsfov.mod +++ b/data/scene/missions/newhorizons/newhorizonsfov/newhorizonsfov.mod @@ -2,7 +2,7 @@ return { -- NewHorizonsFov main module { Name = "NH_LORRI", - Parent = "NewHorizons", + Parent = "NewHorizonsPosition", Renderable = { Type = "RenderableFov", Body = "NEW HORIZONS", @@ -28,7 +28,7 @@ return { -- NewHorizonsFov module NH_RALPH_LEISA { Name = "NH_RALPH_LEISA", - Parent = "NewHorizons", + Parent = "NewHorizonsPosition", Renderable = { Type = "RenderableFov", Body = "NEW HORIZONS", @@ -55,7 +55,7 @@ return { -- NewHorizonsFov module NH_RALPH_MVIC_PAN1 { Name = "NH_RALPH_MVIC_PAN1", - Parent = "NewHorizons", + Parent = "NewHorizonsPosition", Renderable = { Type = "RenderableFov", Body = "NEW HORIZONS", @@ -81,7 +81,7 @@ return { -- NewHorizonsFov module NH_RALPH_MVIC_PAN2 { Name = "NH_RALPH_MVIC_PAN2", - Parent = "NewHorizons", + Parent = "NewHorizonsPosition", Renderable = { Type = "RenderableFov", Body = "NEW HORIZONS", @@ -108,7 +108,7 @@ return { -- NewHorizonsFov module NH_RALPH_MVIC_RED { Name = "NH_RALPH_MVIC_RED", - Parent = "NewHorizons", + Parent = "NewHorizonsPosition", Renderable = { Type = "RenderableFov", Body = "NEW HORIZONS", @@ -135,7 +135,7 @@ return { -- NewHorizonsFov module NH_RALPH_MVIC_BLUE { Name = "NH_RALPH_MVIC_BLUE", - Parent = "NewHorizons", + Parent = "NewHorizonsPosition", Renderable = { Type = "RenderableFov", Body = "NEW HORIZONS", @@ -161,7 +161,7 @@ return { -- NewHorizonsFov module NH_RALPH_MVIC_FT { Name = "NH_RALPH_MVIC_FT", - Parent = "NewHorizons", + Parent = "NewHorizonsPosition", Renderable = { Type = "RenderableFov", Body = "NEW HORIZONS", @@ -187,7 +187,7 @@ return { -- NewHorizonsFov module NH_RALPH_MVIC_METHANE { Name = "NH_RALPH_MVIC_METHANE", - Parent = "NewHorizons", + Parent = "NewHorizonsPosition", Renderable = { Type = "RenderableFov", Body = "NEW HORIZONS", @@ -213,7 +213,7 @@ return { -- NewHorizonsFov module NH_RALPH_MVIC_NIR { Name = "NH_RALPH_MVIC_NIR", - Parent = "NewHorizons", + Parent = "NewHorizonsPosition", Renderable = { Type = "RenderableFov", Body = "NEW HORIZONS", @@ -239,7 +239,7 @@ return { -- NewHorizonsFov module NH_ALICE_AIRGLOW { Name = "NH_ALICE_AIRGLOW", - Parent = "NewHorizons", + Parent = "NewHorizonsPosition", Renderable = { Type = "RenderableFov", Body = "NEW HORIZONS", @@ -265,7 +265,7 @@ return { -- NewHorizonsFov module NH_ALICE_SOC { Name = "NH_ALICE_SOC", - Parent = "NewHorizons", + Parent = "NewHorizonsPosition", Renderable = { Type = "RenderableFov", Body = "NEW HORIZONS", @@ -290,7 +290,7 @@ return { }, { Name = "NH_REX", - Parent = "NewHorizons", + Parent = "NewHorizonsPosition", Renderable = { Type = "RenderableCrawlingLine", Source = "NH_REX", diff --git a/data/scene/newhorizons/newhorizonsfov/textures/glare.png b/data/scene/missions/newhorizons/newhorizonsfov/textures/glare.png similarity index 100% rename from data/scene/newhorizons/newhorizonsfov/textures/glare.png rename to data/scene/missions/newhorizons/newhorizonsfov/textures/glare.png diff --git a/data/scene/dawn/dawn/textures/glare_blue.png b/data/scene/missions/newhorizons/newhorizonsfov/textures/glare_blue.png similarity index 100% rename from data/scene/dawn/dawn/textures/glare_blue.png rename to data/scene/missions/newhorizons/newhorizonsfov/textures/glare_blue.png diff --git a/data/scene/newhorizons/pluto/charon/charon.data b/data/scene/missions/newhorizons/pluto/charon/charon.data similarity index 100% rename from data/scene/newhorizons/pluto/charon/charon.data rename to data/scene/missions/newhorizons/pluto/charon/charon.data diff --git a/data/scene/newhorizons/pluto/charon/charon.mod b/data/scene/missions/newhorizons/pluto/charon/charon.mod similarity index 67% rename from data/scene/newhorizons/pluto/charon/charon.mod rename to data/scene/missions/newhorizons/pluto/charon/charon.mod index f7a2f5e35a..4cfff1d131 100644 --- a/data/scene/newhorizons/pluto/charon/charon.mod +++ b/data/scene/missions/newhorizons/pluto/charon/charon.mod @@ -22,43 +22,40 @@ return { Parent = "PlutoBarycenter", Renderable = { Type = "RenderablePlanetProjection", - Frame = "IAU_CHARON", - Body = "CHARON", Geometry = { Type = "SimpleSphere", Radius = { 6.035 , 5 }, Segments = 100 }, Textures = { - Type = "simple", Color = ColorTexture, Height = "textures/cpdem-Mcolor2-MLorriCA-lr-5_ZMfs-cyl.jpg", - Project = "textures/defaultProj.png", - Sequencing = "true", }, Projection = { Observer = "NEW HORIZONS", Target = "CHARON", Aberration = "NONE", - AspectRatio = 2 - }, - Instrument = { - Name = "NH_LORRI", - Method = "ELLIPSOID", - Aberration = "NONE", - Fovy = 0.2907, - Aspect = 1, - Near = 0.2, - Far = 10000, - }, - PotentialTargets = { - "PLUTO", - "CHARON" + AspectRatio = 2, + + Instrument = { + Name = "NH_LORRI", + Method = "ELLIPSOID", + Aberration = "NONE", + Fovy = 0.2907, + Aspect = 1, + Near = 0.2, + Far = 10000, + }, + + PotentialTargets = { + "PLUTO", + "CHARON" + } } }, Transform = { Translation = { - Type = "SpiceEphemeris", + Type = "SpiceTranslation", Body = "CHARON", Observer = "PLUTO BARYCENTER", Kernels = NewHorizonsKernels @@ -83,7 +80,7 @@ return { }, Transform = { Translation = { - Type = "StaticEphemeris", + Type = "StaticTranslation", Position = {0, -1000000, 0} }, }, @@ -107,19 +104,15 @@ return { Name = "CharonTrail", Parent = "PlutoBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "CHARON", - Frame = "GALACTIC", - Observer = "PLUTO BARYCENTER", - RGB = {0.00,0.62,1.00}, - TropicalOrbitPeriod = 120 , - EarthOrbitRatio = 0.03, - DayLength = 1, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "CHARON", + Observer = "PLUTO BARYCENTER", + }, + Color = {0.00, 0.62, 1.00}, + Period = 6.38725, + Resolution = 1000 }, } } diff --git a/data/scene/newhorizons/pluto/hydra/hydra.mod b/data/scene/missions/newhorizons/pluto/hydra/hydra.mod similarity index 73% rename from data/scene/newhorizons/pluto/hydra/hydra.mod rename to data/scene/missions/newhorizons/pluto/hydra/hydra.mod index 89246a82f6..8dcf6d2d0f 100644 --- a/data/scene/newhorizons/pluto/hydra/hydra.mod +++ b/data/scene/missions/newhorizons/pluto/hydra/hydra.mod @@ -29,7 +29,7 @@ return { }, Transform = { Translation = { - Type = "SpiceEphemeris", + Type = "SpiceTranslation", Body = "HYDRA", Observer = "PLUTO BARYCENTER", Kernels = NewHorizonsKernels @@ -53,7 +53,7 @@ return { }, Transform = { Translation = { - Type = "StaticEphemeris", + Type = "StaticTranslation", Position = {1000000, 0, 1000000}, }, }, @@ -63,20 +63,15 @@ return { Name = "HydraTrail", Parent = "PlutoBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "HYDRA", - Frame = "GALACTIC", - Observer = "PLUTO BARYCENTER", - RGB = {0.00,0.62,1.00}, - TropicalOrbitPeriod = 150 , - EarthOrbitRatio = 0.2, - DayLength = 1, - DayLength = 16.11, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "HYDRA", + Observer = "PLUTO BARYCENTER", + }, + Color = {0.00, 0.62, 1.00}, + Period = 38.20177, + Resolution = 1000 }, } diff --git a/data/scene/newhorizons/pluto/hydra/textures/Hydra-Text.png b/data/scene/missions/newhorizons/pluto/hydra/textures/Hydra-Text.png similarity index 100% rename from data/scene/newhorizons/pluto/hydra/textures/Hydra-Text.png rename to data/scene/missions/newhorizons/pluto/hydra/textures/Hydra-Text.png diff --git a/data/scene/newhorizons/pluto/hydra/textures/gray.jpg b/data/scene/missions/newhorizons/pluto/hydra/textures/gray.jpg similarity index 100% rename from data/scene/newhorizons/pluto/hydra/textures/gray.jpg rename to data/scene/missions/newhorizons/pluto/hydra/textures/gray.jpg diff --git a/data/scene/newhorizons/pluto/kerberos/kerberos.mod b/data/scene/missions/newhorizons/pluto/kerberos/kerberos.mod similarity index 72% rename from data/scene/newhorizons/pluto/kerberos/kerberos.mod rename to data/scene/missions/newhorizons/pluto/kerberos/kerberos.mod index ba541c4de2..595baf13e8 100644 --- a/data/scene/newhorizons/pluto/kerberos/kerberos.mod +++ b/data/scene/missions/newhorizons/pluto/kerberos/kerberos.mod @@ -29,7 +29,7 @@ return { }, Transform = { Translation = { - Type = "SpiceEphemeris", + Type = "SpiceTranslation", Body = "KERBEROS", Observer = "PLUTO BARYCENTER", Kernels = NewHorizonsKernels @@ -53,30 +53,25 @@ return { }, Transform = { Translation = { - Type = "StaticEphemeris", + Type = "StaticTranslation", Position = {1000000, 0, 1000000}, }, }, }, - -- StyxTrail module + -- KerberosTrail module { Name = "KerberosTrail", Parent = "PlutoBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "KERBEROS", - Frame = "GALACTIC", - Observer = "PLUTO BARYCENTER", - RGB = {0.00,0.62,1.00}, - TropicalOrbitPeriod = 150 , - EarthOrbitRatio = 0.2, - DayLength = 1, - DayLength = 16.11, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "KERBEROS", + Observer = "PLUTO BARYCENTER", + }, + Color = {0.00, 0.62, 1.00}, + Period = 32.16756, + Resolution = 1000 }, } diff --git a/data/scene/newhorizons/pluto/kerberos/textures/Kerberos-Text.png b/data/scene/missions/newhorizons/pluto/kerberos/textures/Kerberos-Text.png similarity index 100% rename from data/scene/newhorizons/pluto/kerberos/textures/Kerberos-Text.png rename to data/scene/missions/newhorizons/pluto/kerberos/textures/Kerberos-Text.png diff --git a/data/scene/newhorizons/pluto/kerberos/textures/gray.jpg b/data/scene/missions/newhorizons/pluto/kerberos/textures/gray.jpg similarity index 100% rename from data/scene/newhorizons/pluto/kerberos/textures/gray.jpg rename to data/scene/missions/newhorizons/pluto/kerberos/textures/gray.jpg diff --git a/data/scene/newhorizons/pluto/nix/nix.mod b/data/scene/missions/newhorizons/pluto/nix/nix.mod similarity index 72% rename from data/scene/newhorizons/pluto/nix/nix.mod rename to data/scene/missions/newhorizons/pluto/nix/nix.mod index 10145a29ae..da05401b4e 100644 --- a/data/scene/newhorizons/pluto/nix/nix.mod +++ b/data/scene/missions/newhorizons/pluto/nix/nix.mod @@ -29,7 +29,7 @@ return { }, Transform = { Translation = { - Type = "SpiceEphemeris", + Type = "SpiceTranslation", Body = "NIX", Observer = "PLUTO BARYCENTER", Kernels = NewHorizonsKernels @@ -52,25 +52,20 @@ return { Texture = "textures/Nix-Text.png" }, }, - -- StyxTrail module + -- NixTrail module { Name = "NixTrail", Parent = "PlutoBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "NIX", - Frame = "GALACTIC", - Observer = "PLUTO BARYCENTER", - RGB = {0.00,0.62,1.00}, - TropicalOrbitPeriod = 150 , - EarthOrbitRatio = 0.12, - DayLength = 1, - DayLength = 16.11, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "NIX", + Observer = "PLUTO BARYCENTER", + }, + Color = {0.00, 0.62, 1.00}, + Period = 24.85463, + Resolution = 1000 }, } diff --git a/data/scene/newhorizons/pluto/nix/textures/Nix-Text.png b/data/scene/missions/newhorizons/pluto/nix/textures/Nix-Text.png similarity index 100% rename from data/scene/newhorizons/pluto/nix/textures/Nix-Text.png rename to data/scene/missions/newhorizons/pluto/nix/textures/Nix-Text.png diff --git a/data/scene/newhorizons/pluto/nix/textures/gray.jpg b/data/scene/missions/newhorizons/pluto/nix/textures/gray.jpg similarity index 100% rename from data/scene/newhorizons/pluto/nix/textures/gray.jpg rename to data/scene/missions/newhorizons/pluto/nix/textures/gray.jpg diff --git a/data/scene/newhorizons/pluto/pluto/pluto.data b/data/scene/missions/newhorizons/pluto/pluto/pluto.data similarity index 100% rename from data/scene/newhorizons/pluto/pluto/pluto.data rename to data/scene/missions/newhorizons/pluto/pluto/pluto.data diff --git a/data/scene/missions/newhorizons/pluto/pluto/pluto.mod b/data/scene/missions/newhorizons/pluto/pluto/pluto.mod new file mode 100644 index 0000000000..e512b74708 --- /dev/null +++ b/data/scene/missions/newhorizons/pluto/pluto/pluto.mod @@ -0,0 +1,269 @@ +if UseAccurateNewHorizonsKernels then + NewHorizonsKernels = { + "${SPICE}/nh_kernels/spk/NavPE_de433_od122.bsp", + "${SPICE}/nh_kernels/spk/NavSE_plu047_od122.bsp" + } +else + NewHorizonsKernels = { + "${SPICE}/NewHorizonsKernels/nh_plu017.bsp" + } +end + +Files = { + low = "textures/pluto_large.jpg", + med = "textures/Shenk_180.jpg", + high = "textures/pmap_cyl_HR_LOR_lowres.jpg" +} +ColorTexture = Files[TextureResolution] + +return { + -- Pluto barycenter module + { + Name = "PlutoBarycenter", + Parent = "SolarSystemBarycenter", + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "PLUTO BARYCENTER", + Observer = "SUN", + Kernels = NewHorizonsKernels + }, + }, + }, + -- PlutoProjection module + { + Name = "PlutoProjection", + Parent = "PlutoBarycenter", + Renderable = { + Type = "RenderablePlanetProjection", + Geometry = { + Type = "SimpleSphere", + Radius = { 1.173 , 6 }, + Segments = 100 + }, + Textures = { + Color = ColorTexture, + Height = "textures/pluto_shenk_heightmap.jpg", + }, + Projection = { + Sequence = "${OPENSPACE_DATA}/scene/missions/newhorizons/pluto/pluto/images", + EventFile = "${OPENSPACE_DATA}/scene/missions/newhorizons/pluto/pluto/assets/core_v9h_obs_getmets_v8_time_fix_nofrcd_mld.txt", + SequenceType = "hybrid", + Observer = "NEW HORIZONS", + Target = "PLUTO", + Aberration = "NONE", + AspectRatio = 2, + + DataInputTranslation = { + Instrument = { + LORRI = { + DetectorType = "Camera", + Spice = {"NH_LORRI"}, + }, + RALPH_MVIC_PAN_FRAME = { + DetectorType = "Scanner", + StopCommand = "RALPH_ABORT", + Spice = {"NH_RALPH_MVIC_FT"}, + }, + RALPH_MVIC_COLOR = { + DetectorType = "Scanner", + StopCommand = "END_NOM", + Spice = { "NH_RALPH_MVIC_NIR", + "NH_RALPH_MVIC_METHANE", + "NH_RALPH_MVIC_RED", + "NH_RALPH_MVIC_BLUE" }, + }, + RALPH_LEISA = { + DetectorType = "Scanner", + StopCommand = "END_NOM", + Spice = {"NH_RALPH_LEISA"}, + }, + RALPH_MVIC_PAN1 = { + DetectorType = "Scanner", + StopCommand = "END_NOM", + Spice = {"NH_RALPH_MVIC_PAN1"}, + }, + RALPH_MVIC_PAN2 = { + DetectorType = "Scanner", + StopCommand = "END_NOM", + Spice = {"NH_RALPH_MVIC_PAN2"}, + }, + ALICE_Use_AIRGLOW = { + DetectorType = "Scanner", + StopCommand = "ALICE_END_PIXELLIST", + Spice = {"NH_ALICE_AIRGLOW"}, + }, + ALICE_Use_AIRGLOW = { + DetectorType = "Scanner", + StopCommand = "ALICE_END_HISTOGRAM", + Spice = {"NH_ALICE_AIRGLOW"}, + }, + ALICE_Use_SOCC = { + DetectorType = "Scanner", + StopCommand = "ALICE_END_PIXELLIST", + Spice = {"NH_ALICE_SOC"}, + }, + ALICE_Use_SOCC = { + DetectorType = "Scanner", + StopCommand = "ALICE_END_HISTOGRAM", + Spice = {"NH_ALICE_SOC"}, + }, + REX_START = { + DetectorType = "Scanner", + StopCommand = "REX_MODE_OFF", + Spice = { "NH_REX" }, + } + }, + Target ={ + Read = { + "TARGET_NAME", + "INSTRUMENT_HOST_NAME", + "INSTRUMENT_ID", + "START_TIME", + "STOP_TIME", + "DETECTOR_TYPE", + --"SEQUENCE_ID", + }, + Convert = { + PLUTO = {"PLUTO" }, + NEWHORIZONS = {"NEW HORIZONS"}, + CCD = {"CAMERA" }, + FRAMECCD = {"SCANNER" }, + }, + }, + }, + + Instrument = { + Name = "NH_LORRI", + Method = "ELLIPSOID", + Aberration = "NONE", + Fovy = 0.2907, + Aspect = 1, + Near = 0.2, + Far = 10000, + }, + + PotentialTargets = { + "PLUTO", + "CHARON", + "NIX", + "HYDRA", + "P5", + "P4", + } + }, + }, + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "PLUTO", + Observer = "PLUTO BARYCENTER", + Kernels = NewHorizonsKernels + }, + Rotation = { + Type = "SpiceRotation", + SourceFrame = "IAU_PLUTO", + DestinationFrame = "GALACTIC", + } + }, + }, + { + Name = "PlutoBarycenterLabel", + Parent = "PlutoBarycenter", + Renderable = { + Type = "RenderablePlane", + Billboard = true, + Size = { 5, 4 }, + Texture = "textures/barycenter.png", + Atmosphere = { + Type = "Nishita", -- for example, values missing etc etc + MieFactor = 1.0, + MieColor = {1.0, 1.0, 1.0} + } + }, + }, + { + Name = "PlutoText", + Parent = "PlutoProjection", + Renderable = { + Type = "RenderablePlane", + Size = {1.0, 6.3}, + Origin = "Center", + Billboard = true, + Texture = "textures/Pluto-Text.png", + BlendMode = "Additive" + }, + Transform = { + Translation = { + Type = "StaticTranslation", + Position = {0, -2000000, 0} + }, + }, + }, + { + Name = "PlutoTexture", + Parent = "PlutoProjection", + Renderable = { + Type = "RenderablePlane", + Size = {1.0, 6.4}, + Origin = "Center", + Billboard = true, + ProjectionListener = false, + Texture = "textures/Pluto-Text.png" + }, + Transform = { + Translation = { + Type = "StaticTranslation", + Position = {0, -4000000, 0} + }, + }, + }, + { + Name = "PlutoShadow", + Parent = "PlutoProjection", + Renderable = { + Type = "RenderableShadowCylinder", + TerminatorType = "PENUMBRAL", + LightSource = "SUN", + Observer = "NEW HORIZONS", + Body = "PLUTO", + BodyFrame = "IAU_PLUTO", + MainFrame = "GALACTIC", + Aberration = "NONE", + }, + }, + -- PlutoBarycentricTrail module + { + Name = "PlutoBarycentricTrail", + Parent = "PlutoBarycenter", + Renderable = { + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "PLUTO", + Observer = "PLUTO BARYCENTER", + }, + Color = {0.00, 0.62, 1.00}, + Period = 6.38723, + Resolution = 1000 + }, + }, + -- PlutoTrail module + { + Name = "PlutoTrail", + Parent = "SolarSystemBarycenter", + Renderable = { + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "PLUTO BARYCENTER", + Observer = "SUN", + }, + Color = { 0.3, 0.7, 0.3 }, + -- Not the actual Period, but the SPICE kernels we have only + -- go back to 1850, about 150 yeays ago + Period = 160 * 365.242, + Resolution = 1000 + }, + } +} diff --git a/data/scene/newhorizons/pluto/styx/styx.mod b/data/scene/missions/newhorizons/pluto/styx/styx.mod similarity index 73% rename from data/scene/newhorizons/pluto/styx/styx.mod rename to data/scene/missions/newhorizons/pluto/styx/styx.mod index 52918a7d26..559062be97 100644 --- a/data/scene/newhorizons/pluto/styx/styx.mod +++ b/data/scene/missions/newhorizons/pluto/styx/styx.mod @@ -29,7 +29,7 @@ return { }, Transform = { Translation = { - Type = "SpiceEphemeris", + Type = "SpiceTranslation", Body = "STYX", Observer = "PLUTO BARYCENTER", Kernels = NewHorizonsKernels @@ -54,7 +54,7 @@ return { }, Transform = { Translation = { - Type = "StaticEphemeris", + Type = "StaticTranslation", Position = {1000000, 0, 1000000} }, }, @@ -64,21 +64,15 @@ return { Name = "StyxTrail", Parent = "PlutoBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "STYX", - Frame = "GALACTIC", - Observer = "PLUTO BARYCENTER", - RGB = {0.00,0.62,1.00}, - TropicalOrbitPeriod = 150 , - EarthOrbitRatio = 0.12, - DayLength = 1, - DayLength = 16.11, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "STYX", + Observer = "PLUTO BARYCENTER", + }, + Color = {0.00, 0.62, 1.00}, + Period = 20.16155, + Resolution = 1000 }, } - } diff --git a/data/scene/newhorizons/pluto/styx/textures/Styx-Text.png b/data/scene/missions/newhorizons/pluto/styx/textures/Styx-Text.png similarity index 100% rename from data/scene/newhorizons/pluto/styx/textures/Styx-Text.png rename to data/scene/missions/newhorizons/pluto/styx/textures/Styx-Text.png diff --git a/data/scene/newhorizons/pluto/styx/textures/gray.jpg b/data/scene/missions/newhorizons/pluto/styx/textures/gray.jpg similarity index 100% rename from data/scene/newhorizons/pluto/styx/textures/gray.jpg rename to data/scene/missions/newhorizons/pluto/styx/textures/gray.jpg diff --git a/data/scene/osirisrex/bennu/InstrumentTimes/BaseballDiamond_PolyCam.txt b/data/scene/missions/osirisrex/bennu/InstrumentTimes/BaseballDiamond_PolyCam.txt similarity index 100% rename from data/scene/osirisrex/bennu/InstrumentTimes/BaseballDiamond_PolyCam.txt rename to data/scene/missions/osirisrex/bennu/InstrumentTimes/BaseballDiamond_PolyCam.txt diff --git a/data/scene/osirisrex/bennu/InstrumentTimes/DetailedSurvey_EquatorialStations_Spectrometers.txt b/data/scene/missions/osirisrex/bennu/InstrumentTimes/DetailedSurvey_EquatorialStations_Spectrometers.txt similarity index 100% rename from data/scene/osirisrex/bennu/InstrumentTimes/DetailedSurvey_EquatorialStations_Spectrometers.txt rename to data/scene/missions/osirisrex/bennu/InstrumentTimes/DetailedSurvey_EquatorialStations_Spectrometers.txt diff --git a/data/scene/osirisrex/bennu/InstrumentTimes/OrbitalB_Site08_PolyCamImages.txt b/data/scene/missions/osirisrex/bennu/InstrumentTimes/OrbitalB_Site08_PolyCamImages.txt similarity index 100% rename from data/scene/osirisrex/bennu/InstrumentTimes/OrbitalB_Site08_PolyCamImages.txt rename to data/scene/missions/osirisrex/bennu/InstrumentTimes/OrbitalB_Site08_PolyCamImages.txt diff --git a/data/scene/osirisrex/bennu/InstrumentTimes/Recon_225m_Equatorial_PolyCam.txt b/data/scene/missions/osirisrex/bennu/InstrumentTimes/Recon_225m_Equatorial_PolyCam.txt similarity index 100% rename from data/scene/osirisrex/bennu/InstrumentTimes/Recon_225m_Equatorial_PolyCam.txt rename to data/scene/missions/osirisrex/bennu/InstrumentTimes/Recon_225m_Equatorial_PolyCam.txt diff --git a/data/scene/osirisrex/bennu/InstrumentTimes/Recon_225m_Equatorial_spectrometers.txt b/data/scene/missions/osirisrex/bennu/InstrumentTimes/Recon_225m_Equatorial_spectrometers.txt similarity index 100% rename from data/scene/osirisrex/bennu/InstrumentTimes/Recon_225m_Equatorial_spectrometers.txt rename to data/scene/missions/osirisrex/bennu/InstrumentTimes/Recon_225m_Equatorial_spectrometers.txt diff --git a/data/scene/osirisrex/bennu/InstrumentTimes/Recon_525m_Equatorial_spectrometers.txt b/data/scene/missions/osirisrex/bennu/InstrumentTimes/Recon_525m_Equatorial_spectrometers.txt similarity index 100% rename from data/scene/osirisrex/bennu/InstrumentTimes/Recon_525m_Equatorial_spectrometers.txt rename to data/scene/missions/osirisrex/bennu/InstrumentTimes/Recon_525m_Equatorial_spectrometers.txt diff --git a/data/scene/osirisrex/bennu/bennu.data b/data/scene/missions/osirisrex/bennu/bennu.data similarity index 100% rename from data/scene/osirisrex/bennu/bennu.data rename to data/scene/missions/osirisrex/bennu/bennu.data diff --git a/data/scene/missions/osirisrex/bennu/bennu.mod b/data/scene/missions/osirisrex/bennu/bennu.mod new file mode 100644 index 0000000000..d7718f66bb --- /dev/null +++ b/data/scene/missions/osirisrex/bennu/bennu.mod @@ -0,0 +1,112 @@ +local BENNU_BODY = "2101955" + +return { + ------------------------ + -- Bennu -- + ------------------------ + { + Name = "BennuBarycenter", + Parent = "SolarSystemBarycenter", + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = BENNU_BODY, + Observer = "SUN", + }, + }, + }, + { + Name = "Bennu", + Parent = "BennuBarycenter", + + Renderable = { + Type = "RenderableModelProjection", + Body = BENNU_BODY, + Geometry = { + Type = "MultiModelGeometry", + GeometryFile = "models/BennuTextured.obj", + Magnification = 0, + }, + Shading = { + PerformShading = true, + Fadeable = false, + Ghosting = false, + }, + Textures = { + Type = "simple", + Color = "textures/gray.png", + Project = "textures/defaultProj.png", + Default = "textures/defaultProj.png" + }, + Projection = { + Sequence = "InstrumentTimes", + SequenceType = "instrument-times", + Observer = "OSIRIS-REX", + Target = BENNU_BODY, + Aberration = "NONE", + AspectRatio = 2, + + DataInputTranslation = { + Instruments = { + ORX_OCAMS_POLYCAM = { + DetectorType = "Camera", + Spice = {"ORX_OCAMS_POLYCAM"}, + Files = { + "BaseballDiamond_PolyCam.txt", + --"OrbitalB_Site08_PolyCamImages.txt", + "Recon_225m_Equatorial_PolyCam.txt", + }, + }, + ORX_REXIS = { + DetectorType = "Camera", + Spice = {"ORX_REXIS"}, + Files = { + "DetailedSurvey_EquatorialStations_Spectrometers.txt", + "Recon_225m_Equatorial_spectrometers.txt", + "Recon_525m_Equatorial_spectrometers.txt", + }, + }, + }, + Target = { + Body = BENNU_BODY, -- Do we need this? + }, + }, + + Instrument = { -- INVALID DATA - JUST FOR TESTING + Name = "ORX_OCAMS_POLYCAM", + Method = "ELLIPSOID", + Aberration = "NONE", + Fovy = 0.792, + Aspect = 1, + Near = 0.01, + Far = 1000000, + }, + }, + + }, + + Transform = { + Rotation = { + Type = "SpiceRotation", + SourceFrame = "IAU_BENNU", + DestinationFrame = "GALACTIC", + }, + }, + }, + { + Name = "BennuTrail", + Parent = "SolarSystemBarycenter", + Renderable = { + Type = "RenderableTrailTrajectory", + Translation = { + Type = "SpiceTranslation", + Body = BENNU_BODY, + Observer = "SUN", + }, + Color = { 0.4, 0.0, 0.7}, + StartTime = "2015 JAN 01 00:00:00.000", + EndTime = "2023 MAY 31 00:00:00.000", + SampleInterval = 3600, + }, + }, +} diff --git a/data/scene/osirisrex/osirisrex/OsirisRexKernels.torrent b/data/scene/missions/osirisrex/osirisrex/OsirisRexKernels.torrent similarity index 100% rename from data/scene/osirisrex/osirisrex/OsirisRexKernels.torrent rename to data/scene/missions/osirisrex/osirisrex/OsirisRexKernels.torrent diff --git a/data/scene/osirisrex/osirisrex/osirisrex.data b/data/scene/missions/osirisrex/osirisrex/osirisrex.data similarity index 100% rename from data/scene/osirisrex/osirisrex/osirisrex.data rename to data/scene/missions/osirisrex/osirisrex/osirisrex.data diff --git a/data/scene/osirisrex/osirisrex/osirisrex.mission b/data/scene/missions/osirisrex/osirisrex/osirisrex.mission similarity index 100% rename from data/scene/osirisrex/osirisrex/osirisrex.mission rename to data/scene/missions/osirisrex/osirisrex/osirisrex.mission diff --git a/data/scene/missions/osirisrex/osirisrex/osirisrex.mod b/data/scene/missions/osirisrex/osirisrex/osirisrex.mod new file mode 100644 index 0000000000..a6f220cf56 --- /dev/null +++ b/data/scene/missions/osirisrex/osirisrex/osirisrex.mod @@ -0,0 +1,394 @@ +local BENNU_BODY = "2101955" + +local CaseDependentKernels +if KernelCase == 2 then + CaseDependentKernels = { + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/ORX_Recon_525mSortie_Case02.bsp", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/Recon_525mSortie_Case02_0Latitude.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/Recon_525mSortie_Case02_atl_19145_04.atf", + + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/ORX_Recon_225mSortie_Case02.bsp", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Recon_225mSortie_Case02_0Latitude.bc" + } +elseif KernelCase == 5 then + CaseDependentKernels = { + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/ORX_Recon_525mSortie_Case05.bsp", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/Recon_525mSortie_Case05_20negLatitude.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/Recon_525mSortie_Case05_atl_19145_04.atf", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/Recon_525mSortie_Case05_NominalProfile.bc", + + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/ORX_Recon_225mSortie_Case05.bsp", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Recon_225mSortie_Case05_20negLatitude.bc" + } +elseif KernelCase == 8 then + CaseDependentKernels = { + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/Recon_525mSortie_Case08_NominalProfile.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/ORX_Recon_225mSortie_Case08.bsp", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Recon_225mSortie_Case08_40negLatitude.bc" + } +elseif KernelCase == 11 then + CaseDependentKernels = { + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/ORX_Recon_225mSortie_Case11.bsp", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Recon_225mSortie_Case11_60negLatitude.bc" + } +end + +local OsirisRexKernels = { + -- background + -- SCLK kernels needs to be loaded before CK kernels (and generally first) + "${SPICE}/OsirisRexKernels/background/sclk/ORX_SCLKSCET.00000.tsc", + + -- This cannot be loaded correctly for some reason! + --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/dsk/RQ36mod.oct12_CCv0001.bds") + + "${SPICE}/OsirisRexKernels/background/fk/orx_v04.tf", + "${SPICE}/OsirisRexKernels/background/ik/orx_lidar_v00.ti", + "${SPICE}/OsirisRexKernels/background/ik/orx_ocams_v03.ti", + "${SPICE}/OsirisRexKernels/background/ik/orx_otes_v00.ti", + "${SPICE}/OsirisRexKernels/background/ik/orx_rexis_v00.ti", + "${SPICE}/OsirisRexKernels/background/ik/orx_struct_v00.ti", + "${SPICE}/OsirisRexKernels/background/ik/orx_navcam_v00.ti", + "${SPICE}/OsirisRexKernels/background/ik/orx_ola_v00.ti", + "${SPICE}/OsirisRexKernels/background/ik/orx_ovirs_v00.ti", + "${SPICE}/OsirisRexKernels/background/ik/orx_stowcam_v00.ti", + -- "${SPICE}/OsirisRexKernels/background/lsk/naif0011.tls", + "${SPICE}/OsirisRexKernels/background/pck/bennu_SPH250m.tpc", + "${SPICE}/OsirisRexKernels/background/pck/bennu_v10.tpc", + + -- Low res SPK + "${SPICE}/OsirisRexKernels/background/spk/orx_160917_231024_pgaa3_day15m60_v1.bsp", + "${SPICE}/OsirisRexKernels/background/spk/orx_160914_231024_pgaa3_day12m60_v1.bsp", + + "${SPICE}/OsirisRexKernels/background/spk/orx_160908_231024_pgaa3_day06m60_v1.bsp", + "${SPICE}/OsirisRexKernels/background/spk/spk_orx_160908_231024_pgaa2_day06m60_v3.bsp", + "${SPICE}/OsirisRexKernels/background/spk/orx_160908_231024_pgaa2_day06m60.bsp", + + "${SPICE}/OsirisRexKernels/background/spk/OREX_20160908_M60_complete.bsp", + "${SPICE}/OsirisRexKernels/background/spk/OREX_20160904_M45_complete.bsp", + + -- SPK + "${SPICE}/OsirisRexKernels/background/spk/de421.bsp", + "${SPICE}/OsirisRexKernels/background/spk/sb-101955-76.bsp", + + -- Nominal_Profile_LowRes + "${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/Approach_600s_20180816T230000_20181119T010000.bsp", + "${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/Approach_NominalProfile_600s_20180816T230000_20181119T010000.bc", + "${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/DetailedSurvey_600s_20190108T000000_20190317T000000.bsp", + "${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/OrbitalA_600s_20181203T230000_20190109T000000.bsp", + "${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/OrbitalA_NominalProfile_600s_20181203T230000_20190109T000000.bc", + "${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/OrbitalB_600s_20190316T000000_20190521T000000.bsp", + "${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/DetailedSurvey_NominalProfile_600s_20190108T000000_20190317T000000.bc", + "${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/OrbitalB_NominalProfile600s_20190316T000000_20190521T000000.bc", + "${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/PrelimSurvey_600s_20181119T230000_20181204T010000.bsp", + "${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/PrelimSurvey_NominalProfile_600s_20181119T230000_20181204T010000.bc", + "${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/Recon_600s_20190519T000000_20190830T000000.bsp", + "${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/Recon_NominalProfile_600s_20190519T000000_20190830T000000.bc", + + -- Nominal_Observations_Science + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/DustSearch_v1/Phase03_AP_DustSearch_1.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/LightCurve_v1/Phase03_AP_LightCurve_1.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/LightCurve_v1/Phase03_AP_LightCurve_2.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/NatSatSearch_v1/Phase03_AP_SatSearch_1.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/NatSatSearch_v1/Phase03_AP_SatSearch_2.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/PhaseFunction_v1/Phase03_AP_PhaseFunction_1.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_1.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_2.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_3.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_4.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_5.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_6.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_7.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_8.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_9_Forced4x4.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/SpectraMap_v1/Phase03_AP_SpectraMap_1.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/MapCamOLA_v1/Phase04_PS_MC_1_v1_1a.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/MapCamOLA_v1/Phase04_PS_MC_2_v1_1a.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/OLA_v1/Phase04_PS_OLA_Nominal_1.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/OLA_v1/Phase04_PS_OLA_Nominal_2.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/OLA_v1/Phase04_PS_OLA_Nominal_3.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/OLA_v1/Phase04_PS_OLA_Nominal_4.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/PolyCam_v1/Phase04_PS_PolyCam_1.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/PolyCam_v1/Phase04_PS_PolyCam_2.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/PolyCam_v1/Phase04_PS_PolyCam_3.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/PolyCam_v1/Phase04_PS_PolyCam_4.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/PolyCam_v1/Phase04_PS_PolyCam_5.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/PolyCam_v1/Phase04_PS_PolyCam_6.bc", + + --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19013_18_BBD1_info.TXT") + --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19014_16_BBD2_info.TXT") + --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19020_18_BBD3_info.TXT") + --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19021_19_BBD4_info.TXT") + --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/README.txt") + + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19013_18_BBD1_v2.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19014_16_BBD2_v2.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19020_18_BBD3_v2.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19021_19_BBD4_v2.bc", + + + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/EquatorialStations_v1/Phase06_DS_Equatorial_Stations_1.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/EquatorialStations_v1/Phase06_DS_Equatorial_Stations_2.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/EquatorialStations_v1/Phase06_DS_Equatorial_Stations_3.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/EquatorialStations_v1/Phase06_DS_Equatorial_Stations_4.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/EquatorialStations_v1/Phase06_DS_Equatorial_Stations_5.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/EquatorialStations_v1/Phase06_DS_Equatorial_Stations_6.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/EquatorialStations_v1/Phase06_DS_Equatorial_Stations_7.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/PlumeSearch_v1/Phase06_DS_Plume_Search_1.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/PlumeSearch_v1/Phase06_DS_Plume_Search_2.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/07_OrbitalB/CandidateSampleSite_v1/Phase07_OB_CSS_Mapping_1.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/07_OrbitalB/CandidateSampleSite_v1/Phase07_OB_CSS_Mapping_2.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/07_OrbitalB/CandidateSampleSite_v1/Phase07_OB_CSS_Mapping_3.bc", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/07_OrbitalB/CandidateSampleSite_v2/CSS_Mapping_1.a", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/07_OrbitalB/CandidateSampleSite_v2/CSS_Mapping_2.a", + "${SPICE}/OsirisRexKernels/Nominal_Observations_Science/07_OrbitalB/CandidateSampleSite_v2/CSS_Mapping_3.a", + + --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Case02_0Latitude.wmv") + --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Case05_20negLatitude.wmv") + --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Case08_40negLatitude.wmv") + --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Case11_60negLatitude.wmv") +} + +-- Append the CaseDependentKernels at the end of the OsirisRexKernels set +for i = 0, #CaseDependentKernels do + OsirisRexKernels[#OsirisRexKernels + 1] = CaseDependentKernels[i] +end + + +return { + ------------------------ + -- Osiris Rex -- + ------------------------ + { + Name = "OsirisRex", + Parent = "SolarSystemBarycenter", + Renderable = { + Type = "RenderableModel", + Body = "OSIRIS-REX", + Geometry = { + Type = "MultiModelGeometry", + GeometryFile = "models/orx_base_resized_12_sep_2016.obj", + Magnification = 0, + }, + Textures = { + Type = "simple", + Color = "textures/osirisTex.png", + }, + Shading = { + PerformShading = true, + Fadeable = false, + Ghosting = false, + }, + }, + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "OSIRIS-REX", + Observer = "SUN", + Kernels = OsirisRexKernels + }, + Rotation = { + Type = "SpiceRotation", + SourceFrame = "ORX_SPACECRAFT", + DestinationFrame = "GALACTIC", + }, + }, + }, + { + Name = "ORX_OCAMS_POLYCAM", + Parent = "OsirisRex", + Renderable = { + Type = "RenderableModel", + Body = "OSIRIS-REX", + Geometry = { + Type = "MultiModelGeometry", + GeometryFile = "models/orx_polycam_resized_12_sep_2016.obj", + Magnification = 0, + }, + Textures = { + Type = "simple", + Color = "textures/osirisTex.png", + }, + Shading = { + PerformShading = true, + Fadeable = false, + Ghosting = false, + }, + }, + Transform = { + Translation = { + Type = "StaticTranslation", + Position = {-0.2476, 0.2710, 0.3364}, + }, + Rotation = { + Type = "SpiceRotation", + SourceFrame = "ORX_OCAMS_POLYCAM", + DestinationFrame = "ORX_SPACECRAFT", + }, + }, + }, + { + Name = "ORX_REXIS", + Parent = "OsirisRex", + Renderable = { + Type = "RenderableModel", + Body = "OSIRIS-REX", + Geometry = { + Type = "MultiModelGeometry", + GeometryFile = "models/orx_rexis_resized_12_sep_2016.obj", + Magnification = 0, + }, + Textures = { + Type = "simple", + Color = "textures/osirisTex.png", + }, + Shading = { + PerformShading = true, + Fadeable = false, + Ghosting = false, + }, + }, + Transform = { + Translation = { + Type = "StaticTranslation", + Position = {0, 0.3371, 0.2712}, + }, + Rotation = { + Type = "SpiceRotation", + SourceFrame = "ORX_REXIS", + DestinationFrame = "ORX_SPACECRAFT", + }, + }, + }, + { + Name = "POLYCAM FOV", + Parent = "ORX_OCAMS_POLYCAM", + Renderable = { + Type = "RenderableFov", + Body = "OSIRIS-REX", + Frame = "ORX_OCAMS_POLYCAM", + RGB = { 0.8, 0.7, 0.7 }, + Instrument = { + Name = "ORX_OCAMS_POLYCAM", + Method = "ELLIPSOID", + Aberration = "NONE", + }, + PotentialTargets = { + BENNU_BODY -- Bennu + } + }, + }, + { + Name = "REXIS FOV", + Parent = "ORX_REXIS", + Renderable = { + Type = "RenderableFov", + Body = "OSIRIS-REX", + Frame = "ORX_REXIS", + RGB = { 0.8, 0.7, 0.7 }, + Instrument = { + Name = "ORX_REXIS", + Method = "ELLIPSOID", + Aberration = "NONE", + }, + PotentialTargets = { + BENNU_BODY -- Bennu + }, + FrameConversions = { + [BENNU_BODY] = "IAU_BENNU" + } + }, + }, + --[[ + -- Latest image taken by POLYCAM + { + Name = "ImagePlaneOsirisRex", + Parent = "Bennu2", + Renderable = { + Type = "RenderablePlaneProjection", + Frame = "IAU_BENNU", + DefaultTarget = BENNU_BODY, + Spacecraft = "OSIRIS-REX", + Instrument = "ORX_OCAMS_POLYCAM", + Moving = false, + Texture = "textures/defaultProj.png", + }, + Ephemeris = { + Type = "Static", + Position = {0, 0, 0, 1} + }, + }, + -- POLYCAM FoV square + { + Name = "FovImagePlane", + Parent = "Bennu2", + Renderable = { + Type = "RenderablePlaneProjection", + Frame = "IAU_BENNU", + DefaultTarget = BENNU_BODY, + Spacecraft = "OSIRIS-REX", + Instrument = "ORX_OCAMS_POLYCAM", + Moving = true, + Texture = "textures/defaultProj.png", + }, + Ephemeris = { + Type = "Static", + Position = {0, 0, 0, 1} + }, + }, + ]] + + -- Trail relative to Earth + { + Name = "OsirisRexTrailEarth", + Parent = "Earth", + Renderable = { + Type = "RenderableTrailTrajectory", + Translation = { + Type = "SpiceTranslation", + Body = "OSIRIS-REX", + Frame = "IAU_EARTH", + Observer = "EARTH", + }, + Color = { 0.9, 0.9, 0.0 }, + StartTime = "2016 SEP 8 23:05:00.50", + EndTime = "2016 SEP 9 00:05:00", + SampleInterval = 60, + }, + }, + + -- Trail relative to solar system barycenter + { + Name = "OsirisRexTrailSolarSystem", + Parent = "SolarSystemBarycenter", + Renderable = { + Type = "RenderableTrailTrajectory", + Translation = { + Type = "SpiceTranslation", + Body = "OSIRIS-REX", + Observer = "SUN", + }, + Color = { 0.2, 0.9, 0.2 }, + StartTime = "2016 SEP 8 23:05:00.50", + EndTime = "2023 SEP 24 12:00:00", + SampleInterval = 3600, + }, + }, + + -- Trail relative to Bennu + { + Name = "OsirisRexTrailBennu", + Parent = "BennuBarycenter", + Renderable = { + Type = "RenderableTrailTrajectory", + Translation = { + Type = "SpiceTranslation", + Body = "OSIRIS-REX", + Observer = BENNU_BODY, + }, + Color = { 0.9, 0.2, 0.9 }, + StartTime = "2016 SEP 8 23:05:00.50", + EndTime = "2023 SEP 24 12:00:00", + SampleInterval = 3600, + }, + }, +} diff --git a/data/scene/osirisrex/osirisrex/spice_kernel_times.mission b/data/scene/missions/osirisrex/osirisrex/spice_kernel_times.mission similarity index 100% rename from data/scene/osirisrex/osirisrex/spice_kernel_times.mission rename to data/scene/missions/osirisrex/osirisrex/spice_kernel_times.mission diff --git a/data/scene/osirisrex/scheduled_scripts.lua b/data/scene/missions/osirisrex/scheduled_scripts.lua similarity index 100% rename from data/scene/osirisrex/scheduled_scripts.lua rename to data/scene/missions/osirisrex/scheduled_scripts.lua diff --git a/data/scene/rosetta/67P/67P.data b/data/scene/missions/rosetta/67P/67P.data similarity index 100% rename from data/scene/rosetta/67P/67P.data rename to data/scene/missions/rosetta/67P/67P.data diff --git a/data/scene/missions/rosetta/67P/67P.mod b/data/scene/missions/rosetta/67P/67P.mod new file mode 100644 index 0000000000..a039c22b4d --- /dev/null +++ b/data/scene/missions/rosetta/67P/67P.mod @@ -0,0 +1,127 @@ +return { + -- Comet 67P Body module + { + Name = "67PBarycenter", + Parent = "SolarSystemBarycenter", + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "CHURYUMOV-GERASIMENKO", + Observer = "SUN", + }, + }, + }, + { + Name = "67P", + Parent = "67PBarycenter", + + Renderable = { + Type = "RenderableModelProjection", + Geometry = { + Type = "MultiModelGeometry", + GeometryFile = "obj/67P_rotated_5_130.obj", + Magnification = 0, + }, + Textures = { + Color = "textures/gray.jpg", + -- Color = "textures/may9_map.jpg", + }, + Projection = { + Sequence = "rosettaimages", + SequenceType = "image-sequence", + Observer = "ROSETTA", + Target = "CHURYUMOV-GERASIMENKO", + Aberration = "NONE", + TextureMap = true, + ShadowMap = true, + + DataInputTranslation = { + Instrument = { + NAVCAM = { + DetectorType = "Camera", + Spice = {"ROS_NAVCAM-A"}, + }, + }, + Target = { + Read = { + "TARGET_NAME", + "INSTRUMENT_HOST_NAME", + "INSTRUMENT_ID", + "START_TIME", + "STOP_TIME", + }, + Convert = { + CHURYUMOV = {"CHURYUMOV-GERASIMENKO"}, + ROSETTA = {"ROSETTA" }, + --NAVCAM = {"NAVCAM"}, + ["ROSETTA-ORBITER"] = {"ROSETTA" }, + CHURYUMOVGERASIMENKO11969R1 = {"CHURYUMOV-GERASIMENKO"}, + CHURYUMOVGERASIMENKO = {"CHURYUMOV-GERASIMENKO"}, + ["CHURYUMOV-GERASIMENKO1(1969R1)"] = {"CHURYUMOV-GERASIMENKO"}, + --NAVIGATIONCAMERA = {"NAVCAM" }, + }, + }, + }, + + Instrument = { + Name = "ROS_NAVCAM-A", + Method = "ELLIPSOID", + Aberration = "NONE", + Fovy = 5.00, + Aspect = 1 + }, + }, + + BoundingSphereRadius = 5000.0 + }, + Transform = { + Rotation = { + Type = "SpiceRotation", + SourceFrame = "67P/C-G_CK", + DestinationFrame = "GALACTIC", + }, + }, + }, + -- -- 67P Trail Module + { + Name = "67PTrail", + Parent = "SolarSystemBarycenter", + Renderable = { + Type = "RenderableTrailTrajectory", + Translation = { + Type = "SpiceTranslation", + Body = "CHURYUMOV-GERASIMENKO", + Observer = "SUN", + }, + Color = { 0.1, 0.9, 0.2 }, + StartTime = "2014 JAN 01 00:00:00.000", + EndTime = "2017 JAN 01 00:00:00.000", + SampleInterval = 3600, + }, + }, + --[[ + { + Name = "67PTrail", + Parent = "SolarSystemBarycenter", + Renderable = { + Type = "RenderableTrail", + Body = "CHURYUMOV-GERASIMENKO", + Frame = "GALACTIC", + Observer = "SUN", + + -- 3 Dummy values for compilation: + TropicalOrbitPeriod = 1000.0, + EarthOrbitRatio = 2, + DayLength = 50, + -- End of Dummy values + + RGB = { 0.1, 0.9, 0.2 }, + Textures = { + Type = "simple", + Color = "textures/glare.png" + }, + }, + GuiName = "/Solar/67PTrail" + } + ]] +} \ No newline at end of file diff --git a/data/scene/rosetta/67P/67P_rotated_5_130.obj.torrent b/data/scene/missions/rosetta/67P/67P_rotated_5_130.obj.torrent similarity index 100% rename from data/scene/rosetta/67P/67P_rotated_5_130.obj.torrent rename to data/scene/missions/rosetta/67P/67P_rotated_5_130.obj.torrent diff --git a/data/scene/rosetta/67P/rosettaimages.torrent b/data/scene/missions/rosetta/67P/rosettaimages.torrent similarity index 100% rename from data/scene/rosetta/67P/rosettaimages.torrent rename to data/scene/missions/rosetta/67P/rosettaimages.torrent diff --git a/data/scene/rosetta/rosetta/Rosetta.torrent b/data/scene/missions/rosetta/rosetta/Rosetta.torrent similarity index 100% rename from data/scene/rosetta/rosetta/Rosetta.torrent rename to data/scene/missions/rosetta/rosetta/Rosetta.torrent diff --git a/data/scene/rosetta/rosetta/rosetta.data b/data/scene/missions/rosetta/rosetta/rosetta.data similarity index 100% rename from data/scene/rosetta/rosetta/rosetta.data rename to data/scene/missions/rosetta/rosetta/rosetta.data diff --git a/data/scene/rosetta/rosetta/rosetta.mod b/data/scene/missions/rosetta/rosetta/rosetta.mod similarity index 88% rename from data/scene/rosetta/rosetta/rosetta.mod rename to data/scene/missions/rosetta/rosetta/rosetta.mod index 73b8181ecc..930a4941df 100644 --- a/data/scene/rosetta/rosetta/rosetta.mod +++ b/data/scene/missions/rosetta/rosetta/rosetta.mod @@ -62,7 +62,7 @@ return { Parent = "SolarSystemBarycenter", Transform = { Translation = { - Type = "SpiceEphemeris", + Type = "SpiceTranslation", Body = "ROSETTA", Observer = "SUN", Kernels = RosettaKernels @@ -273,7 +273,7 @@ return { -- translated Transform = { Translation = { - Type = "SpiceEphemeris", + Type = "SpiceTranslation", Body = "PHILAE", Observer = "CHURYUMOV-GERASIMENKO", Kernels = RosettaKernels @@ -365,52 +365,32 @@ return { Name = "RosettaCometTrail", Parent = "67PBarycenter", Renderable = { - Type = "RenderableTrailNew", - -- Spice - Body = "ROSETTA", - Frame = "GALACTIC", - Observer = "CHURYUMOV-GERASIMENKO", - -- Optional rendering properties - LineColor = { 0.288, 0.375, 0.934 }, - PointColor = { 0.9, 0.2, 0.9 }, - LineFade = 0.0, -- [0,1] - RenderPart = 0.5, -- [0,1] - LineWidth = 2, - ShowTimeStamps = false, - RenderFullTrail = false, - -- Time interval - TimeRange = { - Start = "2014 AUG 01 12:00:00", - End = "2016 SEP 30 12:00:00" + Type = "RenderableTrailTrajectory", + Translation = { + Type = "SpiceTranslation", + Body = "ROSETTA", + Observer = "CHURYUMOV-GERASIMENKO", }, - SampleDeltaTime = 3600, -- Seconds between each point - SubSamples = 3, + Color = { 0.288, 0.375, 0.934 }, + StartTime = "2014 AUG 01 12:00:00", + EndTime = "2016 SEP 30 12:00:00", + SampleInterval = 3600, }, }, { Name = "PhilaeTrail", Parent = "67PBarycenter", Renderable = { - Type = "RenderableTrailNew", - -- Spice - Body = "PHILAE", - Frame = "GALACTIC", - Observer = "CHURYUMOV-GERASIMENKO", - -- Optional rendering properties - LineColor = { 1.0, 1.0, 1.0 }, - PointColor = { 0.9, 0.2, 0.9 }, - LineFade = 0.0, -- [0,1] - RenderPart = 0.5, -- [0,1] - LineWidth = 2, - ShowTimeStamps = false, - RenderFullTrail = false, - -- Time interval - TimeRange = { - Start = "2014 NOV 12 08:35:00", - End = "2014 NOV 12 17:00:00" + Type = "RenderableTrailTrajectory", + Translation = { + Type = "SpiceTranslation", + Body = "PHILAE", + Observer = "CHURYUMOV-GERASIMENKO", }, - SampleDeltaTime = 2, -- Seconds between each point - SubSamples = 0, + Color = { 0.8, 0.5, 1.0 }, + StartTime = "2014 NOV 12 08:35:00", + EndTime = "2014 NOV 12 17:00:00", + SampleInterval = 2, }, }, { @@ -437,6 +417,9 @@ return { }, PotentialTargets = { "CHURYUMOV-GERASIMENKO" + }, + FrameConversions = { + ["CHURYUMOV-GERASIMENKO"] = "67P/C-G_CK" } }, }, diff --git a/data/scene/moon/moon.mod b/data/scene/moon/moon.mod index 586cdc1081..b58b056dcb 100644 --- a/data/scene/moon/moon.mod +++ b/data/scene/moon/moon.mod @@ -30,7 +30,7 @@ return { }, Transform = { Translation = { - Type = "SpiceEphemeris", + Type = "SpiceTranslation", Body = "MOON", Observer = "EARTH BARYCENTER", Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" @@ -47,19 +47,15 @@ return { Name = "MoonTrail", Parent = "EarthBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "MOON", - Frame = "GALACTIC", - Observer = "EARTH BARYCENTER", - RGB = { 0.5, 0.3, 0.3 }, - TropicalOrbitPeriod = 60, - EarthOrbitRatio = 0.01, - DayLength = 1.0, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "MOON", + Observer = "EARTH BARYCENTER", + }, + Color = { 0.5, 0.3, 0.3 }, + Period = 27, + Resolution = 1000 }, } } diff --git a/data/scene/neptune/neptune.mod b/data/scene/neptune/neptune.mod index 2a44ae7098..5967f0a8fe 100644 --- a/data/scene/neptune/neptune.mod +++ b/data/scene/neptune/neptune.mod @@ -3,6 +3,14 @@ return { { Name = "NeptuneBarycenter", Parent = "SolarSystemBarycenter", + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "NEPTUNE BARYCENTER", + Observer = "SUN", + Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" + } + } }, -- Neptune module @@ -23,36 +31,28 @@ return { Color = "textures/neptune.jpg", }, }, - Ephemeris = { - Type = "Spice", - Body = "NEPTUNE BARYCENTER", - Observer = "SUN", - Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" - }, - Rotation = { - Type = "Spice", - Frame = "IAU_NEPTUNE", - Reference = "ECLIPJ2000" - }, + Translation = { + Rotation = { + Type = "SpiceRotation", + SourceFrame = "IAU_NEPTUNE", + DestinationFrame = "GALACTIC" + }, + } }, -- NeptuneTrail module { Name = "NeptuneTrail", - Parent = "NeptuneBarycenter", + Parent = "SolarSystemBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "NEPTUNE BARYCENTER", - Frame = "GALACTIC", - Observer = "SUN", - RGB = {0.2, 0.5, 1.0 }, - TropicalOrbitPeriod = 59799.9 , - EarthOrbitRatio = 163.73, - DayLength = 16.11, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "NEPTUNE BARYCENTER", + Observer = "SUN", + }, + Color = {0.2, 0.5, 1.0 }, + Period = 60200, + Resolution = 1000 }, } } diff --git a/data/scene/newhorizons.scene b/data/scene/newhorizons.scene index 812f30ee3d..ca5e4106c9 100644 --- a/data/scene/newhorizons.scene +++ b/data/scene/newhorizons.scene @@ -14,16 +14,8 @@ function preInitialization() openspace.spice.loadKernel("${SPICE}/naif0011.tls") openspace.spice.loadKernel("${SPICE}/pck00010.tpc") - -- openspace.time.setTime("2007-02-28T11:40:00.000") - - -- openspace.time.setTime("2015-07-08T15:57:45.00") - -- openspace.time.setTime("2015-07-12T07:41:00.00") - -- openspace.time.setTime("2015-07-12T15:43:00.00") - -- openspace.time.setTime("2015-07-12T22:19:20.00") - -- openspace.time.setTime("2015-07-13T20:59:00.00") - -- openspace.time.setTime("2015-07-14T02:41:55.00") openspace.time.setTime("2015-07-14T10:05:00.00") - openspace.time.setDeltaTime(0) + dofile(openspace.absPath('${SCRIPTS}/bind_keys_newhorizons.lua')) end @@ -61,17 +53,17 @@ return { "venus", "earth", "mars", - "saturn", + "saturn/saturn", "uranus", "neptune", - "newhorizons/pluto", - "newhorizons/jupiter", "stars", -- "stars-denver", "milkyway", -- "milkyway-eso", - "newhorizons/newhorizons", - "newhorizons/newhorizonsfov", + "missions/newhorizons/pluto", + "missions/newhorizons/jupiter", + "missions/newhorizons/newhorizons", + "missions/newhorizons/newhorizonsfov" } } diff --git a/data/scene/newhorizons/jupiter/jupiter/jupiter.mod b/data/scene/newhorizons/jupiter/jupiter/jupiter.mod deleted file mode 100644 index ccb6649f29..0000000000 --- a/data/scene/newhorizons/jupiter/jupiter/jupiter.mod +++ /dev/null @@ -1,137 +0,0 @@ -return { - -- Jupiter barycenter module - { - Name = "JupiterBarycenter", - Parent = "SolarSystemBarycenter", - Transform = { - Translation = { - Type = "SpiceEphemeris", - Body = "JUPITER BARYCENTER", - Observer = "SUN", - Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" - }, - }, - }, - -- JupiterProjection module - { - Name = "JupiterProjection", - Parent = "JupiterBarycenter", - Renderable = { - Type = "RenderablePlanetProjection", - Frame = "IAU_JUPITER", - Body = "JUPITER", - Geometry = { - Type = "SimpleSphere", - Radius = { 0.71492, 8 }, - Segments = 200, - }, - Textures = { - Type = "simple", - Color = "textures/jupiterFlipped_low.jpg", - Project = "textures/lorriTest1.jpg", - Sequencing = "true", - }, - Projection = { - --Sequence = "F:/JupiterFullSequence", - Sequence = "${OPENSPACE_DATA}/scene/newhorizons/jupiter/jupiter/ProjectionsOfInterest", - SequenceType = "image-sequence", - Observer = "NEW HORIZONS", - Target = "JUPITER", - Aberration = "NONE", - AspectRatio = 2 - }, - DataInputTranslation = { - Instrument = { - LORRI = { - DetectorType = "Camera", - Spice = {"NH_LORRI"}, - }, - }, - Target ={ - Read = { - "TARGET_NAME", - "INSTRUMENT_HOST_NAME", - "INSTRUMENT_ID", - "START_TIME", - "STOP_TIME", - "DETECTOR_TYPE", - --"SEQUENCE_ID", - }, - Convert = { - JRINGS = {"IMAGE-PLANE" }, - J1IO = {"IO" }, - J2EUROPA = {"EUROPA" }, - J6HIMALIA = {"IMAGE-PLANE" }, - J7ELARA = {"IMAGE-PLANE" }, - CALIBRATION = {"CALIBRATION" }, - JUPITER = {"JUPITER" }, - CALLISTO = {"CALLISTO" }, - GANYMEDE = {"GANYMEDE" }, - EARTH = {"EARTH" }, - NEWHORIZONS = {"NEW HORIZONS"}, - CCD = {"CAMERA" }, - FRAMECCD = {"SCANNER" }, - }, - }, - }, - Instrument = { - Name = "NH_LORRI", - Method = "ELLIPSOID", - Aberration = "NONE", - Fovy = 0.2907, - Aspect = 1, - Near = 0.2, - Far = 10000, - }, - PotentialTargets = { - "JUPITER", "IO", "EUROPA", "GANYMEDE", "CALLISTO" - } - }, - Transform = { - Rotation = { - Type = "SpiceRotation", - SourceFrame = "IAU_JUPITER", - DestinationFrame = "GALACTIC", - }, - }, - }, - { - Name = "JupiterText", - Parent = "JupiterProjection", - Renderable = { - Type = "RenderablePlane", - Size = {1.0, 7.5}, - Origin = "Center", - Billboard = true, - Texture = "textures/Jupiter-text.png", - BlendMode = "Additive" - }, - Transform = { - Translation = { - Type = "StaticEphemeris", - Position = {0, -100000000, 0} - }, - }, - }, - -- JupiterTrail module - { - Name = "JupiterTrail", - Parent = "SolarSystemBarycenter", - Renderable = { - Type = "RenderableTrail", - Body = "JUPITER BARYCENTER", - Frame = "GALACTIC", - Observer = "SUN", - RGB = { 0.8, 0.7, 0.7 }, - TropicalOrbitPeriod = 4330.595 , - EarthOrbitRatio = 11.857, - DayLength = 9.9259, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, - }, - } - -} diff --git a/data/scene/newhorizons/jupiter/jupiter/textures/defaultProj.png b/data/scene/newhorizons/jupiter/jupiter/textures/defaultProj.png deleted file mode 100644 index 1d48dc35f4..0000000000 Binary files a/data/scene/newhorizons/jupiter/jupiter/textures/defaultProj.png and /dev/null differ diff --git a/data/scene/newhorizons/newhorizonsfov/textures/glare_blue.png b/data/scene/newhorizons/newhorizonsfov/textures/glare_blue.png deleted file mode 100644 index ebae6637e2..0000000000 Binary files a/data/scene/newhorizons/newhorizonsfov/textures/glare_blue.png and /dev/null differ diff --git a/data/scene/newhorizons/newhorizonspath/newhorizonspath.mod b/data/scene/newhorizons/newhorizonspath/newhorizonspath.mod deleted file mode 100644 index d11cb2a8bb..0000000000 --- a/data/scene/newhorizons/newhorizonspath/newhorizonspath.mod +++ /dev/null @@ -1,19 +0,0 @@ -return { - -- NewHorizonsPath module - { - Name = "NewHorizonsPath", - Parent = "Root", - Renderable = { - Type = "RenderablePath", - Body = "NEW HORIZONS", - Frame = "GALACTIC", - Observer = "SUN", - RGB = { 0.8, 0.7, 0.7 }, - Textures = { - Type = "simple", - Color = "textures/glare_blue.png", - -- need to add different texture - }, - }, - } -} \ No newline at end of file diff --git a/data/scene/newhorizons/newhorizonspath/textures/glare.png b/data/scene/newhorizons/newhorizonspath/textures/glare.png deleted file mode 100644 index 7b7aa34b33..0000000000 Binary files a/data/scene/newhorizons/newhorizonspath/textures/glare.png and /dev/null differ diff --git a/data/scene/newhorizons/newhorizonspath/textures/glare_blue.png b/data/scene/newhorizons/newhorizonspath/textures/glare_blue.png deleted file mode 100644 index ebae6637e2..0000000000 Binary files a/data/scene/newhorizons/newhorizonspath/textures/glare_blue.png and /dev/null differ diff --git a/data/scene/newhorizons/newhorizonstrail/newhorizonstrail.mod b/data/scene/newhorizons/newhorizonstrail/newhorizonstrail.mod deleted file mode 100644 index e8a334b6ae..0000000000 --- a/data/scene/newhorizons/newhorizonstrail/newhorizonstrail.mod +++ /dev/null @@ -1,22 +0,0 @@ -return { - -- NewHorizonsTrail module - { - Name = "NewHorizonsTrail", - Parent = "Root", - Renderable = { - Type = "RenderableTrail", - Body = "NEW HORIZONS", - Frame = "GALACTIC", - Observer = "SUN", - RGB = { 0.1,0.01,0.30 }, - TropicalOrbitPeriod = 6330.595 , - EarthOrbitRatio = 0.857, - DayLength = 9.9259, - Textures = { - Type = "simple", - Color = "textures/glare_blue.png", - -- need to add different texture - }, - }, - } -} \ No newline at end of file diff --git a/data/scene/newhorizons/newhorizonstrail/textures/glare.png b/data/scene/newhorizons/newhorizonstrail/textures/glare.png deleted file mode 100644 index 7b7aa34b33..0000000000 Binary files a/data/scene/newhorizons/newhorizonstrail/textures/glare.png and /dev/null differ diff --git a/data/scene/newhorizons/newhorizonstrail/textures/glare_blue.png b/data/scene/newhorizons/newhorizonstrail/textures/glare_blue.png deleted file mode 100644 index ebae6637e2..0000000000 Binary files a/data/scene/newhorizons/newhorizonstrail/textures/glare_blue.png and /dev/null differ diff --git a/data/scene/newhorizons/pluto/pluto/pluto.mod b/data/scene/newhorizons/pluto/pluto/pluto.mod deleted file mode 100644 index c6bae149dd..0000000000 --- a/data/scene/newhorizons/pluto/pluto/pluto.mod +++ /dev/null @@ -1,277 +0,0 @@ -if UseAccurateNewHorizonsKernels then - NewHorizonsKernels = { - "${SPICE}/nh_kernels/spk/NavPE_de433_od122.bsp", - "${SPICE}/nh_kernels/spk/NavSE_plu047_od122.bsp" - } -else - NewHorizonsKernels = { - "${SPICE}/NewHorizonsKernels/nh_plu017.bsp" - } -end - -Files = { - low = "textures/pluto_large.jpg", - med = "textures/Shenk_180.jpg", - high = "textures/pmap_cyl_HR_LOR_lowres.jpg" -} -ColorTexture = Files[TextureResolution] - -return { - -- Pluto barycenter module - { - Name = "PlutoBarycenter", - Parent = "SolarSystemBarycenter", - Transform = { - Translation = { - Type = "SpiceEphemeris", - Body = "PLUTO BARYCENTER", - Observer = "SUN", - Kernels = NewHorizonsKernels - }, - }, - }, - -- PlutoProjection module - { - Name = "PlutoProjection", - Parent = "PlutoBarycenter", - Renderable = { - Type = "RenderablePlanetProjection", - Frame = "IAU_PLUTO", - Body = "PLUTO", - Geometry = { - Type = "SimpleSphere", - Radius = { 1.173 , 6 }, - Segments = 100 - }, - Textures = { - Type = "simple", - Color = ColorTexture, - Height = "textures/pluto_shenk_heightmap.jpg", - Project = "textures/3.jpg", - Sequencing = "true" - }, - Projection = { - Sequence = "${OPENSPACE_DATA}/scene/newhorizons/pluto/pluto/images", - EventFile = "${OPENSPACE_DATA}/scene/newhorizons/pluto/pluto/assets/core_v9h_obs_getmets_v8_time_fix_nofrcd_mld.txt", - SequenceType = "hybrid", - Observer = "NEW HORIZONS", - Target = "PLUTO", - Aberration = "NONE", - AspectRatio = 2 - }, - DataInputTranslation = { - Instrument = { - LORRI = { - DetectorType = "Camera", - Spice = {"NH_LORRI"}, - }, - RALPH_MVIC_PAN_FRAME = { - DetectorType = "Scanner", - StopCommand = "RALPH_ABORT", - Spice = {"NH_RALPH_MVIC_FT"}, - }, - RALPH_MVIC_COLOR = { - DetectorType = "Scanner", - StopCommand = "END_NOM", - Spice = { "NH_RALPH_MVIC_NIR", - "NH_RALPH_MVIC_METHANE", - "NH_RALPH_MVIC_RED", - "NH_RALPH_MVIC_BLUE" }, - }, - RALPH_LEISA = { - DetectorType = "Scanner", - StopCommand = "END_NOM", - Spice = {"NH_RALPH_LEISA"}, - }, - RALPH_MVIC_PAN1 = { - DetectorType = "Scanner", - StopCommand = "END_NOM", - Spice = {"NH_RALPH_MVIC_PAN1"}, - }, - RALPH_MVIC_PAN2 = { - DetectorType = "Scanner", - StopCommand = "END_NOM", - Spice = {"NH_RALPH_MVIC_PAN2"}, - }, - ALICE_Use_AIRGLOW = { - DetectorType = "Scanner", - StopCommand = "ALICE_END_PIXELLIST", - Spice = {"NH_ALICE_AIRGLOW"}, - }, - ALICE_Use_AIRGLOW = { - DetectorType = "Scanner", - StopCommand = "ALICE_END_HISTOGRAM", - Spice = {"NH_ALICE_AIRGLOW"}, - }, - ALICE_Use_SOCC = { - DetectorType = "Scanner", - StopCommand = "ALICE_END_PIXELLIST", - Spice = {"NH_ALICE_SOC"}, - }, - ALICE_Use_SOCC = { - DetectorType = "Scanner", - StopCommand = "ALICE_END_HISTOGRAM", - Spice = {"NH_ALICE_SOC"}, - }, - REX_START = { - DetectorType = "Scanner", - StopCommand = "REX_MODE_OFF", - Spice = { "NH_REX" }, - } - }, - Target ={ - Read = { - "TARGET_NAME", - "INSTRUMENT_HOST_NAME", - "INSTRUMENT_ID", - "START_TIME", - "STOP_TIME", - "DETECTOR_TYPE", - --"SEQUENCE_ID", - }, - Convert = { - PLUTO = {"PLUTO" }, - NEWHORIZONS = {"NEW HORIZONS"}, - CCD = {"CAMERA" }, - FRAMECCD = {"SCANNER" }, - }, - }, - }, - Instrument = { - Name = "NH_LORRI", - Method = "ELLIPSOID", - Aberration = "NONE", - Fovy = 0.2907, - Aspect = 1, - Near = 0.2, - Far = 10000, - }, - PotentialTargets = { - "PLUTO", - "CHARON", - "NIX", - "HYDRA", - "P5", - "P4", - } - }, - Transform = { - Translation = { - Type = "SpiceEphemeris", - Body = "PLUTO", - Observer = "PLUTO BARYCENTER", - Kernels = NewHorizonsKernels - }, - Rotation = { - Type = "SpiceRotation", - SourceFrame = "IAU_PLUTO", - DestinationFrame = "GALACTIC", - } - }, - }, - { - Name = "PlutoBarycenterLabel", - Parent = "PlutoBarycenter", - Renderable = { - Type = "RenderablePlane", - Billboard = true, - Size = { 5, 4 }, - Texture = "textures/barycenter.png", - Atmosphere = { - Type = "Nishita", -- for example, values missing etc etc - MieFactor = 1.0, - MieColor = {1.0, 1.0, 1.0} - } - }, - }, - { - Name = "PlutoText", - Parent = "PlutoProjection", - Renderable = { - Type = "RenderablePlane", - Size = {1.0, 6.3}, - Origin = "Center", - Billboard = true, - Texture = "textures/Pluto-Text.png", - BlendMode = "Additive" - }, - Transform = { - Translation = { - Type = "StaticEphemeris", - Position = {0, -2000000, 0} - }, - }, - }, - { - Name = "PlutoTexture", - Parent = "PlutoProjection", - Renderable = { - Type = "RenderablePlane", - Size = {1.0, 6.4}, - Origin = "Center", - Billboard = true, - ProjectionListener = false, - Texture = "textures/Pluto-Text.png" - }, - Transform = { - Translation = { - Type = "StaticEphemeris", - Position = {0, -4000000, 0} - }, - }, - }, - { - Name = "PlutoShadow", - Parent = "PlutoProjection", - Renderable = { - Type = "RenderableShadowCylinder", - TerminatorType = "PENUMBRAL", - LightSource = "SUN", - Observer = "NEW HORIZONS", - Body = "PLUTO", - BodyFrame = "IAU_PLUTO", - MainFrame = "GALACTIC", - Aberration = "NONE", - }, - }, - -- PlutoBarycentricTrail module - { - Name = "PlutoBarycentricTrail", - Parent = "PlutoBarycenter", - Renderable = { - Type = "RenderableTrail", - Body = "PLUTO", - Frame = "GALACTIC", - Observer = "PLUTO BARYCENTER", - RGB = {0.00,0.62,1.00}, - TropicalOrbitPeriod = 120 , - EarthOrbitRatio = 0.03, - DayLength = 1, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, - }, - }, - -- PlutoTrail module - { - Name = "PlutoTrail", - Parent = "SolarSystemBarycenter", - Renderable = { - Type = "RenderableTrail", - Body = "PLUTO BARYCENTER", - Frame = "GALACTIC", - Observer = "SUN", - RGB = { 0.3, 0.7, 0.3 }, - TropicalOrbitPeriod = 90588 , - EarthOrbitRatio = 248.02, - DayLength = 9.9259, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, - }, - } -} diff --git a/data/scene/osirisrex-noglobebrowsing.scene b/data/scene/osirisrex-noglobebrowsing.scene deleted file mode 100644 index e6a20d9bfa..0000000000 --- a/data/scene/osirisrex-noglobebrowsing.scene +++ /dev/null @@ -1,233 +0,0 @@ --- TextureResolution = "low" -TextureResolution = "med" --- TextureResolution = "high" - -local startTime = "2016 SEP 8 23:05:00.50" - -function preInitialization() - --[[ - The scripts in this function are executed after the scene is loaded but before the - scene elements have been initialized, thus they should be used to set the time at - which the scene should start and other settings that might determine initialization - critical objects. - ]]-- - - -- Load Spice Kernels - openspace.spice.loadKernel("${OPENSPACE_DATA}/spice/de430_1850-2150.bsp") - - -- background - -- SCLK kernels needs to be loaded before CK kernels (and generally first) - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/sclk/ORX_SCLKSCET.00000.tsc") - - -- This cannot be loaded correctly for some reason! - --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/dsk/RQ36mod.oct12_CCv0001.bds") - - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/fk/orx_v04.tf") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/ik/orx_lidar_v00.ti") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/ik/orx_ocams_v03.ti") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/ik/orx_otes_v00.ti") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/ik/orx_rexis_v00.ti") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/ik/orx_struct_v00.ti") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/ik/orx_navcam_v00.ti") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/ik/orx_ola_v00.ti") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/ik/orx_ovirs_v00.ti") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/ik/orx_stowcam_v00.ti") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/lsk/naif0011.tls") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/pck/bennu_SPH250m.tpc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/pck/bennu_v10.tpc") - - -- Low res SPK - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/spk/orx_160917_231024_pgaa3_day15m60_v1.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/spk/orx_160914_231024_pgaa3_day12m60_v1.bsp") - - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/spk/orx_160908_231024_pgaa3_day06m60_v1.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/spk/spk_orx_160908_231024_pgaa2_day06m60_v3.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/spk/orx_160908_231024_pgaa2_day06m60.bsp") - - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/spk/OREX_20160908_M60_complete.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/spk/OREX_20160904_M45_complete.bsp") - - -- SPK - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/spk/de421.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/spk/sb-101955-76.bsp") - - -- Nominal_Profile_LowRes - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/Approach_600s_20180816T230000_20181119T010000.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/Approach_NominalProfile_600s_20180816T230000_20181119T010000.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/DetailedSurvey_600s_20190108T000000_20190317T000000.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/DetailedSurvey_NominalProfile_600s_20190108T000000_20190317T000000.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/OrbitalA_600s_20181203T230000_20190109T000000.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/OrbitalA_NominalProfile_600s_20181203T230000_20190109T000000.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/OrbitalB_600s_20190316T000000_20190521T000000.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/OrbitalB_NominalProfile600s_20190316T000000_20190521T000000.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/PrelimSurvey_600s_20181119T230000_20181204T010000.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/PrelimSurvey_NominalProfile_600s_20181119T230000_20181204T010000.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/Recon_600s_20190519T000000_20190830T000000.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/Recon_NominalProfile_600s_20190519T000000_20190830T000000.bc") - - -- Nominal_Observations_Science - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/DustSearch_v1/Phase03_AP_DustSearch_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/LightCurve_v1/Phase03_AP_LightCurve_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/LightCurve_v1/Phase03_AP_LightCurve_2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/NatSatSearch_v1/Phase03_AP_SatSearch_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/NatSatSearch_v1/Phase03_AP_SatSearch_2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/PhaseFunction_v1/Phase03_AP_PhaseFunction_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_3.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_4.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_5.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_6.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_7.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_8.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_9_Forced4x4.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/SpectraMap_v1/Phase03_AP_SpectraMap_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/MapCamOLA_v1/Phase04_PS_MC_1_v1_1a.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/MapCamOLA_v1/Phase04_PS_MC_2_v1_1a.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/OLA_v1/Phase04_PS_OLA_Nominal_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/OLA_v1/Phase04_PS_OLA_Nominal_2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/OLA_v1/Phase04_PS_OLA_Nominal_3.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/OLA_v1/Phase04_PS_OLA_Nominal_4.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/PolyCam_v1/Phase04_PS_PolyCam_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/PolyCam_v1/Phase04_PS_PolyCam_2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/PolyCam_v1/Phase04_PS_PolyCam_3.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/PolyCam_v1/Phase04_PS_PolyCam_4.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/PolyCam_v1/Phase04_PS_PolyCam_5.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/PolyCam_v1/Phase04_PS_PolyCam_6.bc") - - --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19013_18_BBD1_info.TXT") - --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19014_16_BBD2_info.TXT") - --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19020_18_BBD3_info.TXT") - --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19021_19_BBD4_info.TXT") - --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/README.txt") - - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19013_18_BBD1_v2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19014_16_BBD2_v2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19020_18_BBD3_v2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19021_19_BBD4_v2.bc") - - - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/EquatorialStations_v1/Phase06_DS_Equatorial_Stations_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/EquatorialStations_v1/Phase06_DS_Equatorial_Stations_2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/EquatorialStations_v1/Phase06_DS_Equatorial_Stations_3.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/EquatorialStations_v1/Phase06_DS_Equatorial_Stations_4.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/EquatorialStations_v1/Phase06_DS_Equatorial_Stations_5.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/EquatorialStations_v1/Phase06_DS_Equatorial_Stations_6.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/EquatorialStations_v1/Phase06_DS_Equatorial_Stations_7.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/PlumeSearch_v1/Phase06_DS_Plume_Search_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/PlumeSearch_v1/Phase06_DS_Plume_Search_2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/07_OrbitalB/CandidateSampleSite_v1/Phase07_OB_CSS_Mapping_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/07_OrbitalB/CandidateSampleSite_v1/Phase07_OB_CSS_Mapping_2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/07_OrbitalB/CandidateSampleSite_v1/Phase07_OB_CSS_Mapping_3.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/07_OrbitalB/CandidateSampleSite_v2/CSS_Mapping_1.a") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/07_OrbitalB/CandidateSampleSite_v2/CSS_Mapping_2.a") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/07_OrbitalB/CandidateSampleSite_v2/CSS_Mapping_3.a") - - --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Case02_0Latitude.wmv") - --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Case05_20negLatitude.wmv") - --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Case08_40negLatitude.wmv") - --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Case11_60negLatitude.wmv") - - local case = 2 -- Right now we only have the image times for case 2 - - if case == 2 then - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/ORX_Recon_525mSortie_Case02.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/Recon_525mSortie_Case02_0Latitude.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/Recon_525mSortie_Case02_atl_19145_04.atf") - - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/ORX_Recon_225mSortie_Case02.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Recon_225mSortie_Case02_0Latitude.bc") - elseif case == 5 then - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/ORX_Recon_525mSortie_Case05.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/Recon_525mSortie_Case05_20negLatitude.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/Recon_525mSortie_Case05_atl_19145_04.atf") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/Recon_525mSortie_Case05_NominalProfile.bc") - - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/ORX_Recon_225mSortie_Case05.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Recon_225mSortie_Case05_20negLatitude.bc") - elseif case == 8 then - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/Recon_525mSortie_Case08_NominalProfile.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/ORX_Recon_225mSortie_Case08.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Recon_225mSortie_Case08_40negLatitude.bc") - elseif case == 11 then - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/ORX_Recon_225mSortie_Case11.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Recon_225mSortie_Case11_60negLatitude.bc") - end - - -- Load planetary constants - openspace.spice.loadKernel("${SPICE}/pck00010.tpc") - - dofile(openspace.absPath('${SCRIPTS}/bind_keys.lua')) - dofile(openspace.absPath('${SCRIPTS}/bind_keys_osirisrex.lua')) - - --local startTime = "2019 APR 16 12:03:00.00" - - openspace.scriptScheduler.load("${OPENSPACE_DATA}/scene/osirisrex/scheduled_scripts.lua") - - -- Removing the line below will cause all scripts prior to to be executed during initialization - -- openspace.scriptScheduler.skipTo(startTime); - -end - -function postInitialization() - --[[ - The scripts in this function are executed after all objects in the scene have been - created and initialized, but before the first render call. This is the place to set - graphical settings for the renderables. - ]]-- - openspace.printInfo("Setting default values") - openspace.setPropertyValue("Sun.renderable.enabled", false) - openspace.setPropertyValue("SunMarker.renderable.enabled", false) - openspace.setPropertyValue("EarthMarker.renderable.enabled", false) - --openspace.setPropertyValue("Constellation Bounds.renderable.enabled", false) - openspace.setPropertyValue("PlutoTrail.renderable.enabled", true) - openspace.setPropertyValue("PlutoTexture.renderable.enabled", false) - - openspace.setPropertyValue("MilkyWay.renderable.transparency", 0.55) - openspace.setPropertyValue("MilkyWay.renderable.segments", 50) - - -- Activate night textures and water masks - openspace.setPropertyValue("Earth.RenderableGlobe.WaterMasks", {0, 1}); - openspace.setPropertyValue("Earth.RenderableGlobe.NightTextures", {0, 1}); - openspace.setPropertyValue("Earth.RenderableGlobe.Atmosphere", true); - - openspace.printInfo("Done setting default values") - openspace.loadMission("${OPENSPACE_DATA}/scene/osirisrex/osirisrex/osirisrex.mission") - - openspace.time.setTime(startTime) - openspace.time.setDeltaTime(0) - - openspace.resetCameraDirection() -end - -return { - ScenePath = ".", - CommonFolder = "common", - Camera = { - Focus = "OsirisRex", - Position = {26974590199.661884, 76314608558.908020, -127086452897.101791}, - Rotation = {0.729548, -0.126024, 0.416827, 0.527382}, - }, - Modules = { - "sun", - "mercury", - -- "lodmercury", - "venus", - "earth", - "mars", - -- "lodearth", - -- "lodmoon", - -- "lodmars", - "jupiter", - "saturn", - "uranus", - "neptune", - "stars", - -- "stars-denver", - "milkyway", - -- "milkyway-eso", - --"imageplane", - "osirisrex", - } -} - diff --git a/data/scene/osirisrex.scene b/data/scene/osirisrex.scene index 44d4a4052e..e59ce808d3 100644 --- a/data/scene/osirisrex.scene +++ b/data/scene/osirisrex.scene @@ -1,8 +1,5 @@ --- TextureResolution = "low" -TextureResolution = "med" --- TextureResolution = "high" +KernelCase = 2 -- Right now we only have the image times for case 2 -local startTime = "2016 SEP 8 23:05:00.50" function preInitialization() --[[ @@ -12,160 +9,15 @@ function preInitialization() critical objects. ]]-- - -- Load Spice Kernels - openspace.spice.loadKernel("${OPENSPACE_DATA}/spice/de430_1850-2150.bsp") - - -- background - -- SCLK kernels needs to be loaded before CK kernels (and generally first) - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/sclk/ORX_SCLKSCET.00000.tsc") - - -- This cannot be loaded correctly for some reason! - --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/dsk/RQ36mod.oct12_CCv0001.bds") - - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/fk/orx_v04.tf") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/ik/orx_lidar_v00.ti") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/ik/orx_ocams_v03.ti") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/ik/orx_otes_v00.ti") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/ik/orx_rexis_v00.ti") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/ik/orx_struct_v00.ti") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/ik/orx_navcam_v00.ti") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/ik/orx_ola_v00.ti") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/ik/orx_ovirs_v00.ti") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/ik/orx_stowcam_v00.ti") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/lsk/naif0011.tls") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/pck/bennu_SPH250m.tpc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/pck/bennu_v10.tpc") - - -- Low res SPK - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/spk/orx_160917_231024_pgaa3_day15m60_v1.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/spk/orx_160914_231024_pgaa3_day12m60_v1.bsp") - - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/spk/orx_160908_231024_pgaa3_day06m60_v1.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/spk/spk_orx_160908_231024_pgaa2_day06m60_v3.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/spk/orx_160908_231024_pgaa2_day06m60.bsp") - - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/spk/OREX_20160908_M60_complete.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/spk/OREX_20160904_M45_complete.bsp") - - -- SPK - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/spk/de421.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/background/spk/sb-101955-76.bsp") - - -- Nominal_Profile_LowRes - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/Approach_600s_20180816T230000_20181119T010000.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/Approach_NominalProfile_600s_20180816T230000_20181119T010000.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/DetailedSurvey_600s_20190108T000000_20190317T000000.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/DetailedSurvey_NominalProfile_600s_20190108T000000_20190317T000000.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/OrbitalA_600s_20181203T230000_20190109T000000.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/OrbitalA_NominalProfile_600s_20181203T230000_20190109T000000.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/OrbitalB_600s_20190316T000000_20190521T000000.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/OrbitalB_NominalProfile600s_20190316T000000_20190521T000000.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/PrelimSurvey_600s_20181119T230000_20181204T010000.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/PrelimSurvey_NominalProfile_600s_20181119T230000_20181204T010000.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/Recon_600s_20190519T000000_20190830T000000.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Profile_LowRes/Recon_NominalProfile_600s_20190519T000000_20190830T000000.bc") - - -- Nominal_Observations_Science - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/DustSearch_v1/Phase03_AP_DustSearch_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/LightCurve_v1/Phase03_AP_LightCurve_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/LightCurve_v1/Phase03_AP_LightCurve_2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/NatSatSearch_v1/Phase03_AP_SatSearch_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/NatSatSearch_v1/Phase03_AP_SatSearch_2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/PhaseFunction_v1/Phase03_AP_PhaseFunction_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_3.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_4.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_5.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_6.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_7.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_8.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/ShapeModel_v1/Phase03_AP_ShapeModel_9_Forced4x4.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/03_Approach/SpectraMap_v1/Phase03_AP_SpectraMap_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/MapCamOLA_v1/Phase04_PS_MC_1_v1_1a.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/MapCamOLA_v1/Phase04_PS_MC_2_v1_1a.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/OLA_v1/Phase04_PS_OLA_Nominal_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/OLA_v1/Phase04_PS_OLA_Nominal_2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/OLA_v1/Phase04_PS_OLA_Nominal_3.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/OLA_v1/Phase04_PS_OLA_Nominal_4.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/PolyCam_v1/Phase04_PS_PolyCam_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/PolyCam_v1/Phase04_PS_PolyCam_2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/PolyCam_v1/Phase04_PS_PolyCam_3.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/PolyCam_v1/Phase04_PS_PolyCam_4.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/PolyCam_v1/Phase04_PS_PolyCam_5.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/04_PrelimSurvey/PolyCam_v1/Phase04_PS_PolyCam_6.bc") - - --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19013_18_BBD1_info.TXT") - --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19014_16_BBD2_info.TXT") - --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19020_18_BBD3_info.TXT") - --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19021_19_BBD4_info.TXT") - --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/README.txt") - - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19013_18_BBD1_v2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19014_16_BBD2_v2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19020_18_BBD3_v2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/BaseballDiamond_v2/atl_19021_19_BBD4_v2.bc") - - - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/EquatorialStations_v1/Phase06_DS_Equatorial_Stations_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/EquatorialStations_v1/Phase06_DS_Equatorial_Stations_2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/EquatorialStations_v1/Phase06_DS_Equatorial_Stations_3.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/EquatorialStations_v1/Phase06_DS_Equatorial_Stations_4.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/EquatorialStations_v1/Phase06_DS_Equatorial_Stations_5.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/EquatorialStations_v1/Phase06_DS_Equatorial_Stations_6.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/EquatorialStations_v1/Phase06_DS_Equatorial_Stations_7.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/PlumeSearch_v1/Phase06_DS_Plume_Search_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/06_DetailedSurvey/PlumeSearch_v1/Phase06_DS_Plume_Search_2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/07_OrbitalB/CandidateSampleSite_v1/Phase07_OB_CSS_Mapping_1.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/07_OrbitalB/CandidateSampleSite_v1/Phase07_OB_CSS_Mapping_2.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/07_OrbitalB/CandidateSampleSite_v1/Phase07_OB_CSS_Mapping_3.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/07_OrbitalB/CandidateSampleSite_v2/CSS_Mapping_1.a") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/07_OrbitalB/CandidateSampleSite_v2/CSS_Mapping_2.a") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/07_OrbitalB/CandidateSampleSite_v2/CSS_Mapping_3.a") - - --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Case02_0Latitude.wmv") - --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Case05_20negLatitude.wmv") - --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Case08_40negLatitude.wmv") - --openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Case11_60negLatitude.wmv") - - local case = 2 -- Right now we only have the image times for case 2 - - if case == 2 then - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/ORX_Recon_525mSortie_Case02.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/Recon_525mSortie_Case02_0Latitude.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/Recon_525mSortie_Case02_atl_19145_04.atf") - - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/ORX_Recon_225mSortie_Case02.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Recon_225mSortie_Case02_0Latitude.bc") - elseif case == 5 then - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/ORX_Recon_525mSortie_Case05.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/Recon_525mSortie_Case05_20negLatitude.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/Recon_525mSortie_Case05_atl_19145_04.atf") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/Recon_525mSortie_Case05_NominalProfile.bc") - - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/ORX_Recon_225mSortie_Case05.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Recon_225mSortie_Case05_20negLatitude.bc") - elseif case == 8 then - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/525m_Sortie_v2/Recon_525mSortie_Case08_NominalProfile.bc") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/ORX_Recon_225mSortie_Case08.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Recon_225mSortie_Case08_40negLatitude.bc") - elseif case == 11 then - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/ORX_Recon_225mSortie_Case11.bsp") - openspace.spice.loadKernel("${SPICE}/OsirisRexKernels/Nominal_Observations_Science/08_Recon/225m_Sortie_v2/Recon_225mSortie_Case11_60negLatitude.bc") - end - - -- Load planetary constants + openspace.spice.loadKernel("${SPICE}/naif0011.tls") openspace.spice.loadKernel("${SPICE}/pck00010.tpc") - dofile(openspace.absPath('${SCRIPTS}/bind_keys.lua')) dofile(openspace.absPath('${SCRIPTS}/bind_keys_osirisrex.lua')) --local startTime = "2019 APR 16 12:03:00.00" + openspace.time.setTime("2016 SEP 8 23:00:00.500") - openspace.scriptScheduler.load("${OPENSPACE_DATA}/scene/osirisrex/scheduled_scripts.lua") - - -- Removing the line below will cause all scripts prior to to be executed during initialization - -- openspace.scriptScheduler.skipTo(startTime); + openspace.scriptScheduler.loadFile("${OPENSPACE_DATA}/scene/missions/osirisrex/scheduled_scripts.lua") end @@ -188,14 +40,11 @@ function postInitialization() -- Activate night textures and water masks openspace.setPropertyValue("Earth.RenderableGlobe.WaterMasks", {0, 1}); - openspace.setPropertyValue("Earth.RenderableGlobe.NightTextures", {0, 1}); + openspace.setPropertyValue("Earth.RenderableGlobe.NightLayers", {0, 1}); openspace.setPropertyValue("Earth.RenderableGlobe.Atmosphere", true); openspace.printInfo("Done setting default values") - openspace.loadMission("${OPENSPACE_DATA}/scene/osirisrex/osirisrex/osirisrex.mission") - - openspace.time.setTime(startTime) - openspace.time.setDeltaTime(0) + openspace.loadMission("${OPENSPACE_DATA}/scene/missions/osirisrex/osirisrex/osirisrex.mission") openspace.resetCameraDirection() end @@ -210,11 +59,11 @@ return { }, Modules = { "sun", - "lodmercury", + "mercury", "venus", - "lodearth", - "lodmoon", - "lodmars", + "lodglobes/lodearth", + "moon", + "mars", "jupiter", "saturn", "uranus", @@ -223,8 +72,7 @@ return { -- "stars-denver", "milkyway", -- "milkyway-eso", - --"imageplane", - "osirisrex", + "missions/osirisrex", } } diff --git a/data/scene/osirisrex/bennu/bennu.mod b/data/scene/osirisrex/bennu/bennu.mod deleted file mode 100644 index 6ab9afaa94..0000000000 --- a/data/scene/osirisrex/bennu/bennu.mod +++ /dev/null @@ -1,123 +0,0 @@ -local BENNU_BODY = "2101955" - -return { - ------------------------ - -- Bennu -- - ------------------------ - { - Name = "BennuBarycenter", - Parent = "SolarSystemBarycenter", - Transform = { - Translation = { - Type = "SpiceEphemeris", - Body = BENNU_BODY, - Observer = "SUN", - }, - }, - }, - { - Name = "Bennu2", - Parent = "BennuBarycenter", - - Renderable = { - Type = "RenderableModelProjection", - Body = BENNU_BODY, - Geometry = { - Type = "MultiModelGeometry", - GeometryFile = "models/BennuTextured.obj", - Magnification = 0, - }, - Shading = { - PerformShading = true, - Fadeable = false, - Ghosting = false, - }, - Textures = { - Type = "simple", - Color = "textures/gray.png", - Project = "textures/defaultProj.png", - Default = "textures/defaultProj.png" - }, - Rotation = { - Source = "IAU_BENNU", - Destination = "GALACTIC" - }, - Projection = { - Sequence = "InstrumentTimes", - SequenceType = "instrument-times", - Observer = "OSIRIS-REX", - Target = BENNU_BODY, - Aberration = "NONE", - AspectRatio = 2 - }, - DataInputTranslation = { - Instruments = { - ORX_OCAMS_POLYCAM = { - DetectorType = "Camera", - Spice = {"ORX_OCAMS_POLYCAM"}, - Files = { - "BaseballDiamond_PolyCam.txt", - --"OrbitalB_Site08_PolyCamImages.txt", - "Recon_225m_Equatorial_PolyCam.txt", - }, - }, - ORX_REXIS = { - DetectorType = "Camera", - Spice = {"ORX_REXIS"}, - Files = { - "DetailedSurvey_EquatorialStations_Spectrometers.txt", - "Recon_225m_Equatorial_spectrometers.txt", - "Recon_525m_Equatorial_spectrometers.txt", - }, - }, - }, - Target = { - Body = BENNU_BODY, -- Do we need this? - }, - }, - - Instrument = { -- INVALID DATA - JUST FOR TESTING - Name = "ORX_OCAMS_POLYCAM", - Method = "ELLIPSOID", - Aberration = "NONE", - Fovy = 0.792, - Aspect = 1, - Near = 0.01, - Far = 1000000, - }, - }, - - Transform = { - Rotation = { - Type = "SpiceRotation", - SourceFrame = "IAU_BENNU", - DestinationFrame = "GALACTIC", - }, - }, - }, - { - Name = "BennuTrail", - Parent = "SolarSystemBarycenter", - Renderable = { - Type = "RenderableTrailNew", - -- Spice - Body = BENNU_BODY, - Frame = "GALACTIC", - Observer = "SUN", - -- Optional rendering properties - LineColor = { 0.4, 0.0, 0.7}, - PointColor = { 0.4, 0.0, 0.7}, - LineFade = 0, -- [0,1] - RenderPart = 0.12, - LineWidth = 2, - ShowTimeStamps = false, - -- Time interval - TimeRange = { - Start = "2015 JAN 01 00:00:00.000", - End = "2023 MAY 31 00:00:00.000", - }, - SampleDeltaTime = 3600, -- Seconds between each point - SubSamples = 0, - }, - }, -} diff --git a/data/scene/osirisrex/osirisrex/osirisrex.mod b/data/scene/osirisrex/osirisrex/osirisrex.mod deleted file mode 100644 index d0c8918d2f..0000000000 --- a/data/scene/osirisrex/osirisrex/osirisrex.mod +++ /dev/null @@ -1,267 +0,0 @@ -local BENNU_BODY = "2101955" - -return { - ------------------------ - -- Osiris Rex -- - ------------------------ - { - Name = "OsirisRex", - Parent = "SolarSystemBarycenter", - Renderable = { - Type = "RenderableModel", - Body = "OSIRIS-REX", - Geometry = { - Type = "MultiModelGeometry", - GeometryFile = "models/orx_base_resized_12_sep_2016.obj", - Magnification = 0, - }, - Textures = { - Type = "simple", - Color = "textures/osirisTex.png", - }, - Shading = { - PerformShading = true, - Fadeable = false, - Ghosting = false, - }, - }, - Transform = { - Translation = { - Type = "SpiceEphemeris", - Body = "OSIRIS-REX", - Observer = "SUN", - }, - Rotation = { - Type = "SpiceRotation", - SourceFrame = "ORX_SPACECRAFT", - DestinationFrame = "GALACTIC", - }, - }, - }, - { - Name = "ORX_OCAMS_POLYCAM", - Parent = "OsirisRex", - Renderable = { - Type = "RenderableModel", - Body = "OSIRIS-REX", - Geometry = { - Type = "MultiModelGeometry", - GeometryFile = "models/orx_polycam_resized_12_sep_2016.obj", - Magnification = 0, - }, - Textures = { - Type = "simple", - Color = "textures/osirisTex.png", - }, - Shading = { - PerformShading = true, - Fadeable = false, - Ghosting = false, - }, - }, - Transform = { - Translation = { - Type = "StaticEphemeris", - Position = {-0.2476, 0.2710, 0.3364}, - }, - Rotation = { - Type = "SpiceRotation", - SourceFrame = "ORX_OCAMS_POLYCAM", - DestinationFrame = "ORX_SPACECRAFT", - }, - }, - }, - { - Name = "ORX_REXIS", - Parent = "OsirisRex", - Renderable = { - Type = "RenderableModel", - Body = "OSIRIS-REX", - Geometry = { - Type = "MultiModelGeometry", - GeometryFile = "models/orx_rexis_resized_12_sep_2016.obj", - Magnification = 0, - }, - Textures = { - Type = "simple", - Color = "textures/osirisTex.png", - }, - Shading = { - PerformShading = true, - Fadeable = false, - Ghosting = false, - }, - }, - Transform = { - Translation = { - Type = "StaticEphemeris", - Position = {0, 0.3371, 0.2712}, - }, - Rotation = { - Type = "SpiceRotation", - SourceFrame = "ORX_REXIS", - DestinationFrame = "ORX_SPACECRAFT", - }, - }, - }, - { - Name = "POLYCAM FOV", - Parent = "ORX_OCAMS_POLYCAM", - Renderable = { - Type = "RenderableFov", - Body = "OSIRIS-REX", - Frame = "ORX_OCAMS_POLYCAM", - RGB = { 0.8, 0.7, 0.7 }, - Instrument = { - Name = "ORX_OCAMS_POLYCAM", - Method = "ELLIPSOID", - Aberration = "NONE", - }, - PotentialTargets = { - BENNU_BODY -- Bennu - } - }, - }, - { - Name = "REXIS FOV", - Parent = "ORX_REXIS", - Renderable = { - Type = "RenderableFov", - Body = "OSIRIS-REX", - Frame = "ORX_REXIS", - RGB = { 0.8, 0.7, 0.7 }, - Instrument = { - Name = "ORX_REXIS", - Method = "ELLIPSOID", - Aberration = "NONE", - }, - PotentialTargets = { - BENNU_BODY -- Bennu - } - }, - }, - --[[ - -- Latest image taken by POLYCAM - { - Name = "ImagePlaneOsirisRex", - Parent = "Bennu2", - Renderable = { - Type = "RenderablePlaneProjection", - Frame = "IAU_BENNU", - DefaultTarget = BENNU_BODY, - Spacecraft = "OSIRIS-REX", - Instrument = "ORX_OCAMS_POLYCAM", - Moving = false, - Texture = "textures/defaultProj.png", - }, - Ephemeris = { - Type = "Static", - Position = {0, 0, 0, 1} - }, - }, - -- POLYCAM FoV square - { - Name = "FovImagePlane", - Parent = "Bennu2", - Renderable = { - Type = "RenderablePlaneProjection", - Frame = "IAU_BENNU", - DefaultTarget = BENNU_BODY, - Spacecraft = "OSIRIS-REX", - Instrument = "ORX_OCAMS_POLYCAM", - Moving = true, - Texture = "textures/defaultProj.png", - }, - Ephemeris = { - Type = "Static", - Position = {0, 0, 0, 1} - }, - }, - ]] - - -- Trail relative to Earth - { - Name = "OsirisRexTrailEarth", - Parent = "Earth", - Renderable = { - Type = "RenderableTrailNew", - -- Spice - Body = "OSIRIS-REX", - Frame = "IAU_EARTH", - Observer = "EARTH", - -- Optional rendering properties - LineColor = { 0.9, 0.9, 0.0 }, - PointColor = { 0.9, 0.9, 0.0 }, - LineFade = 0.0, -- [0,1] - RenderPart = 1, - LineWidth = 2, - ShowTimeStamps = false, - RenderFullTrail = false, - -- Time interval - TimeRange = { - Start = "2016 SEP 8 23:05:00.50", - End = "2016 SEP 9 00:05:00", - }, - SampleDeltaTime = 60, -- Seconds between each point - SubSamples = 59, - }, - }, - - -- Trail relative to solar system barycenter - { - Name = "OsirisRexTrailSolarSystem", - Parent = "SolarSystemBarycenter", - Renderable = { - Type = "RenderableTrailNew", - -- Spice - Body = "OSIRIS-REX", - Frame = "GALACTIC", - Observer = "SUN", - -- Optional rendering properties - LineColor = { 0.2, 0.9, 0.2 }, - PointColor = { 0.2, 0.9, 0.2 }, - LineFade = 0.0, -- [0,1] - RenderPart = 0.13, - LineWidth = 2, - ShowTimeStamps = false, - RenderFullTrail = false, - -- Time interval - TimeRange = { - Start = "2016 SEP 8 23:05:00.50", - End = "2023 SEP 24 12:00:00", - }, - SampleDeltaTime = 3600, -- Seconds between each point - SubSamples = 0, - }, - }, - - -- Trail relative to Bennu - { - Name = "OsirisRexTrailBennu", - Parent = "BennuBarycenter", - Renderable = { - Type = "RenderableTrailNew", - -- Spice - Body = "OSIRIS-REX", - Frame = "GALACTIC", - Observer = BENNU_BODY, - -- Optional rendering properties - LineColor = { 0.9, 0.2, 0.9 }, - PointColor = { 0.9, 0.2, 0.9 }, - LineFade = 0.5, -- [0,1] - RenderPart = 0.06, - LineWidth = 2, - ShowTimeStamps = false, - RenderFullTrail = false, - -- Time interval - TimeRange = { - Start = "2016 SEP 8 23:05:00.50", - End = "2023 SEP 24 12:00:00", - }, - SampleDeltaTime = 3600, -- Seconds between each point - SubSamples = 3, - }, - }, - - -} diff --git a/data/scene/pluto/pluto.data b/data/scene/pluto/pluto.data index 264a9ff830..db86c15f8c 100644 --- a/data/scene/pluto/pluto.data +++ b/data/scene/pluto/pluto.data @@ -1,6 +1,7 @@ return { FileRequest = { { Identifier = "charon_textures", Destination = "textures", Version = 1 }, - { Identifier = "pluto_textures", Destination = "textures", Version = 4 } + { Identifier = "pluto_textures", Destination = "textures", Version = 4 }, + { Identifier = "pluto_spice", Destination = "${SPICE}", Version = 1 } } } \ No newline at end of file diff --git a/data/scene/pluto/pluto.mod b/data/scene/pluto/pluto.mod index e8bdf8b37e..88346771ef 100644 --- a/data/scene/pluto/pluto.mod +++ b/data/scene/pluto/pluto.mod @@ -3,14 +3,18 @@ return { { Name = "PlutoBarycenter", Parent = "SolarSystemBarycenter", - Ephemeris = { - Type = "Spice", - Body = "PLUTO BARYCENTER", - Observer = "SUN", - Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp", - }, + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "PLUTO BARYCENTER", + Observer = "SUN", + Kernels = { + "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp", + "${OPENSPACE_DATA}/spice/plu055.bsp", + } + } + } }, - -- Pluto module { Name = "Pluto", @@ -34,19 +38,21 @@ return { MieColor = {1.0, 1.0, 1.0} } }, - Ephemeris = { - Type = "Spice", - Body = "PLUTO", - Observer = "PLUTO BARYCENTER", - Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp", - }, - Rotation = { - Type = "Spice", - Frame = "IAU_PLUTO", - Reference = "GALACTIC" - }, + Transformation = { + Translation = { + Type = "SpiceTranslation", + Body = "PLUTO", + Observer = "PLUTO BARYCENTER", + Kernels = "${OPENSPACE_DATA}/spice/plu055.bsp", + }, + Rotation = { + Type = "Spice", + SourceFrame = "IAU_PLUTO", + DestinationFrame = "GALACTIC" + } + } }, -{ + { Name = "Charon", Parent = "PlutoBarycenter", Renderable = { @@ -68,59 +74,67 @@ return { MieColor = {1.0, 1.0, 1.0} } }, - Ephemeris = { - Type = "Spice", - Body = "CHARON", - Observer = "PLUTO BARYCENTER", - Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" - }, - Rotation = { - Type = "Spice", - Frame = "IAU_CHARON", - Reference = "ECLIPJ2000" - }, + Transformation = { + Translation = { + Type = "SpiceTranslation", + Body = "CHARON", + Observer = "PLUTO BARYCENTER", + Kernels = "${OPENSPACE_DATA}/spice/plu055.bsp", + }, + Rotation = { + Type = "Spice", + SourceFrame = "IAU_CHARON", + DestinationFrame = "GALACTIC" + } + } }, -- CharonTrail module { Name = "CharonTrail", Parent = "PlutoBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "CHARON", - Frame = "GALACTIC", - Observer = "PLUTO BARYCENTER", - RGB = {0.00,0.62,1.00}, - TropicalOrbitPeriod = 120 , - EarthOrbitRatio = 0.03, - DayLength = 1, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "CHARON", + Observer = "PLUTO BARYCENTER", + }, + Color = {0.00,0.62,1.00}, + Period = 6.38725, + Resolution = 1000, }, - } - --[[ + }, -- PlutoTrail module { - Name = "PlutoTrail", + Name = "PlutoTrailSolarSystem", Parent = "SolarSystemBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "PLUTO BARYCENTER", - Frame = "GALACTIC", - Observer = "SUN", - RGB = {0.58, 0.61, 1.00}, - TropicalOrbitPeriod = 59799.9 , - EarthOrbitRatio = 163.73, - DayLength = 16.11, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "PLUTO BARYCENTER", + Observer = "SUN", + }, + Color = {0.58, 0.61, 1.00}, + Period = 247.92 * 365.242, + Resolution = 1000 + }, + GuiName = "/Solar/PlutoTrail" + }, + { + Name = "PlutoTrailPluto", + Parent = "PlutoBarycenter", + Renderable = { + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "PLUTO", + Observer = "PLUTO BARYCENTER", + }, + Color = {0.58, 0.61, 1.00}, + Period = 6.38725, + Resolution = 1000 }, GuiName = "/Solar/PlutoTrail" } ---]] } diff --git a/data/scene/rosetta.scene b/data/scene/rosetta.scene index befa637e83..361397876f 100644 --- a/data/scene/rosetta.scene +++ b/data/scene/rosetta.scene @@ -18,10 +18,6 @@ function preInitialization() -- Shadow flyby -- openspace.time.setTime("2015-02-14T12:00:00.000") - - -- openspace.time.setTime("2015-07-29T06:02:10.000") - -- openspace.time.setTime("2014 AUG 21 18:00:00") - -- openspace.time.setTime("2015 SEP 10 19:39:00") dofile(openspace.absPath('${SCRIPTS}/bind_keys_rosetta.lua')) end @@ -59,12 +55,12 @@ return { "earth", "mars", "jupiter/jupiter", - "saturn", + "saturn/saturn", "uranus", - "neptune", + -- "neptune", "stars", "milkyway", - "rosetta", + "missions/rosetta", } } diff --git a/data/scene/rosetta/67P/67P.mod b/data/scene/rosetta/67P/67P.mod deleted file mode 100644 index 84af8afce9..0000000000 --- a/data/scene/rosetta/67P/67P.mod +++ /dev/null @@ -1,143 +0,0 @@ -return { - -- Comet 67P Body module - { - Name = "67PBarycenter", - Parent = "SolarSystemBarycenter", - Transform = { - Translation = { - Type = "SpiceEphemeris", - Body = "CHURYUMOV-GERASIMENKO", - Observer = "SUN", - }, - }, - }, - { - Name = "67P", - Parent = "67PBarycenter", - - Renderable = { - Type = "RenderableModelProjection", - Body = "CHURYUMOV-GERASIMENKO", - Geometry = { - Type = "MultiModelGeometry", - GeometryFile = "obj/67P_rotated_5_130.obj", - Magnification = 0, - }, - Textures = { - Type = "simple", - Color = "textures/gray.jpg", - -- Color = "textures/may9_map.jpg", - Project = "textures/defaultProj.png", - Default = "textures/defaultProj.png" - }, - Rotation = { - Source = "67P/C-G_CK", - Destination = "GALACTIC" - }, - Projection = { - Sequence = "rosettaimages", - SequenceType = "image-sequence", - Observer = "ROSETTA", - Target = "CHURYUMOV-GERASIMENKO", - Aberration = "NONE", - TextureMap = true, - ShadowMap = true - }, - DataInputTranslation = { - Instrument = { - NAVCAM = { - DetectorType = "Camera", - Spice = {"ROS_NAVCAM-A"}, - }, - }, - Target = { - Read = { - "TARGET_NAME", - "INSTRUMENT_HOST_NAME", - "INSTRUMENT_ID", - "START_TIME", - "STOP_TIME", - }, - Convert = { - CHURYUMOV = {"CHURYUMOV-GERASIMENKO"}, - ROSETTA = {"ROSETTA" }, - --NAVCAM = {"NAVCAM"}, - ["ROSETTA-ORBITER"] = {"ROSETTA" }, - CHURYUMOVGERASIMENKO11969R1 = {"CHURYUMOV-GERASIMENKO"}, - CHURYUMOVGERASIMENKO = {"CHURYUMOV-GERASIMENKO"}, - ["CHURYUMOV-GERASIMENKO1(1969R1)"] = {"CHURYUMOV-GERASIMENKO"}, - --NAVIGATIONCAMERA = {"NAVCAM" }, - }, - }, - }, - - Instrument = { - Name = "ROS_NAVCAM-A", - Method = "ELLIPSOID", - Aberration = "NONE", - Fovy = 5.00, - Aspect = 1 - }, - BoundingSphereRadius = 5000.0 - }, - Transform = { - Rotation = { - Type = "SpiceRotation", - SourceFrame = "67P/C-G_CK", - DestinationFrame = "GALACTIC", - }, - }, - }, - -- 67P Trail Module - { - Name = "67PTrail", - Parent = "SolarSystemBarycenter", - Renderable = { - Type = "RenderableTrailNew", - -- Spice - Body = "CHURYUMOV-GERASIMENKO", - Frame = "GALACTIC", - Observer = "SUN", - -- Optional rendering properties - LineColor = { 0.1, 0.9, 0.2 }, - PointColor = { 0.1, 0.9, 0.2 }, - LineFade = 0.5, -- [0,1] - RenderPart = 0.5, - LineWidth = 2, - ShowTimeStamps = false, - RenderFullTrail = false, - -- Time interval - TimeRange = { - Start = "2014 JAN 01 00:00:00.000", - End = "2017 JAN 01 00:00:00.000", - }, - SampleDeltaTime = 3600, -- Seconds between each point - SubSamples = 0, - }, - }, - --[[ - { - Name = "67PTrail", - Parent = "SolarSystemBarycenter", - Renderable = { - Type = "RenderableTrail", - Body = "CHURYUMOV-GERASIMENKO", - Frame = "GALACTIC", - Observer = "SUN", - - -- 3 Dummy values for compilation: - TropicalOrbitPeriod = 1000.0, - EarthOrbitRatio = 2, - DayLength = 50, - -- End of Dummy values - - RGB = { 0.1, 0.9, 0.2 }, - Textures = { - Type = "simple", - Color = "textures/glare.png" - }, - }, - GuiName = "/Solar/67PTrail" - } - ]] -} \ No newline at end of file diff --git a/data/scene/saturn/dione/dione.data b/data/scene/saturn/dione/dione.data new file mode 100644 index 0000000000..924a314275 --- /dev/null +++ b/data/scene/saturn/dione/dione.data @@ -0,0 +1,5 @@ +return { + FileRequest = { + { Identifier = "dione_textures", Destination = "textures", Version = 1 } + }, +} \ No newline at end of file diff --git a/data/scene/saturn/dione/dione.mod b/data/scene/saturn/dione/dione.mod new file mode 100644 index 0000000000..d132bea897 --- /dev/null +++ b/data/scene/saturn/dione/dione.mod @@ -0,0 +1,47 @@ +return { + { + Name = "Dione", + Parent = "SaturnBarycenter", + Renderable = { + Type = "RenderablePlanet", + Frame = "IAU_DIONE", + Body = "DIONE", + Geometry = { + Type = "SimpleSphere", + Radius = { 0.563, 3 }, + Segments = 50 + }, + Textures = { + Color = "textures/dione.jpg" + } + }, + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "DIONE", + Observer = "SATURN BARYCENTER", + Kernels = "${OPENSPACE_DATA}/spice/sat375.bsp" + }, + Rotation = { + Type = "SpiceRotation", + SourceFrame = "IAU_ENCELADUS", + DestinationFrame = "GALACTIC" + } + } + }, + { + Name = "DioneTrail", + Parent = "SaturnBarycenter", + Renderable = { + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "DIONE", + Observer = "SATURN BARYCENTER", + }, + Color = { 0.5, 0.3, 0.3 }, + Period = 66 / 24, + Resolution = 1000 + } + } +} \ No newline at end of file diff --git a/data/scene/saturn/enceladus/enceladus.data b/data/scene/saturn/enceladus/enceladus.data new file mode 100644 index 0000000000..a31589f158 --- /dev/null +++ b/data/scene/saturn/enceladus/enceladus.data @@ -0,0 +1,5 @@ +return { + FileRequest = { + { Identifier = "enceladus_textures", Destination = "textures", Version = 1 } + }, +} \ No newline at end of file diff --git a/data/scene/saturn/enceladus/enceladus.mod b/data/scene/saturn/enceladus/enceladus.mod new file mode 100644 index 0000000000..1d3011e4c8 --- /dev/null +++ b/data/scene/saturn/enceladus/enceladus.mod @@ -0,0 +1,47 @@ +return { + { + Name = "Enceladus", + Parent = "SaturnBarycenter", + Renderable = { + Type = "RenderablePlanet", + Frame = "IAU_ENCELADUS", + Body = "ENCELADUS", + Geometry = { + Type = "SimpleSphere", + Radius = { 0.257, 3 }, + Segments = 50 + }, + Textures = { + Color = "textures/enceladus.jpg" + } + }, + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "ENCELADUS", + Observer = "SATURN BARYCENTER", + Kernels = "${OPENSPACE_DATA}/spice/sat375.bsp" + }, + Rotation = { + Type = "SpiceRotation", + SourceFrame = "IAU_ENCELADUS", + DestinationFrame = "GALACTIC" + } + } + }, + { + Name = "EnceladusTrail", + Parent = "SaturnBarycenter", + Renderable = { + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "ENCELADUS", + Observer = "SATURN BARYCENTER", + }, + Color = { 0.5, 0.3, 0.3 }, + Period = 33 / 24, + Resolution = 1000 + } + } +} \ No newline at end of file diff --git a/data/scene/saturn/iapetus/iapetus.data b/data/scene/saturn/iapetus/iapetus.data new file mode 100644 index 0000000000..0db25d34c1 --- /dev/null +++ b/data/scene/saturn/iapetus/iapetus.data @@ -0,0 +1,5 @@ +return { + FileRequest = { + { Identifier = "iapetus_textures", Destination = "textures", Version = 1 } + }, +} \ No newline at end of file diff --git a/data/scene/saturn/iapetus/iapetus.mod b/data/scene/saturn/iapetus/iapetus.mod new file mode 100644 index 0000000000..a390af3ec4 --- /dev/null +++ b/data/scene/saturn/iapetus/iapetus.mod @@ -0,0 +1,47 @@ +return { + { + Name = "Iapetus", + Parent = "SaturnBarycenter", + Renderable = { + Type = "RenderablePlanet", + Frame = "IAU_IAPETUS", + Body = "IAPETUS", + Geometry = { + Type = "SimpleSphere", + Radius = { 0.746, 3 }, + Segments = 50 + }, + Textures = { + Color = "textures/iapetus.jpg" + } + }, + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "IAPETUS", + Observer = "SATURN BARYCENTER", + Kernels = "${OPENSPACE_DATA}/spice/sat375.bsp" + }, + Rotation = { + Type = "SpiceRotation", + SourceFrame = "IAU_ENCELADUS", + DestinationFrame = "GALACTIC" + } + } + }, + { + Name = "IapetusTrail", + Parent = "SaturnBarycenter", + Renderable = { + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "IAPETUS", + Observer = "SATURN BARYCENTER", + }, + Color = { 0.5, 0.3, 0.3 }, + Period = 79, + Resolution = 1000 + } + } +} \ No newline at end of file diff --git a/data/scene/saturn/mimas/mimas.data b/data/scene/saturn/mimas/mimas.data new file mode 100644 index 0000000000..01d792a8d4 --- /dev/null +++ b/data/scene/saturn/mimas/mimas.data @@ -0,0 +1,5 @@ +return { + FileRequest = { + { Identifier = "mimas_textures", Destination = "textures", Version = 1 } + }, +} \ No newline at end of file diff --git a/data/scene/saturn/mimas/mimas.mod b/data/scene/saturn/mimas/mimas.mod new file mode 100644 index 0000000000..bf7b451d83 --- /dev/null +++ b/data/scene/saturn/mimas/mimas.mod @@ -0,0 +1,47 @@ +return { + { + Name = "Mimas", + Parent = "SaturnBarycenter", + Renderable = { + Type = "RenderablePlanet", + Frame = "IAU_MIMAS", + Body = "MIMAS", + Geometry = { + Type = "SimpleSphere", + Radius = { 0.28, 3 }, + Segments = 50 + }, + Textures = { + Color = "textures/mimas.jpg" + } + }, + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "MIMAS", + Observer = "SATURN BARYCENTER", + Kernels = "${OPENSPACE_DATA}/spice/sat375.bsp" + }, + Rotation = { + Type = "SpiceRotation", + SourceFrame = "IAU_MIMAS", + DestinationFrame = "GALACTIC" + } + } + }, + { + Name = "MimasTrail", + Parent = "SaturnBarycenter", + Renderable = { + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "MIMAS", + Observer = "SATURN BARYCENTER", + }, + Color = { 0.5, 0.3, 0.3 }, + Period = 23 / 24, + Resolution = 1000 + } + } +} \ No newline at end of file diff --git a/data/scene/saturn/rhea/rhea.data b/data/scene/saturn/rhea/rhea.data new file mode 100644 index 0000000000..9cf25ca314 --- /dev/null +++ b/data/scene/saturn/rhea/rhea.data @@ -0,0 +1,5 @@ +return { + FileRequest = { + { Identifier = "rhea_textures", Destination = "textures", Version = 1 } + }, +} \ No newline at end of file diff --git a/data/scene/saturn/rhea/rhea.mod b/data/scene/saturn/rhea/rhea.mod new file mode 100644 index 0000000000..623dd479a6 --- /dev/null +++ b/data/scene/saturn/rhea/rhea.mod @@ -0,0 +1,47 @@ +return { + { + Name = "Rhea", + Parent = "SaturnBarycenter", + Renderable = { + Type = "RenderablePlanet", + Frame = "IAU_RHEA", + Body = "RHEA", + Geometry = { + Type = "SimpleSphere", + Radius = { 0.765, 3 }, + Segments = 50 + }, + Textures = { + Color = "textures/rhea.jpg" + } + }, + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "RHEA", + Observer = "SATURN BARYCENTER", + Kernels = "${OPENSPACE_DATA}/spice/sat375.bsp" + }, + Rotation = { + Type = "SpiceRotation", + SourceFrame = "IAU_ENCELADUS", + DestinationFrame = "GALACTIC" + } + } + }, + { + Name = "RheaTrail", + Parent = "SaturnBarycenter", + Renderable = { + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "RHEA", + Observer = "SATURN BARYCENTER", + }, + Color = { 0.5, 0.3, 0.3 }, + Period = 108 / 24, + Resolution = 1000 + } + } +} \ No newline at end of file diff --git a/data/scene/saturn/saturn/sat375.bsp.torrent b/data/scene/saturn/saturn/sat375.bsp.torrent new file mode 100644 index 0000000000..1939e82e2d Binary files /dev/null and b/data/scene/saturn/saturn/sat375.bsp.torrent differ diff --git a/data/scene/saturn/saturn/saturn.data b/data/scene/saturn/saturn/saturn.data new file mode 100644 index 0000000000..cf0748dfc1 --- /dev/null +++ b/data/scene/saturn/saturn/saturn.data @@ -0,0 +1,8 @@ +return { + FileRequest = { + { Identifier = "saturn_textures", Destination = "textures", Version = 2 } + }, + TorrentFiles = { + { File = "sat375.bsp.torrent", Destination = "${SPICE}" }, + } +} \ No newline at end of file diff --git a/data/scene/saturn/saturn.mod b/data/scene/saturn/saturn/saturn.mod similarity index 65% rename from data/scene/saturn/saturn.mod rename to data/scene/saturn/saturn/saturn.mod index 1f7e68170d..aea907718b 100644 --- a/data/scene/saturn/saturn.mod +++ b/data/scene/saturn/saturn/saturn.mod @@ -3,6 +3,14 @@ return { { Name = "SaturnBarycenter", Parent = "SolarSystemBarycenter", + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "SATURN BARYCENTER", + Observer = "SUN", + Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" + } + }, }, -- Saturn module @@ -29,16 +37,10 @@ return { } }, Transform = { - Translation = { - Type = "SpiceEphemeris", - Body = "SATURN BARYCENTER", - Observer = "SUN", - Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" - }, Rotation = { Type = "SpiceRotation", SourceFrame = "IAU_SATURN", - DestinationFrame = "ECLIPJ2000", + DestinationFrame = "GALACTIC", }, Scale = { Type = "StaticScale", @@ -46,24 +48,32 @@ return { }, }, }, + { + Name = "SaturnRings", + Parent = "Saturn", + Renderable = { + Type = "RenderableRings", + Texture = "textures/saturn_rings.png", + Size = 140220000, + Offset = { 74500 / 140445.100671159, 1.0 } -- min / max extend + + }, + + }, -- SaturnTrail module { Name = "SaturnTrail", - Parent = "SaturnBarycenter", + Parent = "SolarSystemBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "SATURN BARYCENTER", - Frame = "GALACTIC", + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "SATURN BARYCENTER", Observer = "SUN", - RGB = {0.85,0.75,0.51 }, - TropicalOrbitPeriod = 10746.94 , - EarthOrbitRatio = 29.424, - DayLength = 10.656, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, + }, + Color = {0.85,0.75,0.51 }, + Period = 10746.94, + Resolution = 1000 }, } } diff --git a/data/scene/saturn/tethys/tethys.data b/data/scene/saturn/tethys/tethys.data new file mode 100644 index 0000000000..fd493213a4 --- /dev/null +++ b/data/scene/saturn/tethys/tethys.data @@ -0,0 +1,5 @@ +return { + FileRequest = { + { Identifier = "tethys_textures", Destination = "textures", Version = 1 } + }, +} \ No newline at end of file diff --git a/data/scene/saturn/tethys/tethys.mod b/data/scene/saturn/tethys/tethys.mod new file mode 100644 index 0000000000..eb2a84b3f9 --- /dev/null +++ b/data/scene/saturn/tethys/tethys.mod @@ -0,0 +1,47 @@ +return { + { + Name = "Tethys", + Parent = "SaturnBarycenter", + Renderable = { + Type = "RenderablePlanet", + Frame = "IAU_TETHYS", + Body = "TETHYS", + Geometry = { + Type = "SimpleSphere", + Radius = { 0.538, 3 }, + Segments = 50 + }, + Textures = { + Color = "textures/tethys.jpg" + } + }, + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "TETHYS", + Observer = "SATURN BARYCENTER", + Kernels = "${OPENSPACE_DATA}/spice/sat375.bsp" + }, + Rotation = { + Type = "SpiceRotation", + SourceFrame = "IAU_ENCELADUS", + DestinationFrame = "GALACTIC" + } + } + }, + { + Name = "TethysTrail", + Parent = "SaturnBarycenter", + Renderable = { + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "TETHYS", + Observer = "SATURN BARYCENTER", + }, + Color = { 0.5, 0.3, 0.3 }, + Period = 45 / 24, + Resolution = 1000 + } + } +} \ No newline at end of file diff --git a/data/scene/saturn/titan/titan.data b/data/scene/saturn/titan/titan.data new file mode 100644 index 0000000000..82c5a342b4 --- /dev/null +++ b/data/scene/saturn/titan/titan.data @@ -0,0 +1,5 @@ +return { + FileRequest = { + { Identifier = "titan_textures", Destination = "textures", Version = 1 } + }, +} \ No newline at end of file diff --git a/data/scene/saturn/titan/titan.mod b/data/scene/saturn/titan/titan.mod new file mode 100644 index 0000000000..83e366c7ba --- /dev/null +++ b/data/scene/saturn/titan/titan.mod @@ -0,0 +1,47 @@ +return { + { + Name = "Titan", + Parent = "SaturnBarycenter", + Renderable = { + Type = "RenderablePlanet", + Frame = "IAU_TITAN", + Body = "TITAN", + Geometry = { + Type = "SimpleSphere", + Radius = { 0.2575, 4 }, + Segments = 50 + }, + Textures = { + Color = "textures/titan.jpg" + } + }, + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "TITAN", + Observer = "SATURN BARYCENTER", + Kernels = "${OPENSPACE_DATA}/spice/sat375.bsp" + }, + Rotation = { + Type = "SpiceRotation", + SourceFrame = "IAU_ENCELADUS", + DestinationFrame = "GALACTIC" + } + } + }, + { + Name = "TitanTrail", + Parent = "SaturnBarycenter", + Renderable = { + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "TITAN", + Observer = "SATURN BARYCENTER", + }, + Color = { 0.5, 0.3, 0.3 }, + Period = 16, + Resolution = 1000 + } + } +} \ No newline at end of file diff --git a/data/scene/stars/stars.mod b/data/scene/stars/stars.mod index 0cb9ed85cc..3e5363aa47 100644 --- a/data/scene/stars/stars.mod +++ b/data/scene/stars/stars.mod @@ -5,9 +5,9 @@ return { Parent = "Root", Renderable = { Type = "RenderableStars", - File = "${OPENSPACE_DATA}/scene/stars/speck/stars.speck", - Texture = "${OPENSPACE_DATA}/scene/stars/textures/halo.png", - ColorMap = "${OPENSPACE_DATA}/scene/stars/colorbv.cmap" + File = "speck/stars.speck", + Texture = "textures/halo.png", + ColorMap = "colorbv.cmap" }, } } diff --git a/data/scene/sun/sun.mod b/data/scene/sun/sun.mod index f377c83011..3bd4e2218e 100644 --- a/data/scene/sun/sun.mod +++ b/data/scene/sun/sun.mod @@ -6,7 +6,7 @@ return { }, -- Sun module - { + { Name = "Sun", Parent = "SolarSystemBarycenter", Renderable = { @@ -24,18 +24,21 @@ return { }, PerformShading = false, }, - Ephemeris = { - Type = "Spice", - Body = "SUN", - Observer = "SSB", - Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" - }, - Rotation = { - Type = "Spice", - Frame = "IAU_SUN", - Reference = "GALACTIC" - }, + Transformation = { + Translation = { + Type = "SpiceTranslation", + Body = "SUN", + Observer = "SSB", + Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" + }, + Rotation = { + Type = "SpiceRotation", + SourceFrame = "IAU_SUN", + DestinationFrame = "GALACTIC" + } + } }, + { Name = "SunGlare", Parent = "SolarSystemBarycenter", @@ -47,13 +50,16 @@ return { Texture = "textures/sun-glare.png", BlendMode = "Additive" }, - Ephemeris = { - Type = "Spice", - Body = "SUN", - Observer = "SSB", - Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" - }, + Transformation = { + Translation = { + Type = "SpiceTranslation", + Body = "SUN", + Observer = "SSB", + Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" + } + } }, + { Name = "SunMarker", Parent = "Sun", @@ -65,9 +71,11 @@ return { Texture = "textures/marker.png", BlendMode = "Additive" }, - Ephemeris = { - Type = "Static", - Position = {0, 0, 0, 5} + Transformation = { + Translation = { + Type = "StaticTranslation", + Position = {0, 0, 0, 5} + } } } } diff --git a/data/scene/uranus/uranus.mod b/data/scene/uranus/uranus.mod index 77bac51663..7d0a559780 100644 --- a/data/scene/uranus/uranus.mod +++ b/data/scene/uranus/uranus.mod @@ -3,6 +3,14 @@ return { { Name = "UranusBarycenter", Parent = "SolarSystemBarycenter", + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "URANUS BARYCENTER", + Observer = "SUN", + Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" + }, + } }, -- Uranus module @@ -29,41 +37,28 @@ return { } }, Transform = { - Translation = { - Type = "SpiceEphemeris", - Body = "URANUS BARYCENTER", - Observer = "SUN", - Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" - }, Rotation = { Type = "SpiceRotation", SourceFrame = "IAU_URANUS", DestinationFrame = "ECLIPJ2000", - }, - Scale = { - Type = "StaticScale", - Scale = 1, - }, + } }, }, + -- UranusTrail module { Name = "UranusTrail", - Parent = "UranusBarycenter", + Parent = "SolarSystemBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "URANUS BARYCENTER", - Frame = "GALACTIC", - Observer = "SUN", - RGB = {0.60,0.95,1.00 }, - TropicalOrbitPeriod = 30588.740 , - EarthOrbitRatio = 83.749, - DayLength = 17.24, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "URANUS BARYCENTER", + Observer = "SUN", + }, + Color = {0.60, 0.95, 1.00 }, + Period = 30588.740, + Resolution = 1000 }, } } diff --git a/data/scene/venus/venus.mod b/data/scene/venus/venus.mod index 6b96b1ca1b..c7943047d3 100644 --- a/data/scene/venus/venus.mod +++ b/data/scene/venus/venus.mod @@ -3,6 +3,14 @@ return { { Name = "VenusBarycenter", Parent = "SolarSystemBarycenter", + Transform = { + Translation = { + Type = "SpiceTranslation", + Body = "VENUS BARYCENTER", + Observer = "SUN", + Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" + }, + } }, -- Venus module @@ -28,36 +36,27 @@ return { MieColor = {1.0, 1.0, 1.0} } }, - Ephemeris = { - Type = "Spice", - Body = "VENUS", - Observer = "SUN", - Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" - }, Rotation = { - Type = "Spice", + Type = "SpiceRotation", Frame = "IAU_VENUS", - Reference = "ECLIPJ2000" + Reference = "GALACTIC" }, }, + -- VenusTrail module - { + { Name = "VenusTrail", - Parent = "VenusBarycenter", + Parent = "SolarSystemBarycenter", Renderable = { - Type = "RenderableTrail", - Body = "VENUS", - Frame = "GALACTIC", - Observer = "SUN", - RGB = {1, 0.5, 0.2}, - TropicalOrbitPeriod = 224.695 , - EarthOrbitRatio = 0.615, - DayLength = 2802.0, - Textures = { - Type = "simple", - Color = "${COMMON_MODULE}/textures/glare_blue.png", - -- need to add different texture - }, - }, + Type = "RenderableTrailOrbit", + Translation = { + Type = "SpiceTranslation", + Body = "VENUS BARYCENTER", + Observer = "SUN", + }, + Color = { 1.0, 0.5, 0.2 }, + Period = 224.695, + Resolution = 1000 + } } } diff --git a/data/web/common/bootstrap.min.css b/data/web/common/bootstrap.min.css new file mode 100644 index 0000000000..ed3905e0e0 --- /dev/null +++ b/data/web/common/bootstrap.min.css @@ -0,0 +1,6 @@ +/*! + * Bootstrap v3.3.7 (http://getbootstrap.com) + * Copyright 2011-2016 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + *//*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,menu,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background-color:transparent}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}h1{margin:.67em 0;font-size:2em}mark{color:#000;background:#ff0}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{height:0;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box}pre{overflow:auto}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}button,input,optgroup,select,textarea{margin:0;font:inherit;color:inherit}button{overflow:visible}button,select{text-transform:none}button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}input{line-height:normal}input[type=checkbox],input[type=radio]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:0}input[type=number]::-webkit-inner-spin-button,input[type=number]::-webkit-outer-spin-button{height:auto}input[type=search]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}fieldset{padding:.35em .625em .75em;margin:0 2px;border:1px solid silver}legend{padding:0;border:0}textarea{overflow:auto}optgroup{font-weight:700}table{border-spacing:0;border-collapse:collapse}td,th{padding:0}/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */@media print{*,:after,:before{color:#000!important;text-shadow:none!important;background:0 0!important;-webkit-box-shadow:none!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}a[href^="javascript:"]:after,a[href^="#"]:after{content:""}blockquote,pre{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}img,tr{page-break-inside:avoid}img{max-width:100%!important}h2,h3,p{orphans:3;widows:3}h2,h3{page-break-after:avoid}.navbar{display:none}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table td,.table th{background-color:#fff!important}.table-bordered td,.table-bordered th{border:1px solid #ddd!important}}@font-face{font-family:'Glyphicons Halflings';src:url(../fonts/glyphicons-halflings-regular.eot);src:url(../fonts/glyphicons-halflings-regular.eot?#iefix) format('embedded-opentype'),url(../fonts/glyphicons-halflings-regular.woff2) format('woff2'),url(../fonts/glyphicons-halflings-regular.woff) format('woff'),url(../fonts/glyphicons-halflings-regular.ttf) format('truetype'),url(../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular) format('svg')}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:400;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.glyphicon-asterisk:before{content:"\002a"}.glyphicon-plus:before{content:"\002b"}.glyphicon-eur:before,.glyphicon-euro:before{content:"\20ac"}.glyphicon-minus:before{content:"\2212"}.glyphicon-cloud:before{content:"\2601"}.glyphicon-envelope:before{content:"\2709"}.glyphicon-pencil:before{content:"\270f"}.glyphicon-glass:before{content:"\e001"}.glyphicon-music:before{content:"\e002"}.glyphicon-search:before{content:"\e003"}.glyphicon-heart:before{content:"\e005"}.glyphicon-star:before{content:"\e006"}.glyphicon-star-empty:before{content:"\e007"}.glyphicon-user:before{content:"\e008"}.glyphicon-film:before{content:"\e009"}.glyphicon-th-large:before{content:"\e010"}.glyphicon-th:before{content:"\e011"}.glyphicon-th-list:before{content:"\e012"}.glyphicon-ok:before{content:"\e013"}.glyphicon-remove:before{content:"\e014"}.glyphicon-zoom-in:before{content:"\e015"}.glyphicon-zoom-out:before{content:"\e016"}.glyphicon-off:before{content:"\e017"}.glyphicon-signal:before{content:"\e018"}.glyphicon-cog:before{content:"\e019"}.glyphicon-trash:before{content:"\e020"}.glyphicon-home:before{content:"\e021"}.glyphicon-file:before{content:"\e022"}.glyphicon-time:before{content:"\e023"}.glyphicon-road:before{content:"\e024"}.glyphicon-download-alt:before{content:"\e025"}.glyphicon-download:before{content:"\e026"}.glyphicon-upload:before{content:"\e027"}.glyphicon-inbox:before{content:"\e028"}.glyphicon-play-circle:before{content:"\e029"}.glyphicon-repeat:before{content:"\e030"}.glyphicon-refresh:before{content:"\e031"}.glyphicon-list-alt:before{content:"\e032"}.glyphicon-lock:before{content:"\e033"}.glyphicon-flag:before{content:"\e034"}.glyphicon-headphones:before{content:"\e035"}.glyphicon-volume-off:before{content:"\e036"}.glyphicon-volume-down:before{content:"\e037"}.glyphicon-volume-up:before{content:"\e038"}.glyphicon-qrcode:before{content:"\e039"}.glyphicon-barcode:before{content:"\e040"}.glyphicon-tag:before{content:"\e041"}.glyphicon-tags:before{content:"\e042"}.glyphicon-book:before{content:"\e043"}.glyphicon-bookmark:before{content:"\e044"}.glyphicon-print:before{content:"\e045"}.glyphicon-camera:before{content:"\e046"}.glyphicon-font:before{content:"\e047"}.glyphicon-bold:before{content:"\e048"}.glyphicon-italic:before{content:"\e049"}.glyphicon-text-height:before{content:"\e050"}.glyphicon-text-width:before{content:"\e051"}.glyphicon-align-left:before{content:"\e052"}.glyphicon-align-center:before{content:"\e053"}.glyphicon-align-right:before{content:"\e054"}.glyphicon-align-justify:before{content:"\e055"}.glyphicon-list:before{content:"\e056"}.glyphicon-indent-left:before{content:"\e057"}.glyphicon-indent-right:before{content:"\e058"}.glyphicon-facetime-video:before{content:"\e059"}.glyphicon-picture:before{content:"\e060"}.glyphicon-map-marker:before{content:"\e062"}.glyphicon-adjust:before{content:"\e063"}.glyphicon-tint:before{content:"\e064"}.glyphicon-edit:before{content:"\e065"}.glyphicon-share:before{content:"\e066"}.glyphicon-check:before{content:"\e067"}.glyphicon-move:before{content:"\e068"}.glyphicon-step-backward:before{content:"\e069"}.glyphicon-fast-backward:before{content:"\e070"}.glyphicon-backward:before{content:"\e071"}.glyphicon-play:before{content:"\e072"}.glyphicon-pause:before{content:"\e073"}.glyphicon-stop:before{content:"\e074"}.glyphicon-forward:before{content:"\e075"}.glyphicon-fast-forward:before{content:"\e076"}.glyphicon-step-forward:before{content:"\e077"}.glyphicon-eject:before{content:"\e078"}.glyphicon-chevron-left:before{content:"\e079"}.glyphicon-chevron-right:before{content:"\e080"}.glyphicon-plus-sign:before{content:"\e081"}.glyphicon-minus-sign:before{content:"\e082"}.glyphicon-remove-sign:before{content:"\e083"}.glyphicon-ok-sign:before{content:"\e084"}.glyphicon-question-sign:before{content:"\e085"}.glyphicon-info-sign:before{content:"\e086"}.glyphicon-screenshot:before{content:"\e087"}.glyphicon-remove-circle:before{content:"\e088"}.glyphicon-ok-circle:before{content:"\e089"}.glyphicon-ban-circle:before{content:"\e090"}.glyphicon-arrow-left:before{content:"\e091"}.glyphicon-arrow-right:before{content:"\e092"}.glyphicon-arrow-up:before{content:"\e093"}.glyphicon-arrow-down:before{content:"\e094"}.glyphicon-share-alt:before{content:"\e095"}.glyphicon-resize-full:before{content:"\e096"}.glyphicon-resize-small:before{content:"\e097"}.glyphicon-exclamation-sign:before{content:"\e101"}.glyphicon-gift:before{content:"\e102"}.glyphicon-leaf:before{content:"\e103"}.glyphicon-fire:before{content:"\e104"}.glyphicon-eye-open:before{content:"\e105"}.glyphicon-eye-close:before{content:"\e106"}.glyphicon-warning-sign:before{content:"\e107"}.glyphicon-plane:before{content:"\e108"}.glyphicon-calendar:before{content:"\e109"}.glyphicon-random:before{content:"\e110"}.glyphicon-comment:before{content:"\e111"}.glyphicon-magnet:before{content:"\e112"}.glyphicon-chevron-up:before{content:"\e113"}.glyphicon-chevron-down:before{content:"\e114"}.glyphicon-retweet:before{content:"\e115"}.glyphicon-shopping-cart:before{content:"\e116"}.glyphicon-folder-close:before{content:"\e117"}.glyphicon-folder-open:before{content:"\e118"}.glyphicon-resize-vertical:before{content:"\e119"}.glyphicon-resize-horizontal:before{content:"\e120"}.glyphicon-hdd:before{content:"\e121"}.glyphicon-bullhorn:before{content:"\e122"}.glyphicon-bell:before{content:"\e123"}.glyphicon-certificate:before{content:"\e124"}.glyphicon-thumbs-up:before{content:"\e125"}.glyphicon-thumbs-down:before{content:"\e126"}.glyphicon-hand-right:before{content:"\e127"}.glyphicon-hand-left:before{content:"\e128"}.glyphicon-hand-up:before{content:"\e129"}.glyphicon-hand-down:before{content:"\e130"}.glyphicon-circle-arrow-right:before{content:"\e131"}.glyphicon-circle-arrow-left:before{content:"\e132"}.glyphicon-circle-arrow-up:before{content:"\e133"}.glyphicon-circle-arrow-down:before{content:"\e134"}.glyphicon-globe:before{content:"\e135"}.glyphicon-wrench:before{content:"\e136"}.glyphicon-tasks:before{content:"\e137"}.glyphicon-filter:before{content:"\e138"}.glyphicon-briefcase:before{content:"\e139"}.glyphicon-fullscreen:before{content:"\e140"}.glyphicon-dashboard:before{content:"\e141"}.glyphicon-paperclip:before{content:"\e142"}.glyphicon-heart-empty:before{content:"\e143"}.glyphicon-link:before{content:"\e144"}.glyphicon-phone:before{content:"\e145"}.glyphicon-pushpin:before{content:"\e146"}.glyphicon-usd:before{content:"\e148"}.glyphicon-gbp:before{content:"\e149"}.glyphicon-sort:before{content:"\e150"}.glyphicon-sort-by-alphabet:before{content:"\e151"}.glyphicon-sort-by-alphabet-alt:before{content:"\e152"}.glyphicon-sort-by-order:before{content:"\e153"}.glyphicon-sort-by-order-alt:before{content:"\e154"}.glyphicon-sort-by-attributes:before{content:"\e155"}.glyphicon-sort-by-attributes-alt:before{content:"\e156"}.glyphicon-unchecked:before{content:"\e157"}.glyphicon-expand:before{content:"\e158"}.glyphicon-collapse-down:before{content:"\e159"}.glyphicon-collapse-up:before{content:"\e160"}.glyphicon-log-in:before{content:"\e161"}.glyphicon-flash:before{content:"\e162"}.glyphicon-log-out:before{content:"\e163"}.glyphicon-new-window:before{content:"\e164"}.glyphicon-record:before{content:"\e165"}.glyphicon-save:before{content:"\e166"}.glyphicon-open:before{content:"\e167"}.glyphicon-saved:before{content:"\e168"}.glyphicon-import:before{content:"\e169"}.glyphicon-export:before{content:"\e170"}.glyphicon-send:before{content:"\e171"}.glyphicon-floppy-disk:before{content:"\e172"}.glyphicon-floppy-saved:before{content:"\e173"}.glyphicon-floppy-remove:before{content:"\e174"}.glyphicon-floppy-save:before{content:"\e175"}.glyphicon-floppy-open:before{content:"\e176"}.glyphicon-credit-card:before{content:"\e177"}.glyphicon-transfer:before{content:"\e178"}.glyphicon-cutlery:before{content:"\e179"}.glyphicon-header:before{content:"\e180"}.glyphicon-compressed:before{content:"\e181"}.glyphicon-earphone:before{content:"\e182"}.glyphicon-phone-alt:before{content:"\e183"}.glyphicon-tower:before{content:"\e184"}.glyphicon-stats:before{content:"\e185"}.glyphicon-sd-video:before{content:"\e186"}.glyphicon-hd-video:before{content:"\e187"}.glyphicon-subtitles:before{content:"\e188"}.glyphicon-sound-stereo:before{content:"\e189"}.glyphicon-sound-dolby:before{content:"\e190"}.glyphicon-sound-5-1:before{content:"\e191"}.glyphicon-sound-6-1:before{content:"\e192"}.glyphicon-sound-7-1:before{content:"\e193"}.glyphicon-copyright-mark:before{content:"\e194"}.glyphicon-registration-mark:before{content:"\e195"}.glyphicon-cloud-download:before{content:"\e197"}.glyphicon-cloud-upload:before{content:"\e198"}.glyphicon-tree-conifer:before{content:"\e199"}.glyphicon-tree-deciduous:before{content:"\e200"}.glyphicon-cd:before{content:"\e201"}.glyphicon-save-file:before{content:"\e202"}.glyphicon-open-file:before{content:"\e203"}.glyphicon-level-up:before{content:"\e204"}.glyphicon-copy:before{content:"\e205"}.glyphicon-paste:before{content:"\e206"}.glyphicon-alert:before{content:"\e209"}.glyphicon-equalizer:before{content:"\e210"}.glyphicon-king:before{content:"\e211"}.glyphicon-queen:before{content:"\e212"}.glyphicon-pawn:before{content:"\e213"}.glyphicon-bishop:before{content:"\e214"}.glyphicon-knight:before{content:"\e215"}.glyphicon-baby-formula:before{content:"\e216"}.glyphicon-tent:before{content:"\26fa"}.glyphicon-blackboard:before{content:"\e218"}.glyphicon-bed:before{content:"\e219"}.glyphicon-apple:before{content:"\f8ff"}.glyphicon-erase:before{content:"\e221"}.glyphicon-hourglass:before{content:"\231b"}.glyphicon-lamp:before{content:"\e223"}.glyphicon-duplicate:before{content:"\e224"}.glyphicon-piggy-bank:before{content:"\e225"}.glyphicon-scissors:before{content:"\e226"}.glyphicon-bitcoin:before{content:"\e227"}.glyphicon-btc:before{content:"\e227"}.glyphicon-xbt:before{content:"\e227"}.glyphicon-yen:before{content:"\00a5"}.glyphicon-jpy:before{content:"\00a5"}.glyphicon-ruble:before{content:"\20bd"}.glyphicon-rub:before{content:"\20bd"}.glyphicon-scale:before{content:"\e230"}.glyphicon-ice-lolly:before{content:"\e231"}.glyphicon-ice-lolly-tasted:before{content:"\e232"}.glyphicon-education:before{content:"\e233"}.glyphicon-option-horizontal:before{content:"\e234"}.glyphicon-option-vertical:before{content:"\e235"}.glyphicon-menu-hamburger:before{content:"\e236"}.glyphicon-modal-window:before{content:"\e237"}.glyphicon-oil:before{content:"\e238"}.glyphicon-grain:before{content:"\e239"}.glyphicon-sunglasses:before{content:"\e240"}.glyphicon-text-size:before{content:"\e241"}.glyphicon-text-color:before{content:"\e242"}.glyphicon-text-background:before{content:"\e243"}.glyphicon-object-align-top:before{content:"\e244"}.glyphicon-object-align-bottom:before{content:"\e245"}.glyphicon-object-align-horizontal:before{content:"\e246"}.glyphicon-object-align-left:before{content:"\e247"}.glyphicon-object-align-vertical:before{content:"\e248"}.glyphicon-object-align-right:before{content:"\e249"}.glyphicon-triangle-right:before{content:"\e250"}.glyphicon-triangle-left:before{content:"\e251"}.glyphicon-triangle-bottom:before{content:"\e252"}.glyphicon-triangle-top:before{content:"\e253"}.glyphicon-console:before{content:"\e254"}.glyphicon-superscript:before{content:"\e255"}.glyphicon-subscript:before{content:"\e256"}.glyphicon-menu-left:before{content:"\e257"}.glyphicon-menu-right:before{content:"\e258"}.glyphicon-menu-down:before{content:"\e259"}.glyphicon-menu-up:before{content:"\e260"}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}:after,:before{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:10px;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857143;color:#333;background-color:#fff}button,input,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}a{color:#337ab7;text-decoration:none}a:focus,a:hover{color:#23527c;text-decoration:underline}a:focus{outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}figure{margin:0}img{vertical-align:middle}.carousel-inner>.item>a>img,.carousel-inner>.item>img,.img-responsive,.thumbnail a>img,.thumbnail>img{display:block;max-width:100%;height:auto}.img-rounded{border-radius:6px}.img-thumbnail{display:inline-block;max-width:100%;height:auto;padding:4px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.img-circle{border-radius:50%}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto}[role=button]{cursor:pointer}.h1,.h2,.h3,.h4,.h5,.h6,h1,h2,h3,h4,h5,h6{font-family:inherit;font-weight:500;line-height:1.1;color:inherit}.h1 .small,.h1 small,.h2 .small,.h2 small,.h3 .small,.h3 small,.h4 .small,.h4 small,.h5 .small,.h5 small,.h6 .small,.h6 small,h1 .small,h1 small,h2 .small,h2 small,h3 .small,h3 small,h4 .small,h4 small,h5 .small,h5 small,h6 .small,h6 small{font-weight:400;line-height:1;color:#777}.h1,.h2,.h3,h1,h2,h3{margin-top:20px;margin-bottom:10px}.h1 .small,.h1 small,.h2 .small,.h2 small,.h3 .small,.h3 small,h1 .small,h1 small,h2 .small,h2 small,h3 .small,h3 small{font-size:65%}.h4,.h5,.h6,h4,h5,h6{margin-top:10px;margin-bottom:10px}.h4 .small,.h4 small,.h5 .small,.h5 small,.h6 .small,.h6 small,h4 .small,h4 small,h5 .small,h5 small,h6 .small,h6 small{font-size:75%}.h1,h1{font-size:36px}.h2,h2{font-size:30px}.h3,h3{font-size:24px}.h4,h4{font-size:18px}.h5,h5{font-size:14px}.h6,h6{font-size:12px}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:16px;font-weight:300;line-height:1.4}@media (min-width:768px){.lead{font-size:21px}}.small,small{font-size:85%}.mark,mark{padding:.2em;background-color:#fcf8e3}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}.text-justify{text-align:justify}.text-nowrap{white-space:nowrap}.text-lowercase{text-transform:lowercase}.text-uppercase{text-transform:uppercase}.text-capitalize{text-transform:capitalize}.text-muted{color:#777}.text-primary{color:#337ab7}a.text-primary:focus,a.text-primary:hover{color:#286090}.text-success{color:#3c763d}a.text-success:focus,a.text-success:hover{color:#2b542c}.text-info{color:#31708f}a.text-info:focus,a.text-info:hover{color:#245269}.text-warning{color:#8a6d3b}a.text-warning:focus,a.text-warning:hover{color:#66512c}.text-danger{color:#a94442}a.text-danger:focus,a.text-danger:hover{color:#843534}.bg-primary{color:#fff;background-color:#337ab7}a.bg-primary:focus,a.bg-primary:hover{background-color:#286090}.bg-success{background-color:#dff0d8}a.bg-success:focus,a.bg-success:hover{background-color:#c1e2b3}.bg-info{background-color:#d9edf7}a.bg-info:focus,a.bg-info:hover{background-color:#afd9ee}.bg-warning{background-color:#fcf8e3}a.bg-warning:focus,a.bg-warning:hover{background-color:#f7ecb5}.bg-danger{background-color:#f2dede}a.bg-danger:focus,a.bg-danger:hover{background-color:#e4b9b9}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ol,ul{margin-top:0;margin-bottom:10px}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;margin-left:-5px;list-style:none}.list-inline>li{display:inline-block;padding-right:5px;padding-left:5px}dl{margin-top:0;margin-bottom:20px}dd,dt{line-height:1.42857143}dt{font-weight:700}dd{margin-left:0}@media (min-width:768px){.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}}abbr[data-original-title],abbr[title]{cursor:help;border-bottom:1px dotted #777}.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;font-size:17.5px;border-left:5px solid #eee}blockquote ol:last-child,blockquote p:last-child,blockquote ul:last-child{margin-bottom:0}blockquote .small,blockquote footer,blockquote small{display:block;font-size:80%;line-height:1.42857143;color:#777}blockquote .small:before,blockquote footer:before,blockquote small:before{content:'\2014 \00A0'}.blockquote-reverse,blockquote.pull-right{padding-right:15px;padding-left:0;text-align:right;border-right:5px solid #eee;border-left:0}.blockquote-reverse .small:before,.blockquote-reverse footer:before,.blockquote-reverse small:before,blockquote.pull-right .small:before,blockquote.pull-right footer:before,blockquote.pull-right small:before{content:''}.blockquote-reverse .small:after,.blockquote-reverse footer:after,.blockquote-reverse small:after,blockquote.pull-right .small:after,blockquote.pull-right footer:after,blockquote.pull-right small:after{content:'\00A0 \2014'}address{margin-bottom:20px;font-style:normal;line-height:1.42857143}code,kbd,pre,samp{font-family:Menlo,Monaco,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;background-color:#f9f2f4;border-radius:4px}kbd{padding:2px 4px;font-size:90%;color:#fff;background-color:#333;border-radius:3px;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.25);box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}kbd kbd{padding:0;font-size:100%;font-weight:700;-webkit-box-shadow:none;box-shadow:none}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.42857143;color:#333;word-break:break-all;word-wrap:break-word;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}@media (min-width:768px){.container{width:750px}}@media (min-width:992px){.container{width:970px}}@media (min-width:1200px){.container{width:1170px}}.container-fluid{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}.row{margin-right:-15px;margin-left:-15px}.col-lg-1,.col-lg-10,.col-lg-11,.col-lg-12,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-md-1,.col-md-10,.col-md-11,.col-md-12,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-sm-1,.col-sm-10,.col-sm-11,.col-sm-12,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-xs-1,.col-xs-10,.col-xs-11,.col-xs-12,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9{position:relative;min-height:1px;padding-right:15px;padding-left:15px}.col-xs-1,.col-xs-10,.col-xs-11,.col-xs-12,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9{float:left}.col-xs-12{width:100%}.col-xs-11{width:91.66666667%}.col-xs-10{width:83.33333333%}.col-xs-9{width:75%}.col-xs-8{width:66.66666667%}.col-xs-7{width:58.33333333%}.col-xs-6{width:50%}.col-xs-5{width:41.66666667%}.col-xs-4{width:33.33333333%}.col-xs-3{width:25%}.col-xs-2{width:16.66666667%}.col-xs-1{width:8.33333333%}.col-xs-pull-12{right:100%}.col-xs-pull-11{right:91.66666667%}.col-xs-pull-10{right:83.33333333%}.col-xs-pull-9{right:75%}.col-xs-pull-8{right:66.66666667%}.col-xs-pull-7{right:58.33333333%}.col-xs-pull-6{right:50%}.col-xs-pull-5{right:41.66666667%}.col-xs-pull-4{right:33.33333333%}.col-xs-pull-3{right:25%}.col-xs-pull-2{right:16.66666667%}.col-xs-pull-1{right:8.33333333%}.col-xs-pull-0{right:auto}.col-xs-push-12{left:100%}.col-xs-push-11{left:91.66666667%}.col-xs-push-10{left:83.33333333%}.col-xs-push-9{left:75%}.col-xs-push-8{left:66.66666667%}.col-xs-push-7{left:58.33333333%}.col-xs-push-6{left:50%}.col-xs-push-5{left:41.66666667%}.col-xs-push-4{left:33.33333333%}.col-xs-push-3{left:25%}.col-xs-push-2{left:16.66666667%}.col-xs-push-1{left:8.33333333%}.col-xs-push-0{left:auto}.col-xs-offset-12{margin-left:100%}.col-xs-offset-11{margin-left:91.66666667%}.col-xs-offset-10{margin-left:83.33333333%}.col-xs-offset-9{margin-left:75%}.col-xs-offset-8{margin-left:66.66666667%}.col-xs-offset-7{margin-left:58.33333333%}.col-xs-offset-6{margin-left:50%}.col-xs-offset-5{margin-left:41.66666667%}.col-xs-offset-4{margin-left:33.33333333%}.col-xs-offset-3{margin-left:25%}.col-xs-offset-2{margin-left:16.66666667%}.col-xs-offset-1{margin-left:8.33333333%}.col-xs-offset-0{margin-left:0}@media (min-width:768px){.col-sm-1,.col-sm-10,.col-sm-11,.col-sm-12,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9{float:left}.col-sm-12{width:100%}.col-sm-11{width:91.66666667%}.col-sm-10{width:83.33333333%}.col-sm-9{width:75%}.col-sm-8{width:66.66666667%}.col-sm-7{width:58.33333333%}.col-sm-6{width:50%}.col-sm-5{width:41.66666667%}.col-sm-4{width:33.33333333%}.col-sm-3{width:25%}.col-sm-2{width:16.66666667%}.col-sm-1{width:8.33333333%}.col-sm-pull-12{right:100%}.col-sm-pull-11{right:91.66666667%}.col-sm-pull-10{right:83.33333333%}.col-sm-pull-9{right:75%}.col-sm-pull-8{right:66.66666667%}.col-sm-pull-7{right:58.33333333%}.col-sm-pull-6{right:50%}.col-sm-pull-5{right:41.66666667%}.col-sm-pull-4{right:33.33333333%}.col-sm-pull-3{right:25%}.col-sm-pull-2{right:16.66666667%}.col-sm-pull-1{right:8.33333333%}.col-sm-pull-0{right:auto}.col-sm-push-12{left:100%}.col-sm-push-11{left:91.66666667%}.col-sm-push-10{left:83.33333333%}.col-sm-push-9{left:75%}.col-sm-push-8{left:66.66666667%}.col-sm-push-7{left:58.33333333%}.col-sm-push-6{left:50%}.col-sm-push-5{left:41.66666667%}.col-sm-push-4{left:33.33333333%}.col-sm-push-3{left:25%}.col-sm-push-2{left:16.66666667%}.col-sm-push-1{left:8.33333333%}.col-sm-push-0{left:auto}.col-sm-offset-12{margin-left:100%}.col-sm-offset-11{margin-left:91.66666667%}.col-sm-offset-10{margin-left:83.33333333%}.col-sm-offset-9{margin-left:75%}.col-sm-offset-8{margin-left:66.66666667%}.col-sm-offset-7{margin-left:58.33333333%}.col-sm-offset-6{margin-left:50%}.col-sm-offset-5{margin-left:41.66666667%}.col-sm-offset-4{margin-left:33.33333333%}.col-sm-offset-3{margin-left:25%}.col-sm-offset-2{margin-left:16.66666667%}.col-sm-offset-1{margin-left:8.33333333%}.col-sm-offset-0{margin-left:0}}@media (min-width:992px){.col-md-1,.col-md-10,.col-md-11,.col-md-12,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9{float:left}.col-md-12{width:100%}.col-md-11{width:91.66666667%}.col-md-10{width:83.33333333%}.col-md-9{width:75%}.col-md-8{width:66.66666667%}.col-md-7{width:58.33333333%}.col-md-6{width:50%}.col-md-5{width:41.66666667%}.col-md-4{width:33.33333333%}.col-md-3{width:25%}.col-md-2{width:16.66666667%}.col-md-1{width:8.33333333%}.col-md-pull-12{right:100%}.col-md-pull-11{right:91.66666667%}.col-md-pull-10{right:83.33333333%}.col-md-pull-9{right:75%}.col-md-pull-8{right:66.66666667%}.col-md-pull-7{right:58.33333333%}.col-md-pull-6{right:50%}.col-md-pull-5{right:41.66666667%}.col-md-pull-4{right:33.33333333%}.col-md-pull-3{right:25%}.col-md-pull-2{right:16.66666667%}.col-md-pull-1{right:8.33333333%}.col-md-pull-0{right:auto}.col-md-push-12{left:100%}.col-md-push-11{left:91.66666667%}.col-md-push-10{left:83.33333333%}.col-md-push-9{left:75%}.col-md-push-8{left:66.66666667%}.col-md-push-7{left:58.33333333%}.col-md-push-6{left:50%}.col-md-push-5{left:41.66666667%}.col-md-push-4{left:33.33333333%}.col-md-push-3{left:25%}.col-md-push-2{left:16.66666667%}.col-md-push-1{left:8.33333333%}.col-md-push-0{left:auto}.col-md-offset-12{margin-left:100%}.col-md-offset-11{margin-left:91.66666667%}.col-md-offset-10{margin-left:83.33333333%}.col-md-offset-9{margin-left:75%}.col-md-offset-8{margin-left:66.66666667%}.col-md-offset-7{margin-left:58.33333333%}.col-md-offset-6{margin-left:50%}.col-md-offset-5{margin-left:41.66666667%}.col-md-offset-4{margin-left:33.33333333%}.col-md-offset-3{margin-left:25%}.col-md-offset-2{margin-left:16.66666667%}.col-md-offset-1{margin-left:8.33333333%}.col-md-offset-0{margin-left:0}}@media (min-width:1200px){.col-lg-1,.col-lg-10,.col-lg-11,.col-lg-12,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9{float:left}.col-lg-12{width:100%}.col-lg-11{width:91.66666667%}.col-lg-10{width:83.33333333%}.col-lg-9{width:75%}.col-lg-8{width:66.66666667%}.col-lg-7{width:58.33333333%}.col-lg-6{width:50%}.col-lg-5{width:41.66666667%}.col-lg-4{width:33.33333333%}.col-lg-3{width:25%}.col-lg-2{width:16.66666667%}.col-lg-1{width:8.33333333%}.col-lg-pull-12{right:100%}.col-lg-pull-11{right:91.66666667%}.col-lg-pull-10{right:83.33333333%}.col-lg-pull-9{right:75%}.col-lg-pull-8{right:66.66666667%}.col-lg-pull-7{right:58.33333333%}.col-lg-pull-6{right:50%}.col-lg-pull-5{right:41.66666667%}.col-lg-pull-4{right:33.33333333%}.col-lg-pull-3{right:25%}.col-lg-pull-2{right:16.66666667%}.col-lg-pull-1{right:8.33333333%}.col-lg-pull-0{right:auto}.col-lg-push-12{left:100%}.col-lg-push-11{left:91.66666667%}.col-lg-push-10{left:83.33333333%}.col-lg-push-9{left:75%}.col-lg-push-8{left:66.66666667%}.col-lg-push-7{left:58.33333333%}.col-lg-push-6{left:50%}.col-lg-push-5{left:41.66666667%}.col-lg-push-4{left:33.33333333%}.col-lg-push-3{left:25%}.col-lg-push-2{left:16.66666667%}.col-lg-push-1{left:8.33333333%}.col-lg-push-0{left:auto}.col-lg-offset-12{margin-left:100%}.col-lg-offset-11{margin-left:91.66666667%}.col-lg-offset-10{margin-left:83.33333333%}.col-lg-offset-9{margin-left:75%}.col-lg-offset-8{margin-left:66.66666667%}.col-lg-offset-7{margin-left:58.33333333%}.col-lg-offset-6{margin-left:50%}.col-lg-offset-5{margin-left:41.66666667%}.col-lg-offset-4{margin-left:33.33333333%}.col-lg-offset-3{margin-left:25%}.col-lg-offset-2{margin-left:16.66666667%}.col-lg-offset-1{margin-left:8.33333333%}.col-lg-offset-0{margin-left:0}}table{background-color:transparent}caption{padding-top:8px;padding-bottom:8px;color:#777;text-align:left}th{text-align:left}.table{width:100%;max-width:100%;margin-bottom:20px}.table>tbody>tr>td,.table>tbody>tr>th,.table>tfoot>tr>td,.table>tfoot>tr>th,.table>thead>tr>td,.table>thead>tr>th{padding:8px;line-height:1.42857143;vertical-align:top;border-top:1px solid #ddd}.table>thead>tr>th{vertical-align:bottom;border-bottom:2px solid #ddd}.table>caption+thead>tr:first-child>td,.table>caption+thead>tr:first-child>th,.table>colgroup+thead>tr:first-child>td,.table>colgroup+thead>tr:first-child>th,.table>thead:first-child>tr:first-child>td,.table>thead:first-child>tr:first-child>th{border-top:0}.table>tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed>tbody>tr>td,.table-condensed>tbody>tr>th,.table-condensed>tfoot>tr>td,.table-condensed>tfoot>tr>th,.table-condensed>thead>tr>td,.table-condensed>thead>tr>th{padding:5px}.table-bordered{border:1px solid #ddd}.table-bordered>tbody>tr>td,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>td,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>thead>tr>th{border:1px solid #ddd}.table-bordered>thead>tr>td,.table-bordered>thead>tr>th{border-bottom-width:2px}.table-striped>tbody>tr:nth-of-type(odd){background-color:#f9f9f9}.table-hover>tbody>tr:hover{background-color:#f5f5f5}table col[class*=col-]{position:static;display:table-column;float:none}table td[class*=col-],table th[class*=col-]{position:static;display:table-cell;float:none}.table>tbody>tr.active>td,.table>tbody>tr.active>th,.table>tbody>tr>td.active,.table>tbody>tr>th.active,.table>tfoot>tr.active>td,.table>tfoot>tr.active>th,.table>tfoot>tr>td.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>thead>tr.active>th,.table>thead>tr>td.active,.table>thead>tr>th.active{background-color:#f5f5f5}.table-hover>tbody>tr.active:hover>td,.table-hover>tbody>tr.active:hover>th,.table-hover>tbody>tr:hover>.active,.table-hover>tbody>tr>td.active:hover,.table-hover>tbody>tr>th.active:hover{background-color:#e8e8e8}.table>tbody>tr.success>td,.table>tbody>tr.success>th,.table>tbody>tr>td.success,.table>tbody>tr>th.success,.table>tfoot>tr.success>td,.table>tfoot>tr.success>th,.table>tfoot>tr>td.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>thead>tr.success>th,.table>thead>tr>td.success,.table>thead>tr>th.success{background-color:#dff0d8}.table-hover>tbody>tr.success:hover>td,.table-hover>tbody>tr.success:hover>th,.table-hover>tbody>tr:hover>.success,.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover{background-color:#d0e9c6}.table>tbody>tr.info>td,.table>tbody>tr.info>th,.table>tbody>tr>td.info,.table>tbody>tr>th.info,.table>tfoot>tr.info>td,.table>tfoot>tr.info>th,.table>tfoot>tr>td.info,.table>tfoot>tr>th.info,.table>thead>tr.info>td,.table>thead>tr.info>th,.table>thead>tr>td.info,.table>thead>tr>th.info{background-color:#d9edf7}.table-hover>tbody>tr.info:hover>td,.table-hover>tbody>tr.info:hover>th,.table-hover>tbody>tr:hover>.info,.table-hover>tbody>tr>td.info:hover,.table-hover>tbody>tr>th.info:hover{background-color:#c4e3f3}.table>tbody>tr.warning>td,.table>tbody>tr.warning>th,.table>tbody>tr>td.warning,.table>tbody>tr>th.warning,.table>tfoot>tr.warning>td,.table>tfoot>tr.warning>th,.table>tfoot>tr>td.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>thead>tr.warning>th,.table>thead>tr>td.warning,.table>thead>tr>th.warning{background-color:#fcf8e3}.table-hover>tbody>tr.warning:hover>td,.table-hover>tbody>tr.warning:hover>th,.table-hover>tbody>tr:hover>.warning,.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover{background-color:#faf2cc}.table>tbody>tr.danger>td,.table>tbody>tr.danger>th,.table>tbody>tr>td.danger,.table>tbody>tr>th.danger,.table>tfoot>tr.danger>td,.table>tfoot>tr.danger>th,.table>tfoot>tr>td.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>thead>tr.danger>th,.table>thead>tr>td.danger,.table>thead>tr>th.danger{background-color:#f2dede}.table-hover>tbody>tr.danger:hover>td,.table-hover>tbody>tr.danger:hover>th,.table-hover>tbody>tr:hover>.danger,.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover{background-color:#ebcccc}.table-responsive{min-height:.01%;overflow-x:auto}@media screen and (max-width:767px){.table-responsive{width:100%;margin-bottom:15px;overflow-y:hidden;-ms-overflow-style:-ms-autohiding-scrollbar;border:1px solid #ddd}.table-responsive>.table{margin-bottom:0}.table-responsive>.table>tbody>tr>td,.table-responsive>.table>tbody>tr>th,.table-responsive>.table>tfoot>tr>td,.table-responsive>.table>tfoot>tr>th,.table-responsive>.table>thead>tr>td,.table-responsive>.table>thead>tr>th{white-space:nowrap}.table-responsive>.table-bordered{border:0}.table-responsive>.table-bordered>tbody>tr>td:first-child,.table-responsive>.table-bordered>tbody>tr>th:first-child,.table-responsive>.table-bordered>tfoot>tr>td:first-child,.table-responsive>.table-bordered>tfoot>tr>th:first-child,.table-responsive>.table-bordered>thead>tr>td:first-child,.table-responsive>.table-bordered>thead>tr>th:first-child{border-left:0}.table-responsive>.table-bordered>tbody>tr>td:last-child,.table-responsive>.table-bordered>tbody>tr>th:last-child,.table-responsive>.table-bordered>tfoot>tr>td:last-child,.table-responsive>.table-bordered>tfoot>tr>th:last-child,.table-responsive>.table-bordered>thead>tr>td:last-child,.table-responsive>.table-bordered>thead>tr>th:last-child{border-right:0}.table-responsive>.table-bordered>tbody>tr:last-child>td,.table-responsive>.table-bordered>tbody>tr:last-child>th,.table-responsive>.table-bordered>tfoot>tr:last-child>td,.table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;max-width:100%;margin-bottom:5px;font-weight:700}input[type=search]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type=checkbox],input[type=radio]{margin:4px 0 0;margin-top:1px\9;line-height:normal}input[type=file]{display:block}input[type=range]{display:block;width:100%}select[multiple],select[size]{height:auto}input[type=file]:focus,input[type=checkbox]:focus,input[type=radio]:focus{outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}output{display:block;padding-top:7px;font-size:14px;line-height:1.42857143;color:#555}.form-control{display:block;width:100%;height:34px;padding:6px 12px;font-size:14px;line-height:1.42857143;color:#555;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.form-control::-moz-placeholder{color:#999;opacity:1}.form-control:-ms-input-placeholder{color:#999}.form-control::-webkit-input-placeholder{color:#999}.form-control::-ms-expand{background-color:transparent;border:0}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{background-color:#eee;opacity:1}.form-control[disabled],fieldset[disabled] .form-control{cursor:not-allowed}textarea.form-control{height:auto}input[type=search]{-webkit-appearance:none}@media screen and (-webkit-min-device-pixel-ratio:0){input[type=date].form-control,input[type=time].form-control,input[type=datetime-local].form-control,input[type=month].form-control{line-height:34px}.input-group-sm input[type=date],.input-group-sm input[type=time],.input-group-sm input[type=datetime-local],.input-group-sm input[type=month],input[type=date].input-sm,input[type=time].input-sm,input[type=datetime-local].input-sm,input[type=month].input-sm{line-height:30px}.input-group-lg input[type=date],.input-group-lg input[type=time],.input-group-lg input[type=datetime-local],.input-group-lg input[type=month],input[type=date].input-lg,input[type=time].input-lg,input[type=datetime-local].input-lg,input[type=month].input-lg{line-height:46px}}.form-group{margin-bottom:15px}.checkbox,.radio{position:relative;display:block;margin-top:10px;margin-bottom:10px}.checkbox label,.radio label{min-height:20px;padding-left:20px;margin-bottom:0;font-weight:400;cursor:pointer}.checkbox input[type=checkbox],.checkbox-inline input[type=checkbox],.radio input[type=radio],.radio-inline input[type=radio]{position:absolute;margin-top:4px\9;margin-left:-20px}.checkbox+.checkbox,.radio+.radio{margin-top:-5px}.checkbox-inline,.radio-inline{position:relative;display:inline-block;padding-left:20px;margin-bottom:0;font-weight:400;vertical-align:middle;cursor:pointer}.checkbox-inline+.checkbox-inline,.radio-inline+.radio-inline{margin-top:0;margin-left:10px}fieldset[disabled] input[type=checkbox],fieldset[disabled] input[type=radio],input[type=checkbox].disabled,input[type=checkbox][disabled],input[type=radio].disabled,input[type=radio][disabled]{cursor:not-allowed}.checkbox-inline.disabled,.radio-inline.disabled,fieldset[disabled] .checkbox-inline,fieldset[disabled] .radio-inline{cursor:not-allowed}.checkbox.disabled label,.radio.disabled label,fieldset[disabled] .checkbox label,fieldset[disabled] .radio label{cursor:not-allowed}.form-control-static{min-height:34px;padding-top:7px;padding-bottom:7px;margin-bottom:0}.form-control-static.input-lg,.form-control-static.input-sm{padding-right:0;padding-left:0}.input-sm{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-sm{height:30px;line-height:30px}select[multiple].input-sm,textarea.input-sm{height:auto}.form-group-sm .form-control{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.form-group-sm select.form-control{height:30px;line-height:30px}.form-group-sm select[multiple].form-control,.form-group-sm textarea.form-control{height:auto}.form-group-sm .form-control-static{height:30px;min-height:32px;padding:6px 10px;font-size:12px;line-height:1.5}.input-lg{height:46px;padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}select.input-lg{height:46px;line-height:46px}select[multiple].input-lg,textarea.input-lg{height:auto}.form-group-lg .form-control{height:46px;padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}.form-group-lg select.form-control{height:46px;line-height:46px}.form-group-lg select[multiple].form-control,.form-group-lg textarea.form-control{height:auto}.form-group-lg .form-control-static{height:46px;min-height:38px;padding:11px 16px;font-size:18px;line-height:1.3333333}.has-feedback{position:relative}.has-feedback .form-control{padding-right:42.5px}.form-control-feedback{position:absolute;top:0;right:0;z-index:2;display:block;width:34px;height:34px;line-height:34px;text-align:center;pointer-events:none}.form-group-lg .form-control+.form-control-feedback,.input-group-lg+.form-control-feedback,.input-lg+.form-control-feedback{width:46px;height:46px;line-height:46px}.form-group-sm .form-control+.form-control-feedback,.input-group-sm+.form-control-feedback,.input-sm+.form-control-feedback{width:30px;height:30px;line-height:30px}.has-success .checkbox,.has-success .checkbox-inline,.has-success .control-label,.has-success .help-block,.has-success .radio,.has-success .radio-inline,.has-success.checkbox label,.has-success.checkbox-inline label,.has-success.radio label,.has-success.radio-inline label{color:#3c763d}.has-success .form-control{border-color:#3c763d;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-success .form-control:focus{border-color:#2b542c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168}.has-success .input-group-addon{color:#3c763d;background-color:#dff0d8;border-color:#3c763d}.has-success .form-control-feedback{color:#3c763d}.has-warning .checkbox,.has-warning .checkbox-inline,.has-warning .control-label,.has-warning .help-block,.has-warning .radio,.has-warning .radio-inline,.has-warning.checkbox label,.has-warning.checkbox-inline label,.has-warning.radio label,.has-warning.radio-inline label{color:#8a6d3b}.has-warning .form-control{border-color:#8a6d3b;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-warning .form-control:focus{border-color:#66512c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b}.has-warning .input-group-addon{color:#8a6d3b;background-color:#fcf8e3;border-color:#8a6d3b}.has-warning .form-control-feedback{color:#8a6d3b}.has-error .checkbox,.has-error .checkbox-inline,.has-error .control-label,.has-error .help-block,.has-error .radio,.has-error .radio-inline,.has-error.checkbox label,.has-error.checkbox-inline label,.has-error.radio label,.has-error.radio-inline label{color:#a94442}.has-error .form-control{border-color:#a94442;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-error .form-control:focus{border-color:#843534;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.has-error .input-group-addon{color:#a94442;background-color:#f2dede;border-color:#a94442}.has-error .form-control-feedback{color:#a94442}.has-feedback label~.form-control-feedback{top:25px}.has-feedback label.sr-only~.form-control-feedback{top:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}@media (min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .form-control-static{display:inline-block}.form-inline .input-group{display:inline-table;vertical-align:middle}.form-inline .input-group .form-control,.form-inline .input-group .input-group-addon,.form-inline .input-group .input-group-btn{width:auto}.form-inline .input-group>.form-control{width:100%}.form-inline .control-label{margin-bottom:0;vertical-align:middle}.form-inline .checkbox,.form-inline .radio{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.form-inline .checkbox label,.form-inline .radio label{padding-left:0}.form-inline .checkbox input[type=checkbox],.form-inline .radio input[type=radio]{position:relative;margin-left:0}.form-inline .has-feedback .form-control-feedback{top:0}}.form-horizontal .checkbox,.form-horizontal .checkbox-inline,.form-horizontal .radio,.form-horizontal .radio-inline{padding-top:7px;margin-top:0;margin-bottom:0}.form-horizontal .checkbox,.form-horizontal .radio{min-height:27px}.form-horizontal .form-group{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.form-horizontal .control-label{padding-top:7px;margin-bottom:0;text-align:right}}.form-horizontal .has-feedback .form-control-feedback{right:15px}@media (min-width:768px){.form-horizontal .form-group-lg .control-label{padding-top:11px;font-size:18px}}@media (min-width:768px){.form-horizontal .form-group-sm .control-label{padding-top:6px;font-size:12px}}.btn{display:inline-block;padding:6px 12px;margin-bottom:0;font-size:14px;font-weight:400;line-height:1.42857143;text-align:center;white-space:nowrap;vertical-align:middle;-ms-touch-action:manipulation;touch-action:manipulation;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-image:none;border:1px solid transparent;border-radius:4px}.btn.active.focus,.btn.active:focus,.btn.focus,.btn:active.focus,.btn:active:focus,.btn:focus{outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.focus,.btn:focus,.btn:hover{color:#333;text-decoration:none}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{cursor:not-allowed;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none;opacity:.65}a.btn.disabled,fieldset[disabled] a.btn{pointer-events:none}.btn-default{color:#333;background-color:#fff;border-color:#ccc}.btn-default.focus,.btn-default:focus{color:#333;background-color:#e6e6e6;border-color:#8c8c8c}.btn-default:hover{color:#333;background-color:#e6e6e6;border-color:#adadad}.btn-default.active,.btn-default:active,.open>.dropdown-toggle.btn-default{color:#333;background-color:#e6e6e6;border-color:#adadad}.btn-default.active.focus,.btn-default.active:focus,.btn-default.active:hover,.btn-default:active.focus,.btn-default:active:focus,.btn-default:active:hover,.open>.dropdown-toggle.btn-default.focus,.open>.dropdown-toggle.btn-default:focus,.open>.dropdown-toggle.btn-default:hover{color:#333;background-color:#d4d4d4;border-color:#8c8c8c}.btn-default.active,.btn-default:active,.open>.dropdown-toggle.btn-default{background-image:none}.btn-default.disabled.focus,.btn-default.disabled:focus,.btn-default.disabled:hover,.btn-default[disabled].focus,.btn-default[disabled]:focus,.btn-default[disabled]:hover,fieldset[disabled] .btn-default.focus,fieldset[disabled] .btn-default:focus,fieldset[disabled] .btn-default:hover{background-color:#fff;border-color:#ccc}.btn-default .badge{color:#fff;background-color:#333}.btn-primary{color:#fff;background-color:#337ab7;border-color:#2e6da4}.btn-primary.focus,.btn-primary:focus{color:#fff;background-color:#286090;border-color:#122b40}.btn-primary:hover{color:#fff;background-color:#286090;border-color:#204d74}.btn-primary.active,.btn-primary:active,.open>.dropdown-toggle.btn-primary{color:#fff;background-color:#286090;border-color:#204d74}.btn-primary.active.focus,.btn-primary.active:focus,.btn-primary.active:hover,.btn-primary:active.focus,.btn-primary:active:focus,.btn-primary:active:hover,.open>.dropdown-toggle.btn-primary.focus,.open>.dropdown-toggle.btn-primary:focus,.open>.dropdown-toggle.btn-primary:hover{color:#fff;background-color:#204d74;border-color:#122b40}.btn-primary.active,.btn-primary:active,.open>.dropdown-toggle.btn-primary{background-image:none}.btn-primary.disabled.focus,.btn-primary.disabled:focus,.btn-primary.disabled:hover,.btn-primary[disabled].focus,.btn-primary[disabled]:focus,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary.focus,fieldset[disabled] .btn-primary:focus,fieldset[disabled] .btn-primary:hover{background-color:#337ab7;border-color:#2e6da4}.btn-primary .badge{color:#337ab7;background-color:#fff}.btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.btn-success.focus,.btn-success:focus{color:#fff;background-color:#449d44;border-color:#255625}.btn-success:hover{color:#fff;background-color:#449d44;border-color:#398439}.btn-success.active,.btn-success:active,.open>.dropdown-toggle.btn-success{color:#fff;background-color:#449d44;border-color:#398439}.btn-success.active.focus,.btn-success.active:focus,.btn-success.active:hover,.btn-success:active.focus,.btn-success:active:focus,.btn-success:active:hover,.open>.dropdown-toggle.btn-success.focus,.open>.dropdown-toggle.btn-success:focus,.open>.dropdown-toggle.btn-success:hover{color:#fff;background-color:#398439;border-color:#255625}.btn-success.active,.btn-success:active,.open>.dropdown-toggle.btn-success{background-image:none}.btn-success.disabled.focus,.btn-success.disabled:focus,.btn-success.disabled:hover,.btn-success[disabled].focus,.btn-success[disabled]:focus,.btn-success[disabled]:hover,fieldset[disabled] .btn-success.focus,fieldset[disabled] .btn-success:focus,fieldset[disabled] .btn-success:hover{background-color:#5cb85c;border-color:#4cae4c}.btn-success .badge{color:#5cb85c;background-color:#fff}.btn-info{color:#fff;background-color:#5bc0de;border-color:#46b8da}.btn-info.focus,.btn-info:focus{color:#fff;background-color:#31b0d5;border-color:#1b6d85}.btn-info:hover{color:#fff;background-color:#31b0d5;border-color:#269abc}.btn-info.active,.btn-info:active,.open>.dropdown-toggle.btn-info{color:#fff;background-color:#31b0d5;border-color:#269abc}.btn-info.active.focus,.btn-info.active:focus,.btn-info.active:hover,.btn-info:active.focus,.btn-info:active:focus,.btn-info:active:hover,.open>.dropdown-toggle.btn-info.focus,.open>.dropdown-toggle.btn-info:focus,.open>.dropdown-toggle.btn-info:hover{color:#fff;background-color:#269abc;border-color:#1b6d85}.btn-info.active,.btn-info:active,.open>.dropdown-toggle.btn-info{background-image:none}.btn-info.disabled.focus,.btn-info.disabled:focus,.btn-info.disabled:hover,.btn-info[disabled].focus,.btn-info[disabled]:focus,.btn-info[disabled]:hover,fieldset[disabled] .btn-info.focus,fieldset[disabled] .btn-info:focus,fieldset[disabled] .btn-info:hover{background-color:#5bc0de;border-color:#46b8da}.btn-info .badge{color:#5bc0de;background-color:#fff}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236}.btn-warning.focus,.btn-warning:focus{color:#fff;background-color:#ec971f;border-color:#985f0d}.btn-warning:hover{color:#fff;background-color:#ec971f;border-color:#d58512}.btn-warning.active,.btn-warning:active,.open>.dropdown-toggle.btn-warning{color:#fff;background-color:#ec971f;border-color:#d58512}.btn-warning.active.focus,.btn-warning.active:focus,.btn-warning.active:hover,.btn-warning:active.focus,.btn-warning:active:focus,.btn-warning:active:hover,.open>.dropdown-toggle.btn-warning.focus,.open>.dropdown-toggle.btn-warning:focus,.open>.dropdown-toggle.btn-warning:hover{color:#fff;background-color:#d58512;border-color:#985f0d}.btn-warning.active,.btn-warning:active,.open>.dropdown-toggle.btn-warning{background-image:none}.btn-warning.disabled.focus,.btn-warning.disabled:focus,.btn-warning.disabled:hover,.btn-warning[disabled].focus,.btn-warning[disabled]:focus,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning.focus,fieldset[disabled] .btn-warning:focus,fieldset[disabled] .btn-warning:hover{background-color:#f0ad4e;border-color:#eea236}.btn-warning .badge{color:#f0ad4e;background-color:#fff}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a}.btn-danger.focus,.btn-danger:focus{color:#fff;background-color:#c9302c;border-color:#761c19}.btn-danger:hover{color:#fff;background-color:#c9302c;border-color:#ac2925}.btn-danger.active,.btn-danger:active,.open>.dropdown-toggle.btn-danger{color:#fff;background-color:#c9302c;border-color:#ac2925}.btn-danger.active.focus,.btn-danger.active:focus,.btn-danger.active:hover,.btn-danger:active.focus,.btn-danger:active:focus,.btn-danger:active:hover,.open>.dropdown-toggle.btn-danger.focus,.open>.dropdown-toggle.btn-danger:focus,.open>.dropdown-toggle.btn-danger:hover{color:#fff;background-color:#ac2925;border-color:#761c19}.btn-danger.active,.btn-danger:active,.open>.dropdown-toggle.btn-danger{background-image:none}.btn-danger.disabled.focus,.btn-danger.disabled:focus,.btn-danger.disabled:hover,.btn-danger[disabled].focus,.btn-danger[disabled]:focus,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger.focus,fieldset[disabled] .btn-danger:focus,fieldset[disabled] .btn-danger:hover{background-color:#d9534f;border-color:#d43f3a}.btn-danger .badge{color:#d9534f;background-color:#fff}.btn-link{font-weight:400;color:#337ab7;border-radius:0}.btn-link,.btn-link.active,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:active,.btn-link:focus,.btn-link:hover{border-color:transparent}.btn-link:focus,.btn-link:hover{color:#23527c;text-decoration:underline;background-color:transparent}.btn-link[disabled]:focus,.btn-link[disabled]:hover,fieldset[disabled] .btn-link:focus,fieldset[disabled] .btn-link:hover{color:#777;text-decoration:none}.btn-group-lg>.btn,.btn-lg{padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}.btn-group-sm>.btn,.btn-sm{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-group-xs>.btn,.btn-xs{padding:1px 5px;font-size:12px;line-height:1.5;border-radius:3px}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:5px}input[type=button].btn-block,input[type=reset].btn-block,input[type=submit].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;-o-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}tr.collapse.in{display:table-row}tbody.collapse.in{display:table-row-group}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition-timing-function:ease;-o-transition-timing-function:ease;transition-timing-function:ease;-webkit-transition-duration:.35s;-o-transition-duration:.35s;transition-duration:.35s;-webkit-transition-property:height,visibility;-o-transition-property:height,visibility;transition-property:height,visibility}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px dashed;border-top:4px solid\9;border-right:4px solid transparent;border-left:4px solid transparent}.dropdown,.dropup{position:relative}.dropdown-toggle:focus{outline:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;font-size:14px;text-align:left;list-style:none;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,.175);box-shadow:0 6px 12px rgba(0,0,0,.175)}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:400;line-height:1.42857143;color:#333;white-space:nowrap}.dropdown-menu>li>a:focus,.dropdown-menu>li>a:hover{color:#262626;text-decoration:none;background-color:#f5f5f5}.dropdown-menu>.active>a,.dropdown-menu>.active>a:focus,.dropdown-menu>.active>a:hover{color:#fff;text-decoration:none;background-color:#337ab7;outline:0}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:focus,.dropdown-menu>.disabled>a:hover{color:#777}.dropdown-menu>.disabled>a:focus,.dropdown-menu>.disabled>a:hover{text-decoration:none;cursor:not-allowed;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-menu-right{right:0;left:auto}.dropdown-menu-left{right:auto;left:0}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.42857143;color:#777;white-space:nowrap}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{content:"";border-top:0;border-bottom:4px dashed;border-bottom:4px solid\9}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:2px}@media (min-width:768px){.navbar-right .dropdown-menu{right:0;left:auto}.navbar-right .dropdown-menu-left{right:auto;left:0}}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group-vertical>.btn,.btn-group>.btn{position:relative;float:left}.btn-group-vertical>.btn.active,.btn-group-vertical>.btn:active,.btn-group-vertical>.btn:focus,.btn-group-vertical>.btn:hover,.btn-group>.btn.active,.btn-group>.btn:active,.btn-group>.btn:focus,.btn-group>.btn:hover{z-index:2}.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group{margin-left:-1px}.btn-toolbar{margin-left:-5px}.btn-toolbar .btn,.btn-toolbar .btn-group,.btn-toolbar .input-group{float:left}.btn-toolbar>.btn,.btn-toolbar>.btn-group,.btn-toolbar>.input-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-left-radius:0;border-bottom-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{padding-right:8px;padding-left:8px}.btn-group>.btn-lg+.dropdown-toggle{padding-right:12px;padding-left:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn-group.open .dropdown-toggle.btn-link{-webkit-box-shadow:none;box-shadow:none}.btn .caret{margin-left:0}.btn-lg .caret{border-width:5px 5px 0;border-bottom-width:0}.dropup .btn-lg .caret{border-width:0 5px 5px}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group,.btn-group-vertical>.btn-group>.btn{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn-group>.btn{float:none}.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical>.btn:first-child:not(:last-child){border-top-left-radius:4px;border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn:last-child:not(:first-child){border-top-left-radius:0;border-top-right-radius:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group-vertical>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group-vertical>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-left-radius:0;border-top-right-radius:0}.btn-group-justified{display:table;width:100%;table-layout:fixed;border-collapse:separate}.btn-group-justified>.btn,.btn-group-justified>.btn-group{display:table-cell;float:none;width:1%}.btn-group-justified>.btn-group .btn{width:100%}.btn-group-justified>.btn-group .dropdown-menu{left:auto}[data-toggle=buttons]>.btn input[type=checkbox],[data-toggle=buttons]>.btn input[type=radio],[data-toggle=buttons]>.btn-group>.btn input[type=checkbox],[data-toggle=buttons]>.btn-group>.btn input[type=radio]{position:absolute;clip:rect(0,0,0,0);pointer-events:none}.input-group{position:relative;display:table;border-collapse:separate}.input-group[class*=col-]{float:none;padding-right:0;padding-left:0}.input-group .form-control{position:relative;z-index:2;float:left;width:100%;margin-bottom:0}.input-group .form-control:focus{z-index:3}.input-group-lg>.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.btn{height:46px;padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}select.input-group-lg>.form-control,select.input-group-lg>.input-group-addon,select.input-group-lg>.input-group-btn>.btn{height:46px;line-height:46px}select[multiple].input-group-lg>.form-control,select[multiple].input-group-lg>.input-group-addon,select[multiple].input-group-lg>.input-group-btn>.btn,textarea.input-group-lg>.form-control,textarea.input-group-lg>.input-group-addon,textarea.input-group-lg>.input-group-btn>.btn{height:auto}.input-group-sm>.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.btn{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-group-sm>.form-control,select.input-group-sm>.input-group-addon,select.input-group-sm>.input-group-btn>.btn{height:30px;line-height:30px}select[multiple].input-group-sm>.form-control,select[multiple].input-group-sm>.input-group-addon,select[multiple].input-group-sm>.input-group-btn>.btn,textarea.input-group-sm>.form-control,textarea.input-group-sm>.input-group-addon,textarea.input-group-sm>.input-group-btn>.btn{height:auto}.input-group .form-control,.input-group-addon,.input-group-btn{display:table-cell}.input-group .form-control:not(:first-child):not(:last-child),.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:6px 12px;font-size:14px;font-weight:400;line-height:1;color:#555;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.input-group-addon.input-sm{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-lg{padding:10px 16px;font-size:18px;border-radius:6px}.input-group-addon input[type=checkbox],.input-group-addon input[type=radio]{margin-top:0}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn-group:not(:last-child)>.btn,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:first-child>.btn-group:not(:first-child)>.btn,.input-group-btn:first-child>.btn:not(:first-child),.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group>.btn,.input-group-btn:last-child>.dropdown-toggle{border-top-left-radius:0;border-bottom-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;font-size:0;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-1px}.input-group-btn>.btn:active,.input-group-btn>.btn:focus,.input-group-btn>.btn:hover{z-index:2}.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group{margin-right:-1px}.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group{z-index:2;margin-left:-1px}.nav{padding-left:0;margin-bottom:0;list-style:none}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:focus,.nav>li>a:hover{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#777}.nav>li.disabled>a:focus,.nav>li.disabled>a:hover{color:#777;text-decoration:none;cursor:not-allowed;background-color:transparent}.nav .open>a,.nav .open>a:focus,.nav .open>a:hover{background-color:#eee;border-color:#337ab7}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav>li>a>img{max-width:none}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.42857143;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee #eee #ddd}.nav-tabs>li.active>a,.nav-tabs>li.active>a:focus,.nav-tabs>li.active>a:hover{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{float:none}.nav-tabs.nav-justified>li>a{margin-bottom:5px;text-align:center}.nav-tabs.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-tabs.nav-justified>li{display:table-cell;width:1%}.nav-tabs.nav-justified>li>a{margin-bottom:0}}.nav-tabs.nav-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:focus,.nav-tabs.nav-justified>.active>a:hover{border:1px solid #ddd}@media (min-width:768px){.nav-tabs.nav-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:focus,.nav-tabs.nav-justified>.active>a:hover{border-bottom-color:#fff}}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:4px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:focus,.nav-pills>li.active>a:hover{color:#fff;background-color:#337ab7}.nav-stacked>li{float:none}.nav-stacked>li+li{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{float:none}.nav-justified>li>a{margin-bottom:5px;text-align:center}.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-justified>li{display:table-cell;width:1%}.nav-justified>li>a{margin-bottom:0}}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:focus,.nav-tabs-justified>.active>a:hover{border:1px solid #ddd}@media (min-width:768px){.nav-tabs-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:focus,.nav-tabs-justified>.active>a:hover{border-bottom-color:#fff}}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-left-radius:0;border-top-right-radius:0}.navbar{position:relative;min-height:50px;margin-bottom:20px;border:1px solid transparent}@media (min-width:768px){.navbar{border-radius:4px}}@media (min-width:768px){.navbar-header{float:left}}.navbar-collapse{padding-right:15px;padding-left:15px;overflow-x:visible;-webkit-overflow-scrolling:touch;border-top:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1)}.navbar-collapse.in{overflow-y:auto}@media (min-width:768px){.navbar-collapse{width:auto;border-top:0;-webkit-box-shadow:none;box-shadow:none}.navbar-collapse.collapse{display:block!important;height:auto!important;padding-bottom:0;overflow:visible!important}.navbar-collapse.in{overflow-y:visible}.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse,.navbar-static-top .navbar-collapse{padding-right:0;padding-left:0}}.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse{max-height:340px}@media (max-device-width:480px) and (orientation:landscape){.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse{max-height:200px}}.container-fluid>.navbar-collapse,.container-fluid>.navbar-header,.container>.navbar-collapse,.container>.navbar-header{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.container-fluid>.navbar-collapse,.container-fluid>.navbar-header,.container>.navbar-collapse,.container>.navbar-header{margin-right:0;margin-left:0}}.navbar-static-top{z-index:1000;border-width:0 0 1px}@media (min-width:768px){.navbar-static-top{border-radius:0}}.navbar-fixed-bottom,.navbar-fixed-top{position:fixed;right:0;left:0;z-index:1030}@media (min-width:768px){.navbar-fixed-bottom,.navbar-fixed-top{border-radius:0}}.navbar-fixed-top{top:0;border-width:0 0 1px}.navbar-fixed-bottom{bottom:0;margin-bottom:0;border-width:1px 0 0}.navbar-brand{float:left;height:50px;padding:15px 15px;font-size:18px;line-height:20px}.navbar-brand:focus,.navbar-brand:hover{text-decoration:none}.navbar-brand>img{display:block}@media (min-width:768px){.navbar>.container .navbar-brand,.navbar>.container-fluid .navbar-brand{margin-left:-15px}}.navbar-toggle{position:relative;float:right;padding:9px 10px;margin-top:8px;margin-right:15px;margin-bottom:8px;background-color:transparent;background-image:none;border:1px solid transparent;border-radius:4px}.navbar-toggle:focus{outline:0}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}@media (min-width:768px){.navbar-toggle{display:none}}.navbar-nav{margin:7.5px -15px}.navbar-nav>li>a{padding-top:10px;padding-bottom:10px;line-height:20px}@media (max-width:767px){.navbar-nav .open .dropdown-menu{position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;-webkit-box-shadow:none;box-shadow:none}.navbar-nav .open .dropdown-menu .dropdown-header,.navbar-nav .open .dropdown-menu>li>a{padding:5px 15px 5px 25px}.navbar-nav .open .dropdown-menu>li>a{line-height:20px}.navbar-nav .open .dropdown-menu>li>a:focus,.navbar-nav .open .dropdown-menu>li>a:hover{background-image:none}}@media (min-width:768px){.navbar-nav{float:left;margin:0}.navbar-nav>li{float:left}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px}}.navbar-form{padding:10px 15px;margin-top:8px;margin-right:-15px;margin-bottom:8px;margin-left:-15px;border-top:1px solid transparent;border-bottom:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1)}@media (min-width:768px){.navbar-form .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.navbar-form .form-control{display:inline-block;width:auto;vertical-align:middle}.navbar-form .form-control-static{display:inline-block}.navbar-form .input-group{display:inline-table;vertical-align:middle}.navbar-form .input-group .form-control,.navbar-form .input-group .input-group-addon,.navbar-form .input-group .input-group-btn{width:auto}.navbar-form .input-group>.form-control{width:100%}.navbar-form .control-label{margin-bottom:0;vertical-align:middle}.navbar-form .checkbox,.navbar-form .radio{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.navbar-form .checkbox label,.navbar-form .radio label{padding-left:0}.navbar-form .checkbox input[type=checkbox],.navbar-form .radio input[type=radio]{position:relative;margin-left:0}.navbar-form .has-feedback .form-control-feedback{top:0}}@media (max-width:767px){.navbar-form .form-group{margin-bottom:5px}.navbar-form .form-group:last-child{margin-bottom:0}}@media (min-width:768px){.navbar-form{width:auto;padding-top:0;padding-bottom:0;margin-right:0;margin-left:0;border:0;-webkit-box-shadow:none;box-shadow:none}}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-left-radius:0;border-top-right-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{margin-bottom:0;border-top-left-radius:4px;border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-btn{margin-top:8px;margin-bottom:8px}.navbar-btn.btn-sm{margin-top:10px;margin-bottom:10px}.navbar-btn.btn-xs{margin-top:14px;margin-bottom:14px}.navbar-text{margin-top:15px;margin-bottom:15px}@media (min-width:768px){.navbar-text{float:left;margin-right:15px;margin-left:15px}}@media (min-width:768px){.navbar-left{float:left!important}.navbar-right{float:right!important;margin-right:-15px}.navbar-right~.navbar-right{margin-right:0}}.navbar-default{background-color:#f8f8f8;border-color:#e7e7e7}.navbar-default .navbar-brand{color:#777}.navbar-default .navbar-brand:focus,.navbar-default .navbar-brand:hover{color:#5e5e5e;background-color:transparent}.navbar-default .navbar-text{color:#777}.navbar-default .navbar-nav>li>a{color:#777}.navbar-default .navbar-nav>li>a:focus,.navbar-default .navbar-nav>li>a:hover{color:#333;background-color:transparent}.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:focus,.navbar-default .navbar-nav>.active>a:hover{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:focus,.navbar-default .navbar-nav>.disabled>a:hover{color:#ccc;background-color:transparent}.navbar-default .navbar-toggle{border-color:#ddd}.navbar-default .navbar-toggle:focus,.navbar-default .navbar-toggle:hover{background-color:#ddd}.navbar-default .navbar-toggle .icon-bar{background-color:#888}.navbar-default .navbar-collapse,.navbar-default .navbar-form{border-color:#e7e7e7}.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:focus,.navbar-default .navbar-nav>.open>a:hover{color:#555;background-color:#e7e7e7}@media (max-width:767px){.navbar-default .navbar-nav .open .dropdown-menu>li>a{color:#777}.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover{color:#333;background-color:transparent}.navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover{color:#ccc;background-color:transparent}}.navbar-default .navbar-link{color:#777}.navbar-default .navbar-link:hover{color:#333}.navbar-default .btn-link{color:#777}.navbar-default .btn-link:focus,.navbar-default .btn-link:hover{color:#333}.navbar-default .btn-link[disabled]:focus,.navbar-default .btn-link[disabled]:hover,fieldset[disabled] .navbar-default .btn-link:focus,fieldset[disabled] .navbar-default .btn-link:hover{color:#ccc}.navbar-inverse{background-color:#222;border-color:#080808}.navbar-inverse .navbar-brand{color:#9d9d9d}.navbar-inverse .navbar-brand:focus,.navbar-inverse .navbar-brand:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-text{color:#9d9d9d}.navbar-inverse .navbar-nav>li>a{color:#9d9d9d}.navbar-inverse .navbar-nav>li>a:focus,.navbar-inverse .navbar-nav>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:focus,.navbar-inverse .navbar-nav>.active>a:hover{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:focus,.navbar-inverse .navbar-nav>.disabled>a:hover{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:focus,.navbar-inverse .navbar-toggle:hover{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form{border-color:#101010}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:focus,.navbar-inverse .navbar-nav>.open>a:hover{color:#fff;background-color:#080808}@media (max-width:767px){.navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header{border-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu .divider{background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a{color:#9d9d9d}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover{color:#444;background-color:transparent}}.navbar-inverse .navbar-link{color:#9d9d9d}.navbar-inverse .navbar-link:hover{color:#fff}.navbar-inverse .btn-link{color:#9d9d9d}.navbar-inverse .btn-link:focus,.navbar-inverse .btn-link:hover{color:#fff}.navbar-inverse .btn-link[disabled]:focus,.navbar-inverse .btn-link[disabled]:hover,fieldset[disabled] .navbar-inverse .btn-link:focus,fieldset[disabled] .navbar-inverse .btn-link:hover{color:#444}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{padding:0 5px;color:#ccc;content:"/\00a0"}.breadcrumb>.active{color:#777}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:6px 12px;margin-left:-1px;line-height:1.42857143;color:#337ab7;text-decoration:none;background-color:#fff;border:1px solid #ddd}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-top-left-radius:4px;border-bottom-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-top-right-radius:4px;border-bottom-right-radius:4px}.pagination>li>a:focus,.pagination>li>a:hover,.pagination>li>span:focus,.pagination>li>span:hover{z-index:2;color:#23527c;background-color:#eee;border-color:#ddd}.pagination>.active>a,.pagination>.active>a:focus,.pagination>.active>a:hover,.pagination>.active>span,.pagination>.active>span:focus,.pagination>.active>span:hover{z-index:3;color:#fff;cursor:default;background-color:#337ab7;border-color:#337ab7}.pagination>.disabled>a,.pagination>.disabled>a:focus,.pagination>.disabled>a:hover,.pagination>.disabled>span,.pagination>.disabled>span:focus,.pagination>.disabled>span:hover{color:#777;cursor:not-allowed;background-color:#fff;border-color:#ddd}.pagination-lg>li>a,.pagination-lg>li>span{padding:10px 16px;font-size:18px;line-height:1.3333333}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-top-left-radius:6px;border-bottom-left-radius:6px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-top-right-radius:6px;border-bottom-right-radius:6px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:12px;line-height:1.5}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-top-left-radius:3px;border-bottom-left-radius:3px}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-top-right-radius:3px;border-bottom-right-radius:3px}.pager{padding-left:0;margin:20px 0;text-align:center;list-style:none}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:focus,.pager li>a:hover{text-decoration:none;background-color:#eee}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:focus,.pager .disabled>a:hover,.pager .disabled>span{color:#777;cursor:not-allowed;background-color:#fff}.label{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em}a.label:focus,a.label:hover{color:#fff;text-decoration:none;cursor:pointer}.label:empty{display:none}.btn .label{position:relative;top:-1px}.label-default{background-color:#777}.label-default[href]:focus,.label-default[href]:hover{background-color:#5e5e5e}.label-primary{background-color:#337ab7}.label-primary[href]:focus,.label-primary[href]:hover{background-color:#286090}.label-success{background-color:#5cb85c}.label-success[href]:focus,.label-success[href]:hover{background-color:#449d44}.label-info{background-color:#5bc0de}.label-info[href]:focus,.label-info[href]:hover{background-color:#31b0d5}.label-warning{background-color:#f0ad4e}.label-warning[href]:focus,.label-warning[href]:hover{background-color:#ec971f}.label-danger{background-color:#d9534f}.label-danger[href]:focus,.label-danger[href]:hover{background-color:#c9302c}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:middle;background-color:#777;border-radius:10px}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.btn-group-xs>.btn .badge,.btn-xs .badge{top:0;padding:1px 5px}a.badge:focus,a.badge:hover{color:#fff;text-decoration:none;cursor:pointer}.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#337ab7;background-color:#fff}.list-group-item>.badge{float:right}.list-group-item>.badge+.badge{margin-right:5px}.nav-pills>li>a>.badge{margin-left:3px}.jumbotron{padding-top:30px;padding-bottom:30px;margin-bottom:30px;color:inherit;background-color:#eee}.jumbotron .h1,.jumbotron h1{color:inherit}.jumbotron p{margin-bottom:15px;font-size:21px;font-weight:200}.jumbotron>hr{border-top-color:#d5d5d5}.container .jumbotron,.container-fluid .jumbotron{padding-right:15px;padding-left:15px;border-radius:6px}.jumbotron .container{max-width:100%}@media screen and (min-width:768px){.jumbotron{padding-top:48px;padding-bottom:48px}.container .jumbotron,.container-fluid .jumbotron{padding-right:60px;padding-left:60px}.jumbotron .h1,.jumbotron h1{font-size:63px}}.thumbnail{display:block;padding:4px;margin-bottom:20px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:border .2s ease-in-out;-o-transition:border .2s ease-in-out;transition:border .2s ease-in-out}.thumbnail a>img,.thumbnail>img{margin-right:auto;margin-left:auto}a.thumbnail.active,a.thumbnail:focus,a.thumbnail:hover{border-color:#337ab7}.thumbnail .caption{padding:9px;color:#333}.alert{padding:15px;margin-bottom:20px;border:1px solid transparent;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert .alert-link{font-weight:700}.alert>p,.alert>ul{margin-bottom:0}.alert>p+p{margin-top:5px}.alert-dismissable,.alert-dismissible{padding-right:35px}.alert-dismissable .close,.alert-dismissible .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#2b542c}.alert-info{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#245269}.alert-warning{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.alert-warning hr{border-top-color:#f7e1b5}.alert-warning .alert-link{color:#66512c}.alert-danger{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.alert-danger hr{border-top-color:#e4b9c0}.alert-danger .alert-link{color:#843534}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,.1);box-shadow:inset 0 1px 2px rgba(0,0,0,.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;line-height:20px;color:#fff;text-align:center;background-color:#337ab7;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);-webkit-transition:width .6s ease;-o-transition:width .6s ease;transition:width .6s ease}.progress-bar-striped,.progress-striped .progress-bar{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);-webkit-background-size:40px 40px;background-size:40px 40px}.progress-bar.active,.progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-success{background-color:#5cb85c}.progress-striped .progress-bar-success{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#5bc0de}.progress-striped .progress-bar-info{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f0ad4e}.progress-striped .progress-bar-warning{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-danger{background-color:#d9534f}.progress-striped .progress-bar-danger{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.media{margin-top:15px}.media:first-child{margin-top:0}.media,.media-body{overflow:hidden;zoom:1}.media-body{width:10000px}.media-object{display:block}.media-object.img-thumbnail{max-width:none}.media-right,.media>.pull-right{padding-left:10px}.media-left,.media>.pull-left{padding-right:10px}.media-body,.media-left,.media-right{display:table-cell;vertical-align:top}.media-middle{vertical-align:middle}.media-bottom{vertical-align:bottom}.media-heading{margin-top:0;margin-bottom:5px}.media-list{padding-left:0;list-style:none}.list-group{padding-left:0;margin-bottom:20px}.list-group-item{position:relative;display:block;padding:10px 15px;margin-bottom:-1px;background-color:#fff;border:1px solid #ddd}.list-group-item:first-child{border-top-left-radius:4px;border-top-right-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}a.list-group-item,button.list-group-item{color:#555}a.list-group-item .list-group-item-heading,button.list-group-item .list-group-item-heading{color:#333}a.list-group-item:focus,a.list-group-item:hover,button.list-group-item:focus,button.list-group-item:hover{color:#555;text-decoration:none;background-color:#f5f5f5}button.list-group-item{width:100%;text-align:left}.list-group-item.disabled,.list-group-item.disabled:focus,.list-group-item.disabled:hover{color:#777;cursor:not-allowed;background-color:#eee}.list-group-item.disabled .list-group-item-heading,.list-group-item.disabled:focus .list-group-item-heading,.list-group-item.disabled:hover .list-group-item-heading{color:inherit}.list-group-item.disabled .list-group-item-text,.list-group-item.disabled:focus .list-group-item-text,.list-group-item.disabled:hover .list-group-item-text{color:#777}.list-group-item.active,.list-group-item.active:focus,.list-group-item.active:hover{z-index:2;color:#fff;background-color:#337ab7;border-color:#337ab7}.list-group-item.active .list-group-item-heading,.list-group-item.active .list-group-item-heading>.small,.list-group-item.active .list-group-item-heading>small,.list-group-item.active:focus .list-group-item-heading,.list-group-item.active:focus .list-group-item-heading>.small,.list-group-item.active:focus .list-group-item-heading>small,.list-group-item.active:hover .list-group-item-heading,.list-group-item.active:hover .list-group-item-heading>.small,.list-group-item.active:hover .list-group-item-heading>small{color:inherit}.list-group-item.active .list-group-item-text,.list-group-item.active:focus .list-group-item-text,.list-group-item.active:hover .list-group-item-text{color:#c7ddef}.list-group-item-success{color:#3c763d;background-color:#dff0d8}a.list-group-item-success,button.list-group-item-success{color:#3c763d}a.list-group-item-success .list-group-item-heading,button.list-group-item-success .list-group-item-heading{color:inherit}a.list-group-item-success:focus,a.list-group-item-success:hover,button.list-group-item-success:focus,button.list-group-item-success:hover{color:#3c763d;background-color:#d0e9c6}a.list-group-item-success.active,a.list-group-item-success.active:focus,a.list-group-item-success.active:hover,button.list-group-item-success.active,button.list-group-item-success.active:focus,button.list-group-item-success.active:hover{color:#fff;background-color:#3c763d;border-color:#3c763d}.list-group-item-info{color:#31708f;background-color:#d9edf7}a.list-group-item-info,button.list-group-item-info{color:#31708f}a.list-group-item-info .list-group-item-heading,button.list-group-item-info .list-group-item-heading{color:inherit}a.list-group-item-info:focus,a.list-group-item-info:hover,button.list-group-item-info:focus,button.list-group-item-info:hover{color:#31708f;background-color:#c4e3f3}a.list-group-item-info.active,a.list-group-item-info.active:focus,a.list-group-item-info.active:hover,button.list-group-item-info.active,button.list-group-item-info.active:focus,button.list-group-item-info.active:hover{color:#fff;background-color:#31708f;border-color:#31708f}.list-group-item-warning{color:#8a6d3b;background-color:#fcf8e3}a.list-group-item-warning,button.list-group-item-warning{color:#8a6d3b}a.list-group-item-warning .list-group-item-heading,button.list-group-item-warning .list-group-item-heading{color:inherit}a.list-group-item-warning:focus,a.list-group-item-warning:hover,button.list-group-item-warning:focus,button.list-group-item-warning:hover{color:#8a6d3b;background-color:#faf2cc}a.list-group-item-warning.active,a.list-group-item-warning.active:focus,a.list-group-item-warning.active:hover,button.list-group-item-warning.active,button.list-group-item-warning.active:focus,button.list-group-item-warning.active:hover{color:#fff;background-color:#8a6d3b;border-color:#8a6d3b}.list-group-item-danger{color:#a94442;background-color:#f2dede}a.list-group-item-danger,button.list-group-item-danger{color:#a94442}a.list-group-item-danger .list-group-item-heading,button.list-group-item-danger .list-group-item-heading{color:inherit}a.list-group-item-danger:focus,a.list-group-item-danger:hover,button.list-group-item-danger:focus,button.list-group-item-danger:hover{color:#a94442;background-color:#ebcccc}a.list-group-item-danger.active,a.list-group-item-danger.active:focus,a.list-group-item-danger.active:hover,button.list-group-item-danger.active,button.list-group-item-danger.active:focus,button.list-group-item-danger.active:hover{color:#fff;background-color:#a94442;border-color:#a94442}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}.panel{margin-bottom:20px;background-color:#fff;border:1px solid transparent;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.05);box-shadow:0 1px 1px rgba(0,0,0,.05)}.panel-body{padding:15px}.panel-heading{padding:10px 15px;border-bottom:1px solid transparent;border-top-left-radius:3px;border-top-right-radius:3px}.panel-heading>.dropdown .dropdown-toggle{color:inherit}.panel-title{margin-top:0;margin-bottom:0;font-size:16px;color:inherit}.panel-title>.small,.panel-title>.small>a,.panel-title>a,.panel-title>small,.panel-title>small>a{color:inherit}.panel-footer{padding:10px 15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.list-group,.panel>.panel-collapse>.list-group{margin-bottom:0}.panel>.list-group .list-group-item,.panel>.panel-collapse>.list-group .list-group-item{border-width:1px 0;border-radius:0}.panel>.list-group:first-child .list-group-item:first-child,.panel>.panel-collapse>.list-group:first-child .list-group-item:first-child{border-top:0;border-top-left-radius:3px;border-top-right-radius:3px}.panel>.list-group:last-child .list-group-item:last-child,.panel>.panel-collapse>.list-group:last-child .list-group-item:last-child{border-bottom:0;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.panel-heading+.panel-collapse>.list-group .list-group-item:first-child{border-top-left-radius:0;border-top-right-radius:0}.panel-heading+.list-group .list-group-item:first-child{border-top-width:0}.list-group+.panel-footer{border-top-width:0}.panel>.panel-collapse>.table,.panel>.table,.panel>.table-responsive>.table{margin-bottom:0}.panel>.panel-collapse>.table caption,.panel>.table caption,.panel>.table-responsive>.table caption{padding-right:15px;padding-left:15px}.panel>.table-responsive:first-child>.table:first-child,.panel>.table:first-child{border-top-left-radius:3px;border-top-right-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child,.panel>.table:first-child>thead:first-child>tr:first-child{border-top-left-radius:3px;border-top-right-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table:first-child>thead:first-child>tr:first-child th:first-child{border-top-left-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table:first-child>thead:first-child>tr:first-child th:last-child{border-top-right-radius:3px}.panel>.table-responsive:last-child>.table:last-child,.panel>.table:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:first-child{border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:last-child{border-bottom-right-radius:3px}.panel>.panel-body+.table,.panel>.panel-body+.table-responsive,.panel>.table+.panel-body,.panel>.table-responsive+.panel-body{border-top:1px solid #ddd}.panel>.table>tbody:first-child>tr:first-child td,.panel>.table>tbody:first-child>tr:first-child th{border-top:0}.panel>.table-bordered,.panel>.table-responsive>.table-bordered{border:0}.panel>.table-bordered>tbody>tr>td:first-child,.panel>.table-bordered>tbody>tr>th:first-child,.panel>.table-bordered>tfoot>tr>td:first-child,.panel>.table-bordered>tfoot>tr>th:first-child,.panel>.table-bordered>thead>tr>td:first-child,.panel>.table-bordered>thead>tr>th:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:first-child,.panel>.table-responsive>.table-bordered>thead>tr>td:first-child,.panel>.table-responsive>.table-bordered>thead>tr>th:first-child{border-left:0}.panel>.table-bordered>tbody>tr>td:last-child,.panel>.table-bordered>tbody>tr>th:last-child,.panel>.table-bordered>tfoot>tr>td:last-child,.panel>.table-bordered>tfoot>tr>th:last-child,.panel>.table-bordered>thead>tr>td:last-child,.panel>.table-bordered>thead>tr>th:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:last-child,.panel>.table-responsive>.table-bordered>thead>tr>td:last-child,.panel>.table-responsive>.table-bordered>thead>tr>th:last-child{border-right:0}.panel>.table-bordered>tbody>tr:first-child>td,.panel>.table-bordered>tbody>tr:first-child>th,.panel>.table-bordered>thead>tr:first-child>td,.panel>.table-bordered>thead>tr:first-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>th,.panel>.table-responsive>.table-bordered>thead>tr:first-child>td,.panel>.table-responsive>.table-bordered>thead>tr:first-child>th{border-bottom:0}.panel>.table-bordered>tbody>tr:last-child>td,.panel>.table-bordered>tbody>tr:last-child>th,.panel>.table-bordered>tfoot>tr:last-child>td,.panel>.table-bordered>tfoot>tr:last-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>th,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>td,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}.panel>.table-responsive{margin-bottom:0;border:0}.panel-group{margin-bottom:20px}.panel-group .panel{margin-bottom:0;border-radius:4px}.panel-group .panel+.panel{margin-top:5px}.panel-group .panel-heading{border-bottom:0}.panel-group .panel-heading+.panel-collapse>.list-group,.panel-group .panel-heading+.panel-collapse>.panel-body{border-top:1px solid #ddd}.panel-group .panel-footer{border-top:0}.panel-group .panel-footer+.panel-collapse .panel-body{border-bottom:1px solid #ddd}.panel-default{border-color:#ddd}.panel-default>.panel-heading{color:#333;background-color:#f5f5f5;border-color:#ddd}.panel-default>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ddd}.panel-default>.panel-heading .badge{color:#f5f5f5;background-color:#333}.panel-default>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ddd}.panel-primary{border-color:#337ab7}.panel-primary>.panel-heading{color:#fff;background-color:#337ab7;border-color:#337ab7}.panel-primary>.panel-heading+.panel-collapse>.panel-body{border-top-color:#337ab7}.panel-primary>.panel-heading .badge{color:#337ab7;background-color:#fff}.panel-primary>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#337ab7}.panel-success{border-color:#d6e9c6}.panel-success>.panel-heading{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.panel-success>.panel-heading+.panel-collapse>.panel-body{border-top-color:#d6e9c6}.panel-success>.panel-heading .badge{color:#dff0d8;background-color:#3c763d}.panel-success>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#d6e9c6}.panel-info{border-color:#bce8f1}.panel-info>.panel-heading{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.panel-info>.panel-heading+.panel-collapse>.panel-body{border-top-color:#bce8f1}.panel-info>.panel-heading .badge{color:#d9edf7;background-color:#31708f}.panel-info>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#bce8f1}.panel-warning{border-color:#faebcc}.panel-warning>.panel-heading{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.panel-warning>.panel-heading+.panel-collapse>.panel-body{border-top-color:#faebcc}.panel-warning>.panel-heading .badge{color:#fcf8e3;background-color:#8a6d3b}.panel-warning>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#faebcc}.panel-danger{border-color:#ebccd1}.panel-danger>.panel-heading{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.panel-danger>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ebccd1}.panel-danger>.panel-heading .badge{color:#f2dede;background-color:#a94442}.panel-danger>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ebccd1}.embed-responsive{position:relative;display:block;height:0;padding:0;overflow:hidden}.embed-responsive .embed-responsive-item,.embed-responsive embed,.embed-responsive iframe,.embed-responsive object,.embed-responsive video{position:absolute;top:0;bottom:0;left:0;width:100%;height:100%;border:0}.embed-responsive-16by9{padding-bottom:56.25%}.embed-responsive-4by3{padding-bottom:75%}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.05);box-shadow:inset 0 1px 1px rgba(0,0,0,.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,.15)}.well-lg{padding:24px;border-radius:6px}.well-sm{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;filter:alpha(opacity=20);opacity:.2}.close:focus,.close:hover{color:#000;text-decoration:none;cursor:pointer;filter:alpha(opacity=50);opacity:.5}button.close{-webkit-appearance:none;padding:0;cursor:pointer;background:0 0;border:0}.modal-open{overflow:hidden}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1050;display:none;overflow:hidden;-webkit-overflow-scrolling:touch;outline:0}.modal.fade .modal-dialog{-webkit-transition:-webkit-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out;-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);-o-transform:translate(0,-25%);transform:translate(0,-25%)}.modal.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);-o-transform:translate(0,0);transform:translate(0,0)}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal-dialog{position:relative;width:auto;margin:10px}.modal-content{position:relative;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #999;border:1px solid rgba(0,0,0,.2);border-radius:6px;outline:0;-webkit-box-shadow:0 3px 9px rgba(0,0,0,.5);box-shadow:0 3px 9px rgba(0,0,0,.5)}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{filter:alpha(opacity=0);opacity:0}.modal-backdrop.in{filter:alpha(opacity=50);opacity:.5}.modal-header{padding:15px;border-bottom:1px solid #e5e5e5}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.42857143}.modal-body{position:relative;padding:15px}.modal-footer{padding:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media (min-width:768px){.modal-dialog{width:600px;margin:30px auto}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,.5);box-shadow:0 5px 15px rgba(0,0,0,.5)}.modal-sm{width:300px}}@media (min-width:992px){.modal-lg{width:900px}}.tooltip{position:absolute;z-index:1070;display:block;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:12px;font-style:normal;font-weight:400;line-height:1.42857143;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;word-wrap:normal;white-space:normal;filter:alpha(opacity=0);opacity:0;line-break:auto}.tooltip.in{filter:alpha(opacity=90);opacity:.9}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;background-color:#000;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-left .tooltip-arrow{right:5px;bottom:0;margin-bottom:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-right .tooltip-arrow{bottom:0;left:5px;margin-bottom:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-width:5px 5px 5px 0;border-right-color:#000}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-width:5px 0 5px 5px;border-left-color:#000}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-left .tooltip-arrow{top:0;right:5px;margin-top:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-right .tooltip-arrow{top:0;left:5px;margin-top:-5px;border-width:0 5px 5px;border-bottom-color:#000}.popover{position:absolute;top:0;left:0;z-index:1060;display:none;max-width:276px;padding:1px;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;font-style:normal;font-weight:400;line-height:1.42857143;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;word-wrap:normal;white-space:normal;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,.2);box-shadow:0 5px 10px rgba(0,0,0,.2);line-break:auto}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover>.arrow,.popover>.arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover>.arrow{border-width:11px}.popover>.arrow:after{content:"";border-width:10px}.popover.top>.arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,.25);border-bottom-width:0}.popover.top>.arrow:after{bottom:1px;margin-left:-10px;content:" ";border-top-color:#fff;border-bottom-width:0}.popover.right>.arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,.25);border-left-width:0}.popover.right>.arrow:after{bottom:-10px;left:1px;content:" ";border-right-color:#fff;border-left-width:0}.popover.bottom>.arrow{top:-11px;left:50%;margin-left:-11px;border-top-width:0;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,.25)}.popover.bottom>.arrow:after{top:1px;margin-left:-10px;content:" ";border-top-width:0;border-bottom-color:#fff}.popover.left>.arrow{top:50%;right:-11px;margin-top:-11px;border-right-width:0;border-left-color:#999;border-left-color:rgba(0,0,0,.25)}.popover.left>.arrow:after{right:1px;bottom:-10px;content:" ";border-right-width:0;border-left-color:#fff}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;-o-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>a>img,.carousel-inner>.item>img{line-height:1}@media all and (transform-3d),(-webkit-transform-3d){.carousel-inner>.item{-webkit-transition:-webkit-transform .6s ease-in-out;-o-transition:-o-transform .6s ease-in-out;transition:transform .6s ease-in-out;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-perspective:1000px;perspective:1000px}.carousel-inner>.item.active.right,.carousel-inner>.item.next{left:0;-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}.carousel-inner>.item.active.left,.carousel-inner>.item.prev{left:0;-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}.carousel-inner>.item.active,.carousel-inner>.item.next.left,.carousel-inner>.item.prev.right{left:0;-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;bottom:0;left:0;width:15%;font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6);background-color:rgba(0,0,0,0);filter:alpha(opacity=50);opacity:.5}.carousel-control.left{background-image:-webkit-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:-webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.5)),to(rgba(0,0,0,.0001)));background-image:linear-gradient(to right,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);background-repeat:repeat-x}.carousel-control.right{right:0;left:auto;background-image:-webkit-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:-webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.0001)),to(rgba(0,0,0,.5)));background-image:linear-gradient(to right,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);background-repeat:repeat-x}.carousel-control:focus,.carousel-control:hover{color:#fff;text-decoration:none;filter:alpha(opacity=90);outline:0;opacity:.9}.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next,.carousel-control .icon-prev{position:absolute;top:50%;z-index:5;display:inline-block;margin-top:-10px}.carousel-control .glyphicon-chevron-left,.carousel-control .icon-prev{left:50%;margin-left:-10px}.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next{right:50%;margin-right:-10px}.carousel-control .icon-next,.carousel-control .icon-prev{width:20px;height:20px;font-family:serif;line-height:1}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:60%;padding-left:0;margin-left:-30%;text-align:center;list-style:none}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;cursor:pointer;background-color:#000\9;background-color:rgba(0,0,0,0);border:1px solid #fff;border-radius:10px}.carousel-indicators .active{width:12px;height:12px;margin:0;background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next,.carousel-control .icon-prev{width:30px;height:30px;margin-top:-10px;font-size:30px}.carousel-control .glyphicon-chevron-left,.carousel-control .icon-prev{margin-left:-10px}.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next{margin-right:-10px}.carousel-caption{right:20%;left:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.btn-group-vertical>.btn-group:after,.btn-group-vertical>.btn-group:before,.btn-toolbar:after,.btn-toolbar:before,.clearfix:after,.clearfix:before,.container-fluid:after,.container-fluid:before,.container:after,.container:before,.dl-horizontal dd:after,.dl-horizontal dd:before,.form-horizontal .form-group:after,.form-horizontal .form-group:before,.modal-footer:after,.modal-footer:before,.modal-header:after,.modal-header:before,.nav:after,.nav:before,.navbar-collapse:after,.navbar-collapse:before,.navbar-header:after,.navbar-header:before,.navbar:after,.navbar:before,.pager:after,.pager:before,.panel-body:after,.panel-body:before,.row:after,.row:before{display:table;content:" "}.btn-group-vertical>.btn-group:after,.btn-toolbar:after,.clearfix:after,.container-fluid:after,.container:after,.dl-horizontal dd:after,.form-horizontal .form-group:after,.modal-footer:after,.modal-header:after,.nav:after,.navbar-collapse:after,.navbar-header:after,.navbar:after,.pager:after,.panel-body:after,.row:after{clear:both}.center-block{display:block;margin-right:auto;margin-left:auto}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.hidden{display:none!important}.affix{position:fixed}@-ms-viewport{width:device-width}.visible-lg,.visible-md,.visible-sm,.visible-xs{display:none!important}.visible-lg-block,.visible-lg-inline,.visible-lg-inline-block,.visible-md-block,.visible-md-inline,.visible-md-inline-block,.visible-sm-block,.visible-sm-inline,.visible-sm-inline-block,.visible-xs-block,.visible-xs-inline,.visible-xs-inline-block{display:none!important}@media (max-width:767px){.visible-xs{display:block!important}table.visible-xs{display:table!important}tr.visible-xs{display:table-row!important}td.visible-xs,th.visible-xs{display:table-cell!important}}@media (max-width:767px){.visible-xs-block{display:block!important}}@media (max-width:767px){.visible-xs-inline{display:inline!important}}@media (max-width:767px){.visible-xs-inline-block{display:inline-block!important}}@media (min-width:768px) and (max-width:991px){.visible-sm{display:block!important}table.visible-sm{display:table!important}tr.visible-sm{display:table-row!important}td.visible-sm,th.visible-sm{display:table-cell!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-block{display:block!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-inline{display:inline!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-inline-block{display:inline-block!important}}@media (min-width:992px) and (max-width:1199px){.visible-md{display:block!important}table.visible-md{display:table!important}tr.visible-md{display:table-row!important}td.visible-md,th.visible-md{display:table-cell!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-block{display:block!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-inline{display:inline!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-inline-block{display:inline-block!important}}@media (min-width:1200px){.visible-lg{display:block!important}table.visible-lg{display:table!important}tr.visible-lg{display:table-row!important}td.visible-lg,th.visible-lg{display:table-cell!important}}@media (min-width:1200px){.visible-lg-block{display:block!important}}@media (min-width:1200px){.visible-lg-inline{display:inline!important}}@media (min-width:1200px){.visible-lg-inline-block{display:inline-block!important}}@media (max-width:767px){.hidden-xs{display:none!important}}@media (min-width:768px) and (max-width:991px){.hidden-sm{display:none!important}}@media (min-width:992px) and (max-width:1199px){.hidden-md{display:none!important}}@media (min-width:1200px){.hidden-lg{display:none!important}}.visible-print{display:none!important}@media print{.visible-print{display:block!important}table.visible-print{display:table!important}tr.visible-print{display:table-row!important}td.visible-print,th.visible-print{display:table-cell!important}}.visible-print-block{display:none!important}@media print{.visible-print-block{display:block!important}}.visible-print-inline{display:none!important}@media print{.visible-print-inline{display:inline!important}}.visible-print-inline-block{display:none!important}@media print{.visible-print-inline-block{display:inline-block!important}}@media print{.hidden-print{display:none!important}} +/*# sourceMappingURL=bootstrap.min.css.map */ \ No newline at end of file diff --git a/data/web/common/handlebars-v4.0.5.js b/data/web/common/handlebars-v4.0.5.js new file mode 100644 index 0000000000..289ae458ae --- /dev/null +++ b/data/web/common/handlebars-v4.0.5.js @@ -0,0 +1,4608 @@ +/*! + + handlebars v4.0.5 + +Copyright (C) 2011-2015 by Yehuda Katz + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +@license +*/ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["Handlebars"] = factory(); + else + root["Handlebars"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var _interopRequireDefault = __webpack_require__(1)['default']; + + exports.__esModule = true; + + var _handlebarsRuntime = __webpack_require__(2); + + var _handlebarsRuntime2 = _interopRequireDefault(_handlebarsRuntime); + + // Compiler imports + + var _handlebarsCompilerAst = __webpack_require__(21); + + var _handlebarsCompilerAst2 = _interopRequireDefault(_handlebarsCompilerAst); + + var _handlebarsCompilerBase = __webpack_require__(22); + + var _handlebarsCompilerCompiler = __webpack_require__(27); + + var _handlebarsCompilerJavascriptCompiler = __webpack_require__(28); + + var _handlebarsCompilerJavascriptCompiler2 = _interopRequireDefault(_handlebarsCompilerJavascriptCompiler); + + var _handlebarsCompilerVisitor = __webpack_require__(25); + + var _handlebarsCompilerVisitor2 = _interopRequireDefault(_handlebarsCompilerVisitor); + + var _handlebarsNoConflict = __webpack_require__(20); + + var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict); + + var _create = _handlebarsRuntime2['default'].create; + function create() { + var hb = _create(); + + hb.compile = function (input, options) { + return _handlebarsCompilerCompiler.compile(input, options, hb); + }; + hb.precompile = function (input, options) { + return _handlebarsCompilerCompiler.precompile(input, options, hb); + }; + + hb.AST = _handlebarsCompilerAst2['default']; + hb.Compiler = _handlebarsCompilerCompiler.Compiler; + hb.JavaScriptCompiler = _handlebarsCompilerJavascriptCompiler2['default']; + hb.Parser = _handlebarsCompilerBase.parser; + hb.parse = _handlebarsCompilerBase.parse; + + return hb; + } + + var inst = create(); + inst.create = create; + + _handlebarsNoConflict2['default'](inst); + + inst.Visitor = _handlebarsCompilerVisitor2['default']; + + inst['default'] = inst; + + exports['default'] = inst; + module.exports = exports['default']; + +/***/ }, +/* 1 */ +/***/ function(module, exports) { + + "use strict"; + + exports["default"] = function (obj) { + return obj && obj.__esModule ? obj : { + "default": obj + }; + }; + + exports.__esModule = true; + +/***/ }, +/* 2 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var _interopRequireWildcard = __webpack_require__(3)['default']; + + var _interopRequireDefault = __webpack_require__(1)['default']; + + exports.__esModule = true; + + var _handlebarsBase = __webpack_require__(4); + + var base = _interopRequireWildcard(_handlebarsBase); + + // Each of these augment the Handlebars object. No need to setup here. + // (This is done to easily share code between commonjs and browse envs) + + var _handlebarsSafeString = __webpack_require__(18); + + var _handlebarsSafeString2 = _interopRequireDefault(_handlebarsSafeString); + + var _handlebarsException = __webpack_require__(6); + + var _handlebarsException2 = _interopRequireDefault(_handlebarsException); + + var _handlebarsUtils = __webpack_require__(5); + + var Utils = _interopRequireWildcard(_handlebarsUtils); + + var _handlebarsRuntime = __webpack_require__(19); + + var runtime = _interopRequireWildcard(_handlebarsRuntime); + + var _handlebarsNoConflict = __webpack_require__(20); + + var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict); + + // For compatibility and usage outside of module systems, make the Handlebars object a namespace + function create() { + var hb = new base.HandlebarsEnvironment(); + + Utils.extend(hb, base); + hb.SafeString = _handlebarsSafeString2['default']; + hb.Exception = _handlebarsException2['default']; + hb.Utils = Utils; + hb.escapeExpression = Utils.escapeExpression; + + hb.VM = runtime; + hb.template = function (spec) { + return runtime.template(spec, hb); + }; + + return hb; + } + + var inst = create(); + inst.create = create; + + _handlebarsNoConflict2['default'](inst); + + inst['default'] = inst; + + exports['default'] = inst; + module.exports = exports['default']; + +/***/ }, +/* 3 */ +/***/ function(module, exports) { + + "use strict"; + + exports["default"] = function (obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + + newObj["default"] = obj; + return newObj; + } + }; + + exports.__esModule = true; + +/***/ }, +/* 4 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var _interopRequireDefault = __webpack_require__(1)['default']; + + exports.__esModule = true; + exports.HandlebarsEnvironment = HandlebarsEnvironment; + + var _utils = __webpack_require__(5); + + var _exception = __webpack_require__(6); + + var _exception2 = _interopRequireDefault(_exception); + + var _helpers = __webpack_require__(7); + + var _decorators = __webpack_require__(15); + + var _logger = __webpack_require__(17); + + var _logger2 = _interopRequireDefault(_logger); + + var VERSION = '4.0.5'; + exports.VERSION = VERSION; + var COMPILER_REVISION = 7; + + exports.COMPILER_REVISION = COMPILER_REVISION; + var REVISION_CHANGES = { + 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it + 2: '== 1.0.0-rc.3', + 3: '== 1.0.0-rc.4', + 4: '== 1.x.x', + 5: '== 2.0.0-alpha.x', + 6: '>= 2.0.0-beta.1', + 7: '>= 4.0.0' + }; + + exports.REVISION_CHANGES = REVISION_CHANGES; + var objectType = '[object Object]'; + + function HandlebarsEnvironment(helpers, partials, decorators) { + this.helpers = helpers || {}; + this.partials = partials || {}; + this.decorators = decorators || {}; + + _helpers.registerDefaultHelpers(this); + _decorators.registerDefaultDecorators(this); + } + + HandlebarsEnvironment.prototype = { + constructor: HandlebarsEnvironment, + + logger: _logger2['default'], + log: _logger2['default'].log, + + registerHelper: function registerHelper(name, fn) { + if (_utils.toString.call(name) === objectType) { + if (fn) { + throw new _exception2['default']('Arg not supported with multiple helpers'); + } + _utils.extend(this.helpers, name); + } else { + this.helpers[name] = fn; + } + }, + unregisterHelper: function unregisterHelper(name) { + delete this.helpers[name]; + }, + + registerPartial: function registerPartial(name, partial) { + if (_utils.toString.call(name) === objectType) { + _utils.extend(this.partials, name); + } else { + if (typeof partial === 'undefined') { + throw new _exception2['default']('Attempting to register a partial called "' + name + '" as undefined'); + } + this.partials[name] = partial; + } + }, + unregisterPartial: function unregisterPartial(name) { + delete this.partials[name]; + }, + + registerDecorator: function registerDecorator(name, fn) { + if (_utils.toString.call(name) === objectType) { + if (fn) { + throw new _exception2['default']('Arg not supported with multiple decorators'); + } + _utils.extend(this.decorators, name); + } else { + this.decorators[name] = fn; + } + }, + unregisterDecorator: function unregisterDecorator(name) { + delete this.decorators[name]; + } + }; + + var log = _logger2['default'].log; + + exports.log = log; + exports.createFrame = _utils.createFrame; + exports.logger = _logger2['default']; + +/***/ }, +/* 5 */ +/***/ function(module, exports) { + + 'use strict'; + + exports.__esModule = true; + exports.extend = extend; + exports.indexOf = indexOf; + exports.escapeExpression = escapeExpression; + exports.isEmpty = isEmpty; + exports.createFrame = createFrame; + exports.blockParams = blockParams; + exports.appendContextPath = appendContextPath; + var escape = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', + '`': '`', + '=': '=' + }; + + var badChars = /[&<>"'`=]/g, + possible = /[&<>"'`=]/; + + function escapeChar(chr) { + return escape[chr]; + } + + function extend(obj /* , ...source */) { + for (var i = 1; i < arguments.length; i++) { + for (var key in arguments[i]) { + if (Object.prototype.hasOwnProperty.call(arguments[i], key)) { + obj[key] = arguments[i][key]; + } + } + } + + return obj; + } + + var toString = Object.prototype.toString; + + exports.toString = toString; + // Sourced from lodash + // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt + /* eslint-disable func-style */ + var isFunction = function isFunction(value) { + return typeof value === 'function'; + }; + // fallback for older versions of Chrome and Safari + /* istanbul ignore next */ + if (isFunction(/x/)) { + exports.isFunction = isFunction = function (value) { + return typeof value === 'function' && toString.call(value) === '[object Function]'; + }; + } + exports.isFunction = isFunction; + + /* eslint-enable func-style */ + + /* istanbul ignore next */ + var isArray = Array.isArray || function (value) { + return value && typeof value === 'object' ? toString.call(value) === '[object Array]' : false; + }; + + exports.isArray = isArray; + // Older IE versions do not directly support indexOf so we must implement our own, sadly. + + function indexOf(array, value) { + for (var i = 0, len = array.length; i < len; i++) { + if (array[i] === value) { + return i; + } + } + return -1; + } + + function escapeExpression(string) { + if (typeof string !== 'string') { + // don't escape SafeStrings, since they're already safe + if (string && string.toHTML) { + return string.toHTML(); + } else if (string == null) { + return ''; + } else if (!string) { + return string + ''; + } + + // Force a string conversion as this will be done by the append regardless and + // the regex test will do this transparently behind the scenes, causing issues if + // an object's to string has escaped characters in it. + string = '' + string; + } + + if (!possible.test(string)) { + return string; + } + return string.replace(badChars, escapeChar); + } + + function isEmpty(value) { + if (!value && value !== 0) { + return true; + } else if (isArray(value) && value.length === 0) { + return true; + } else { + return false; + } + } + + function createFrame(object) { + var frame = extend({}, object); + frame._parent = object; + return frame; + } + + function blockParams(params, ids) { + params.path = ids; + return params; + } + + function appendContextPath(contextPath, id) { + return (contextPath ? contextPath + '.' : '') + id; + } + +/***/ }, +/* 6 */ +/***/ function(module, exports) { + + 'use strict'; + + exports.__esModule = true; + + var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; + + function Exception(message, node) { + var loc = node && node.loc, + line = undefined, + column = undefined; + if (loc) { + line = loc.start.line; + column = loc.start.column; + + message += ' - ' + line + ':' + column; + } + + var tmp = Error.prototype.constructor.call(this, message); + + // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. + for (var idx = 0; idx < errorProps.length; idx++) { + this[errorProps[idx]] = tmp[errorProps[idx]]; + } + + /* istanbul ignore else */ + if (Error.captureStackTrace) { + Error.captureStackTrace(this, Exception); + } + + if (loc) { + this.lineNumber = line; + this.column = column; + } + } + + Exception.prototype = new Error(); + + exports['default'] = Exception; + module.exports = exports['default']; + +/***/ }, +/* 7 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var _interopRequireDefault = __webpack_require__(1)['default']; + + exports.__esModule = true; + exports.registerDefaultHelpers = registerDefaultHelpers; + + var _helpersBlockHelperMissing = __webpack_require__(8); + + var _helpersBlockHelperMissing2 = _interopRequireDefault(_helpersBlockHelperMissing); + + var _helpersEach = __webpack_require__(9); + + var _helpersEach2 = _interopRequireDefault(_helpersEach); + + var _helpersHelperMissing = __webpack_require__(10); + + var _helpersHelperMissing2 = _interopRequireDefault(_helpersHelperMissing); + + var _helpersIf = __webpack_require__(11); + + var _helpersIf2 = _interopRequireDefault(_helpersIf); + + var _helpersLog = __webpack_require__(12); + + var _helpersLog2 = _interopRequireDefault(_helpersLog); + + var _helpersLookup = __webpack_require__(13); + + var _helpersLookup2 = _interopRequireDefault(_helpersLookup); + + var _helpersWith = __webpack_require__(14); + + var _helpersWith2 = _interopRequireDefault(_helpersWith); + + function registerDefaultHelpers(instance) { + _helpersBlockHelperMissing2['default'](instance); + _helpersEach2['default'](instance); + _helpersHelperMissing2['default'](instance); + _helpersIf2['default'](instance); + _helpersLog2['default'](instance); + _helpersLookup2['default'](instance); + _helpersWith2['default'](instance); + } + +/***/ }, +/* 8 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + exports.__esModule = true; + + var _utils = __webpack_require__(5); + + exports['default'] = function (instance) { + instance.registerHelper('blockHelperMissing', function (context, options) { + var inverse = options.inverse, + fn = options.fn; + + if (context === true) { + return fn(this); + } else if (context === false || context == null) { + return inverse(this); + } else if (_utils.isArray(context)) { + if (context.length > 0) { + if (options.ids) { + options.ids = [options.name]; + } + + return instance.helpers.each(context, options); + } else { + return inverse(this); + } + } else { + if (options.data && options.ids) { + var data = _utils.createFrame(options.data); + data.contextPath = _utils.appendContextPath(options.data.contextPath, options.name); + options = { data: data }; + } + + return fn(context, options); + } + }); + }; + + module.exports = exports['default']; + +/***/ }, +/* 9 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var _interopRequireDefault = __webpack_require__(1)['default']; + + exports.__esModule = true; + + var _utils = __webpack_require__(5); + + var _exception = __webpack_require__(6); + + var _exception2 = _interopRequireDefault(_exception); + + exports['default'] = function (instance) { + instance.registerHelper('each', function (context, options) { + if (!options) { + throw new _exception2['default']('Must pass iterator to #each'); + } + + var fn = options.fn, + inverse = options.inverse, + i = 0, + ret = '', + data = undefined, + contextPath = undefined; + + if (options.data && options.ids) { + contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]) + '.'; + } + + if (_utils.isFunction(context)) { + context = context.call(this); + } + + if (options.data) { + data = _utils.createFrame(options.data); + } + + function execIteration(field, index, last) { + if (data) { + data.key = field; + data.index = index; + data.first = index === 0; + data.last = !!last; + + if (contextPath) { + data.contextPath = contextPath + field; + } + } + + ret = ret + fn(context[field], { + data: data, + blockParams: _utils.blockParams([context[field], field], [contextPath + field, null]) + }); + } + + if (context && typeof context === 'object') { + if (_utils.isArray(context)) { + for (var j = context.length; i < j; i++) { + if (i in context) { + execIteration(i, i, i === context.length - 1); + } + } + } else { + var priorKey = undefined; + + for (var key in context) { + if (context.hasOwnProperty(key)) { + // We're running the iterations one step out of sync so we can detect + // the last iteration without have to scan the object twice and create + // an itermediate keys array. + if (priorKey !== undefined) { + execIteration(priorKey, i - 1); + } + priorKey = key; + i++; + } + } + if (priorKey !== undefined) { + execIteration(priorKey, i - 1, true); + } + } + } + + if (i === 0) { + ret = inverse(this); + } + + return ret; + }); + }; + + module.exports = exports['default']; + +/***/ }, +/* 10 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var _interopRequireDefault = __webpack_require__(1)['default']; + + exports.__esModule = true; + + var _exception = __webpack_require__(6); + + var _exception2 = _interopRequireDefault(_exception); + + exports['default'] = function (instance) { + instance.registerHelper('helperMissing', function () /* [args, ]options */{ + if (arguments.length === 1) { + // A missing field in a {{foo}} construct. + return undefined; + } else { + // Someone is actually trying to call something, blow up. + throw new _exception2['default']('Missing helper: "' + arguments[arguments.length - 1].name + '"'); + } + }); + }; + + module.exports = exports['default']; + +/***/ }, +/* 11 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + exports.__esModule = true; + + var _utils = __webpack_require__(5); + + exports['default'] = function (instance) { + instance.registerHelper('if', function (conditional, options) { + if (_utils.isFunction(conditional)) { + conditional = conditional.call(this); + } + + // Default behavior is to render the positive path if the value is truthy and not empty. + // The `includeZero` option may be set to treat the condtional as purely not empty based on the + // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative. + if (!options.hash.includeZero && !conditional || _utils.isEmpty(conditional)) { + return options.inverse(this); + } else { + return options.fn(this); + } + }); + + instance.registerHelper('unless', function (conditional, options) { + return instance.helpers['if'].call(this, conditional, { fn: options.inverse, inverse: options.fn, hash: options.hash }); + }); + }; + + module.exports = exports['default']; + +/***/ }, +/* 12 */ +/***/ function(module, exports) { + + 'use strict'; + + exports.__esModule = true; + + exports['default'] = function (instance) { + instance.registerHelper('log', function () /* message, options */{ + var args = [undefined], + options = arguments[arguments.length - 1]; + for (var i = 0; i < arguments.length - 1; i++) { + args.push(arguments[i]); + } + + var level = 1; + if (options.hash.level != null) { + level = options.hash.level; + } else if (options.data && options.data.level != null) { + level = options.data.level; + } + args[0] = level; + + instance.log.apply(instance, args); + }); + }; + + module.exports = exports['default']; + +/***/ }, +/* 13 */ +/***/ function(module, exports) { + + 'use strict'; + + exports.__esModule = true; + + exports['default'] = function (instance) { + instance.registerHelper('lookup', function (obj, field) { + return obj && obj[field]; + }); + }; + + module.exports = exports['default']; + +/***/ }, +/* 14 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + exports.__esModule = true; + + var _utils = __webpack_require__(5); + + exports['default'] = function (instance) { + instance.registerHelper('with', function (context, options) { + if (_utils.isFunction(context)) { + context = context.call(this); + } + + var fn = options.fn; + + if (!_utils.isEmpty(context)) { + var data = options.data; + if (options.data && options.ids) { + data = _utils.createFrame(options.data); + data.contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]); + } + + return fn(context, { + data: data, + blockParams: _utils.blockParams([context], [data && data.contextPath]) + }); + } else { + return options.inverse(this); + } + }); + }; + + module.exports = exports['default']; + +/***/ }, +/* 15 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var _interopRequireDefault = __webpack_require__(1)['default']; + + exports.__esModule = true; + exports.registerDefaultDecorators = registerDefaultDecorators; + + var _decoratorsInline = __webpack_require__(16); + + var _decoratorsInline2 = _interopRequireDefault(_decoratorsInline); + + function registerDefaultDecorators(instance) { + _decoratorsInline2['default'](instance); + } + +/***/ }, +/* 16 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + exports.__esModule = true; + + var _utils = __webpack_require__(5); + + exports['default'] = function (instance) { + instance.registerDecorator('inline', function (fn, props, container, options) { + var ret = fn; + if (!props.partials) { + props.partials = {}; + ret = function (context, options) { + // Create a new partials stack frame prior to exec. + var original = container.partials; + container.partials = _utils.extend({}, original, props.partials); + var ret = fn(context, options); + container.partials = original; + return ret; + }; + } + + props.partials[options.args[0]] = options.fn; + + return ret; + }); + }; + + module.exports = exports['default']; + +/***/ }, +/* 17 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + exports.__esModule = true; + + var _utils = __webpack_require__(5); + + var logger = { + methodMap: ['debug', 'info', 'warn', 'error'], + level: 'info', + + // Maps a given level value to the `methodMap` indexes above. + lookupLevel: function lookupLevel(level) { + if (typeof level === 'string') { + var levelMap = _utils.indexOf(logger.methodMap, level.toLowerCase()); + if (levelMap >= 0) { + level = levelMap; + } else { + level = parseInt(level, 10); + } + } + + return level; + }, + + // Can be overridden in the host environment + log: function log(level) { + level = logger.lookupLevel(level); + + if (typeof console !== 'undefined' && logger.lookupLevel(logger.level) <= level) { + var method = logger.methodMap[level]; + if (!console[method]) { + // eslint-disable-line no-console + method = 'log'; + } + + for (var _len = arguments.length, message = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + message[_key - 1] = arguments[_key]; + } + + console[method].apply(console, message); // eslint-disable-line no-console + } + } + }; + + exports['default'] = logger; + module.exports = exports['default']; + +/***/ }, +/* 18 */ +/***/ function(module, exports) { + + // Build out our basic SafeString type + 'use strict'; + + exports.__esModule = true; + function SafeString(string) { + this.string = string; + } + + SafeString.prototype.toString = SafeString.prototype.toHTML = function () { + return '' + this.string; + }; + + exports['default'] = SafeString; + module.exports = exports['default']; + +/***/ }, +/* 19 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var _interopRequireWildcard = __webpack_require__(3)['default']; + + var _interopRequireDefault = __webpack_require__(1)['default']; + + exports.__esModule = true; + exports.checkRevision = checkRevision; + exports.template = template; + exports.wrapProgram = wrapProgram; + exports.resolvePartial = resolvePartial; + exports.invokePartial = invokePartial; + exports.noop = noop; + + var _utils = __webpack_require__(5); + + var Utils = _interopRequireWildcard(_utils); + + var _exception = __webpack_require__(6); + + var _exception2 = _interopRequireDefault(_exception); + + var _base = __webpack_require__(4); + + function checkRevision(compilerInfo) { + var compilerRevision = compilerInfo && compilerInfo[0] || 1, + currentRevision = _base.COMPILER_REVISION; + + if (compilerRevision !== currentRevision) { + if (compilerRevision < currentRevision) { + var runtimeVersions = _base.REVISION_CHANGES[currentRevision], + compilerVersions = _base.REVISION_CHANGES[compilerRevision]; + throw new _exception2['default']('Template was precompiled with an older version of Handlebars than the current runtime. ' + 'Please update your precompiler to a newer version (' + runtimeVersions + ') or downgrade your runtime to an older version (' + compilerVersions + ').'); + } else { + // Use the embedded version info since the runtime doesn't know about this revision yet + throw new _exception2['default']('Template was precompiled with a newer version of Handlebars than the current runtime. ' + 'Please update your runtime to a newer version (' + compilerInfo[1] + ').'); + } + } + } + + function template(templateSpec, env) { + /* istanbul ignore next */ + if (!env) { + throw new _exception2['default']('No environment passed to template'); + } + if (!templateSpec || !templateSpec.main) { + throw new _exception2['default']('Unknown template object: ' + typeof templateSpec); + } + + templateSpec.main.decorator = templateSpec.main_d; + + // Note: Using env.VM references rather than local var references throughout this section to allow + // for external users to override these as psuedo-supported APIs. + env.VM.checkRevision(templateSpec.compiler); + + function invokePartialWrapper(partial, context, options) { + if (options.hash) { + context = Utils.extend({}, context, options.hash); + if (options.ids) { + options.ids[0] = true; + } + } + + partial = env.VM.resolvePartial.call(this, partial, context, options); + var result = env.VM.invokePartial.call(this, partial, context, options); + + if (result == null && env.compile) { + options.partials[options.name] = env.compile(partial, templateSpec.compilerOptions, env); + result = options.partials[options.name](context, options); + } + if (result != null) { + if (options.indent) { + var lines = result.split('\n'); + for (var i = 0, l = lines.length; i < l; i++) { + if (!lines[i] && i + 1 === l) { + break; + } + + lines[i] = options.indent + lines[i]; + } + result = lines.join('\n'); + } + return result; + } else { + throw new _exception2['default']('The partial ' + options.name + ' could not be compiled when running in runtime-only mode'); + } + } + + // Just add water + var container = { + strict: function strict(obj, name) { + if (!(name in obj)) { + throw new _exception2['default']('"' + name + '" not defined in ' + obj); + } + return obj[name]; + }, + lookup: function lookup(depths, name) { + var len = depths.length; + for (var i = 0; i < len; i++) { + if (depths[i] && depths[i][name] != null) { + return depths[i][name]; + } + } + }, + lambda: function lambda(current, context) { + return typeof current === 'function' ? current.call(context) : current; + }, + + escapeExpression: Utils.escapeExpression, + invokePartial: invokePartialWrapper, + + fn: function fn(i) { + var ret = templateSpec[i]; + ret.decorator = templateSpec[i + '_d']; + return ret; + }, + + programs: [], + program: function program(i, data, declaredBlockParams, blockParams, depths) { + var programWrapper = this.programs[i], + fn = this.fn(i); + if (data || depths || blockParams || declaredBlockParams) { + programWrapper = wrapProgram(this, i, fn, data, declaredBlockParams, blockParams, depths); + } else if (!programWrapper) { + programWrapper = this.programs[i] = wrapProgram(this, i, fn); + } + return programWrapper; + }, + + data: function data(value, depth) { + while (value && depth--) { + value = value._parent; + } + return value; + }, + merge: function merge(param, common) { + var obj = param || common; + + if (param && common && param !== common) { + obj = Utils.extend({}, common, param); + } + + return obj; + }, + + noop: env.VM.noop, + compilerInfo: templateSpec.compiler + }; + + function ret(context) { + var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + + var data = options.data; + + ret._setup(options); + if (!options.partial && templateSpec.useData) { + data = initData(context, data); + } + var depths = undefined, + blockParams = templateSpec.useBlockParams ? [] : undefined; + if (templateSpec.useDepths) { + if (options.depths) { + depths = context !== options.depths[0] ? [context].concat(options.depths) : options.depths; + } else { + depths = [context]; + } + } + + function main(context /*, options*/) { + return '' + templateSpec.main(container, context, container.helpers, container.partials, data, blockParams, depths); + } + main = executeDecorators(templateSpec.main, main, container, options.depths || [], data, blockParams); + return main(context, options); + } + ret.isTop = true; + + ret._setup = function (options) { + if (!options.partial) { + container.helpers = container.merge(options.helpers, env.helpers); + + if (templateSpec.usePartial) { + container.partials = container.merge(options.partials, env.partials); + } + if (templateSpec.usePartial || templateSpec.useDecorators) { + container.decorators = container.merge(options.decorators, env.decorators); + } + } else { + container.helpers = options.helpers; + container.partials = options.partials; + container.decorators = options.decorators; + } + }; + + ret._child = function (i, data, blockParams, depths) { + if (templateSpec.useBlockParams && !blockParams) { + throw new _exception2['default']('must pass block params'); + } + if (templateSpec.useDepths && !depths) { + throw new _exception2['default']('must pass parent depths'); + } + + return wrapProgram(container, i, templateSpec[i], data, 0, blockParams, depths); + }; + return ret; + } + + function wrapProgram(container, i, fn, data, declaredBlockParams, blockParams, depths) { + function prog(context) { + var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + + var currentDepths = depths; + if (depths && context !== depths[0]) { + currentDepths = [context].concat(depths); + } + + return fn(container, context, container.helpers, container.partials, options.data || data, blockParams && [options.blockParams].concat(blockParams), currentDepths); + } + + prog = executeDecorators(fn, prog, container, depths, data, blockParams); + + prog.program = i; + prog.depth = depths ? depths.length : 0; + prog.blockParams = declaredBlockParams || 0; + return prog; + } + + function resolvePartial(partial, context, options) { + if (!partial) { + if (options.name === '@partial-block') { + partial = options.data['partial-block']; + } else { + partial = options.partials[options.name]; + } + } else if (!partial.call && !options.name) { + // This is a dynamic partial that returned a string + options.name = partial; + partial = options.partials[partial]; + } + return partial; + } + + function invokePartial(partial, context, options) { + options.partial = true; + if (options.ids) { + options.data.contextPath = options.ids[0] || options.data.contextPath; + } + + var partialBlock = undefined; + if (options.fn && options.fn !== noop) { + options.data = _base.createFrame(options.data); + partialBlock = options.data['partial-block'] = options.fn; + + if (partialBlock.partials) { + options.partials = Utils.extend({}, options.partials, partialBlock.partials); + } + } + + if (partial === undefined && partialBlock) { + partial = partialBlock; + } + + if (partial === undefined) { + throw new _exception2['default']('The partial ' + options.name + ' could not be found'); + } else if (partial instanceof Function) { + return partial(context, options); + } + } + + function noop() { + return ''; + } + + function initData(context, data) { + if (!data || !('root' in data)) { + data = data ? _base.createFrame(data) : {}; + data.root = context; + } + return data; + } + + function executeDecorators(fn, prog, container, depths, data, blockParams) { + if (fn.decorator) { + var props = {}; + prog = fn.decorator(prog, props, container, depths && depths[0], data, blockParams, depths); + Utils.extend(prog, props); + } + return prog; + } + +/***/ }, +/* 20 */ +/***/ function(module, exports) { + + /* WEBPACK VAR INJECTION */(function(global) {/* global window */ + 'use strict'; + + exports.__esModule = true; + + exports['default'] = function (Handlebars) { + /* istanbul ignore next */ + var root = typeof global !== 'undefined' ? global : window, + $Handlebars = root.Handlebars; + /* istanbul ignore next */ + Handlebars.noConflict = function () { + if (root.Handlebars === Handlebars) { + root.Handlebars = $Handlebars; + } + return Handlebars; + }; + }; + + module.exports = exports['default']; + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }, +/* 21 */ +/***/ function(module, exports) { + + 'use strict'; + + exports.__esModule = true; + var AST = { + // Public API used to evaluate derived attributes regarding AST nodes + helpers: { + // a mustache is definitely a helper if: + // * it is an eligible helper, and + // * it has at least one parameter or hash segment + helperExpression: function helperExpression(node) { + return node.type === 'SubExpression' || (node.type === 'MustacheStatement' || node.type === 'BlockStatement') && !!(node.params && node.params.length || node.hash); + }, + + scopedId: function scopedId(path) { + return (/^\.|this\b/.test(path.original) + ); + }, + + // an ID is simple if it only has one part, and that part is not + // `..` or `this`. + simpleId: function simpleId(path) { + return path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth; + } + } + }; + + // Must be exported as an object rather than the root of the module as the jison lexer + // must modify the object to operate properly. + exports['default'] = AST; + module.exports = exports['default']; + +/***/ }, +/* 22 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var _interopRequireDefault = __webpack_require__(1)['default']; + + var _interopRequireWildcard = __webpack_require__(3)['default']; + + exports.__esModule = true; + exports.parse = parse; + + var _parser = __webpack_require__(23); + + var _parser2 = _interopRequireDefault(_parser); + + var _whitespaceControl = __webpack_require__(24); + + var _whitespaceControl2 = _interopRequireDefault(_whitespaceControl); + + var _helpers = __webpack_require__(26); + + var Helpers = _interopRequireWildcard(_helpers); + + var _utils = __webpack_require__(5); + + exports.parser = _parser2['default']; + + var yy = {}; + _utils.extend(yy, Helpers); + + function parse(input, options) { + // Just return if an already-compiled AST was passed in. + if (input.type === 'Program') { + return input; + } + + _parser2['default'].yy = yy; + + // Altering the shared object here, but this is ok as parser is a sync operation + yy.locInfo = function (locInfo) { + return new yy.SourceLocation(options && options.srcName, locInfo); + }; + + var strip = new _whitespaceControl2['default'](options); + return strip.accept(_parser2['default'].parse(input)); + } + +/***/ }, +/* 23 */ +/***/ function(module, exports) { + + /* istanbul ignore next */ + /* Jison generated parser */ + "use strict"; + + var handlebars = (function () { + var parser = { trace: function trace() {}, + yy: {}, + symbols_: { "error": 2, "root": 3, "program": 4, "EOF": 5, "program_repetition0": 6, "statement": 7, "mustache": 8, "block": 9, "rawBlock": 10, "partial": 11, "partialBlock": 12, "content": 13, "COMMENT": 14, "CONTENT": 15, "openRawBlock": 16, "rawBlock_repetition_plus0": 17, "END_RAW_BLOCK": 18, "OPEN_RAW_BLOCK": 19, "helperName": 20, "openRawBlock_repetition0": 21, "openRawBlock_option0": 22, "CLOSE_RAW_BLOCK": 23, "openBlock": 24, "block_option0": 25, "closeBlock": 26, "openInverse": 27, "block_option1": 28, "OPEN_BLOCK": 29, "openBlock_repetition0": 30, "openBlock_option0": 31, "openBlock_option1": 32, "CLOSE": 33, "OPEN_INVERSE": 34, "openInverse_repetition0": 35, "openInverse_option0": 36, "openInverse_option1": 37, "openInverseChain": 38, "OPEN_INVERSE_CHAIN": 39, "openInverseChain_repetition0": 40, "openInverseChain_option0": 41, "openInverseChain_option1": 42, "inverseAndProgram": 43, "INVERSE": 44, "inverseChain": 45, "inverseChain_option0": 46, "OPEN_ENDBLOCK": 47, "OPEN": 48, "mustache_repetition0": 49, "mustache_option0": 50, "OPEN_UNESCAPED": 51, "mustache_repetition1": 52, "mustache_option1": 53, "CLOSE_UNESCAPED": 54, "OPEN_PARTIAL": 55, "partialName": 56, "partial_repetition0": 57, "partial_option0": 58, "openPartialBlock": 59, "OPEN_PARTIAL_BLOCK": 60, "openPartialBlock_repetition0": 61, "openPartialBlock_option0": 62, "param": 63, "sexpr": 64, "OPEN_SEXPR": 65, "sexpr_repetition0": 66, "sexpr_option0": 67, "CLOSE_SEXPR": 68, "hash": 69, "hash_repetition_plus0": 70, "hashSegment": 71, "ID": 72, "EQUALS": 73, "blockParams": 74, "OPEN_BLOCK_PARAMS": 75, "blockParams_repetition_plus0": 76, "CLOSE_BLOCK_PARAMS": 77, "path": 78, "dataName": 79, "STRING": 80, "NUMBER": 81, "BOOLEAN": 82, "UNDEFINED": 83, "NULL": 84, "DATA": 85, "pathSegments": 86, "SEP": 87, "$accept": 0, "$end": 1 }, + terminals_: { 2: "error", 5: "EOF", 14: "COMMENT", 15: "CONTENT", 18: "END_RAW_BLOCK", 19: "OPEN_RAW_BLOCK", 23: "CLOSE_RAW_BLOCK", 29: "OPEN_BLOCK", 33: "CLOSE", 34: "OPEN_INVERSE", 39: "OPEN_INVERSE_CHAIN", 44: "INVERSE", 47: "OPEN_ENDBLOCK", 48: "OPEN", 51: "OPEN_UNESCAPED", 54: "CLOSE_UNESCAPED", 55: "OPEN_PARTIAL", 60: "OPEN_PARTIAL_BLOCK", 65: "OPEN_SEXPR", 68: "CLOSE_SEXPR", 72: "ID", 73: "EQUALS", 75: "OPEN_BLOCK_PARAMS", 77: "CLOSE_BLOCK_PARAMS", 80: "STRING", 81: "NUMBER", 82: "BOOLEAN", 83: "UNDEFINED", 84: "NULL", 85: "DATA", 87: "SEP" }, + productions_: [0, [3, 2], [4, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [13, 1], [10, 3], [16, 5], [9, 4], [9, 4], [24, 6], [27, 6], [38, 6], [43, 2], [45, 3], [45, 1], [26, 3], [8, 5], [8, 5], [11, 5], [12, 3], [59, 5], [63, 1], [63, 1], [64, 5], [69, 1], [71, 3], [74, 3], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [56, 1], [56, 1], [79, 2], [78, 1], [86, 3], [86, 1], [6, 0], [6, 2], [17, 1], [17, 2], [21, 0], [21, 2], [22, 0], [22, 1], [25, 0], [25, 1], [28, 0], [28, 1], [30, 0], [30, 2], [31, 0], [31, 1], [32, 0], [32, 1], [35, 0], [35, 2], [36, 0], [36, 1], [37, 0], [37, 1], [40, 0], [40, 2], [41, 0], [41, 1], [42, 0], [42, 1], [46, 0], [46, 1], [49, 0], [49, 2], [50, 0], [50, 1], [52, 0], [52, 2], [53, 0], [53, 1], [57, 0], [57, 2], [58, 0], [58, 1], [61, 0], [61, 2], [62, 0], [62, 1], [66, 0], [66, 2], [67, 0], [67, 1], [70, 1], [70, 2], [76, 1], [76, 2]], + performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$ + /**/) { + + var $0 = $$.length - 1; + switch (yystate) { + case 1: + return $$[$0 - 1]; + break; + case 2: + this.$ = yy.prepareProgram($$[$0]); + break; + case 3: + this.$ = $$[$0]; + break; + case 4: + this.$ = $$[$0]; + break; + case 5: + this.$ = $$[$0]; + break; + case 6: + this.$ = $$[$0]; + break; + case 7: + this.$ = $$[$0]; + break; + case 8: + this.$ = $$[$0]; + break; + case 9: + this.$ = { + type: 'CommentStatement', + value: yy.stripComment($$[$0]), + strip: yy.stripFlags($$[$0], $$[$0]), + loc: yy.locInfo(this._$) + }; + + break; + case 10: + this.$ = { + type: 'ContentStatement', + original: $$[$0], + value: $$[$0], + loc: yy.locInfo(this._$) + }; + + break; + case 11: + this.$ = yy.prepareRawBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$); + break; + case 12: + this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1] }; + break; + case 13: + this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], false, this._$); + break; + case 14: + this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], true, this._$); + break; + case 15: + this.$ = { open: $$[$0 - 5], path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) }; + break; + case 16: + this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) }; + break; + case 17: + this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) }; + break; + case 18: + this.$ = { strip: yy.stripFlags($$[$0 - 1], $$[$0 - 1]), program: $$[$0] }; + break; + case 19: + var inverse = yy.prepareBlock($$[$0 - 2], $$[$0 - 1], $$[$0], $$[$0], false, this._$), + program = yy.prepareProgram([inverse], $$[$0 - 1].loc); + program.chained = true; + + this.$ = { strip: $$[$0 - 2].strip, program: program, chain: true }; + + break; + case 20: + this.$ = $$[$0]; + break; + case 21: + this.$ = { path: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 2], $$[$0]) }; + break; + case 22: + this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$); + break; + case 23: + this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$); + break; + case 24: + this.$ = { + type: 'PartialStatement', + name: $$[$0 - 3], + params: $$[$0 - 2], + hash: $$[$0 - 1], + indent: '', + strip: yy.stripFlags($$[$0 - 4], $$[$0]), + loc: yy.locInfo(this._$) + }; + + break; + case 25: + this.$ = yy.preparePartialBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$); + break; + case 26: + this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 4], $$[$0]) }; + break; + case 27: + this.$ = $$[$0]; + break; + case 28: + this.$ = $$[$0]; + break; + case 29: + this.$ = { + type: 'SubExpression', + path: $$[$0 - 3], + params: $$[$0 - 2], + hash: $$[$0 - 1], + loc: yy.locInfo(this._$) + }; + + break; + case 30: + this.$ = { type: 'Hash', pairs: $$[$0], loc: yy.locInfo(this._$) }; + break; + case 31: + this.$ = { type: 'HashPair', key: yy.id($$[$0 - 2]), value: $$[$0], loc: yy.locInfo(this._$) }; + break; + case 32: + this.$ = yy.id($$[$0 - 1]); + break; + case 33: + this.$ = $$[$0]; + break; + case 34: + this.$ = $$[$0]; + break; + case 35: + this.$ = { type: 'StringLiteral', value: $$[$0], original: $$[$0], loc: yy.locInfo(this._$) }; + break; + case 36: + this.$ = { type: 'NumberLiteral', value: Number($$[$0]), original: Number($$[$0]), loc: yy.locInfo(this._$) }; + break; + case 37: + this.$ = { type: 'BooleanLiteral', value: $$[$0] === 'true', original: $$[$0] === 'true', loc: yy.locInfo(this._$) }; + break; + case 38: + this.$ = { type: 'UndefinedLiteral', original: undefined, value: undefined, loc: yy.locInfo(this._$) }; + break; + case 39: + this.$ = { type: 'NullLiteral', original: null, value: null, loc: yy.locInfo(this._$) }; + break; + case 40: + this.$ = $$[$0]; + break; + case 41: + this.$ = $$[$0]; + break; + case 42: + this.$ = yy.preparePath(true, $$[$0], this._$); + break; + case 43: + this.$ = yy.preparePath(false, $$[$0], this._$); + break; + case 44: + $$[$0 - 2].push({ part: yy.id($$[$0]), original: $$[$0], separator: $$[$0 - 1] });this.$ = $$[$0 - 2]; + break; + case 45: + this.$ = [{ part: yy.id($$[$0]), original: $$[$0] }]; + break; + case 46: + this.$ = []; + break; + case 47: + $$[$0 - 1].push($$[$0]); + break; + case 48: + this.$ = [$$[$0]]; + break; + case 49: + $$[$0 - 1].push($$[$0]); + break; + case 50: + this.$ = []; + break; + case 51: + $$[$0 - 1].push($$[$0]); + break; + case 58: + this.$ = []; + break; + case 59: + $$[$0 - 1].push($$[$0]); + break; + case 64: + this.$ = []; + break; + case 65: + $$[$0 - 1].push($$[$0]); + break; + case 70: + this.$ = []; + break; + case 71: + $$[$0 - 1].push($$[$0]); + break; + case 78: + this.$ = []; + break; + case 79: + $$[$0 - 1].push($$[$0]); + break; + case 82: + this.$ = []; + break; + case 83: + $$[$0 - 1].push($$[$0]); + break; + case 86: + this.$ = []; + break; + case 87: + $$[$0 - 1].push($$[$0]); + break; + case 90: + this.$ = []; + break; + case 91: + $$[$0 - 1].push($$[$0]); + break; + case 94: + this.$ = []; + break; + case 95: + $$[$0 - 1].push($$[$0]); + break; + case 98: + this.$ = [$$[$0]]; + break; + case 99: + $$[$0 - 1].push($$[$0]); + break; + case 100: + this.$ = [$$[$0]]; + break; + case 101: + $$[$0 - 1].push($$[$0]); + break; + } + }, + table: [{ 3: 1, 4: 2, 5: [2, 46], 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 1: [3] }, { 5: [1, 4] }, { 5: [2, 2], 7: 5, 8: 6, 9: 7, 10: 8, 11: 9, 12: 10, 13: 11, 14: [1, 12], 15: [1, 20], 16: 17, 19: [1, 23], 24: 15, 27: 16, 29: [1, 21], 34: [1, 22], 39: [2, 2], 44: [2, 2], 47: [2, 2], 48: [1, 13], 51: [1, 14], 55: [1, 18], 59: 19, 60: [1, 24] }, { 1: [2, 1] }, { 5: [2, 47], 14: [2, 47], 15: [2, 47], 19: [2, 47], 29: [2, 47], 34: [2, 47], 39: [2, 47], 44: [2, 47], 47: [2, 47], 48: [2, 47], 51: [2, 47], 55: [2, 47], 60: [2, 47] }, { 5: [2, 3], 14: [2, 3], 15: [2, 3], 19: [2, 3], 29: [2, 3], 34: [2, 3], 39: [2, 3], 44: [2, 3], 47: [2, 3], 48: [2, 3], 51: [2, 3], 55: [2, 3], 60: [2, 3] }, { 5: [2, 4], 14: [2, 4], 15: [2, 4], 19: [2, 4], 29: [2, 4], 34: [2, 4], 39: [2, 4], 44: [2, 4], 47: [2, 4], 48: [2, 4], 51: [2, 4], 55: [2, 4], 60: [2, 4] }, { 5: [2, 5], 14: [2, 5], 15: [2, 5], 19: [2, 5], 29: [2, 5], 34: [2, 5], 39: [2, 5], 44: [2, 5], 47: [2, 5], 48: [2, 5], 51: [2, 5], 55: [2, 5], 60: [2, 5] }, { 5: [2, 6], 14: [2, 6], 15: [2, 6], 19: [2, 6], 29: [2, 6], 34: [2, 6], 39: [2, 6], 44: [2, 6], 47: [2, 6], 48: [2, 6], 51: [2, 6], 55: [2, 6], 60: [2, 6] }, { 5: [2, 7], 14: [2, 7], 15: [2, 7], 19: [2, 7], 29: [2, 7], 34: [2, 7], 39: [2, 7], 44: [2, 7], 47: [2, 7], 48: [2, 7], 51: [2, 7], 55: [2, 7], 60: [2, 7] }, { 5: [2, 8], 14: [2, 8], 15: [2, 8], 19: [2, 8], 29: [2, 8], 34: [2, 8], 39: [2, 8], 44: [2, 8], 47: [2, 8], 48: [2, 8], 51: [2, 8], 55: [2, 8], 60: [2, 8] }, { 5: [2, 9], 14: [2, 9], 15: [2, 9], 19: [2, 9], 29: [2, 9], 34: [2, 9], 39: [2, 9], 44: [2, 9], 47: [2, 9], 48: [2, 9], 51: [2, 9], 55: [2, 9], 60: [2, 9] }, { 20: 25, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 36, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 37, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 4: 38, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 13: 40, 15: [1, 20], 17: 39 }, { 20: 42, 56: 41, 64: 43, 65: [1, 44], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 45, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 5: [2, 10], 14: [2, 10], 15: [2, 10], 18: [2, 10], 19: [2, 10], 29: [2, 10], 34: [2, 10], 39: [2, 10], 44: [2, 10], 47: [2, 10], 48: [2, 10], 51: [2, 10], 55: [2, 10], 60: [2, 10] }, { 20: 46, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 47, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 48, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 42, 56: 49, 64: 43, 65: [1, 44], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [2, 78], 49: 50, 65: [2, 78], 72: [2, 78], 80: [2, 78], 81: [2, 78], 82: [2, 78], 83: [2, 78], 84: [2, 78], 85: [2, 78] }, { 23: [2, 33], 33: [2, 33], 54: [2, 33], 65: [2, 33], 68: [2, 33], 72: [2, 33], 75: [2, 33], 80: [2, 33], 81: [2, 33], 82: [2, 33], 83: [2, 33], 84: [2, 33], 85: [2, 33] }, { 23: [2, 34], 33: [2, 34], 54: [2, 34], 65: [2, 34], 68: [2, 34], 72: [2, 34], 75: [2, 34], 80: [2, 34], 81: [2, 34], 82: [2, 34], 83: [2, 34], 84: [2, 34], 85: [2, 34] }, { 23: [2, 35], 33: [2, 35], 54: [2, 35], 65: [2, 35], 68: [2, 35], 72: [2, 35], 75: [2, 35], 80: [2, 35], 81: [2, 35], 82: [2, 35], 83: [2, 35], 84: [2, 35], 85: [2, 35] }, { 23: [2, 36], 33: [2, 36], 54: [2, 36], 65: [2, 36], 68: [2, 36], 72: [2, 36], 75: [2, 36], 80: [2, 36], 81: [2, 36], 82: [2, 36], 83: [2, 36], 84: [2, 36], 85: [2, 36] }, { 23: [2, 37], 33: [2, 37], 54: [2, 37], 65: [2, 37], 68: [2, 37], 72: [2, 37], 75: [2, 37], 80: [2, 37], 81: [2, 37], 82: [2, 37], 83: [2, 37], 84: [2, 37], 85: [2, 37] }, { 23: [2, 38], 33: [2, 38], 54: [2, 38], 65: [2, 38], 68: [2, 38], 72: [2, 38], 75: [2, 38], 80: [2, 38], 81: [2, 38], 82: [2, 38], 83: [2, 38], 84: [2, 38], 85: [2, 38] }, { 23: [2, 39], 33: [2, 39], 54: [2, 39], 65: [2, 39], 68: [2, 39], 72: [2, 39], 75: [2, 39], 80: [2, 39], 81: [2, 39], 82: [2, 39], 83: [2, 39], 84: [2, 39], 85: [2, 39] }, { 23: [2, 43], 33: [2, 43], 54: [2, 43], 65: [2, 43], 68: [2, 43], 72: [2, 43], 75: [2, 43], 80: [2, 43], 81: [2, 43], 82: [2, 43], 83: [2, 43], 84: [2, 43], 85: [2, 43], 87: [1, 51] }, { 72: [1, 35], 86: 52 }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 52: 53, 54: [2, 82], 65: [2, 82], 72: [2, 82], 80: [2, 82], 81: [2, 82], 82: [2, 82], 83: [2, 82], 84: [2, 82], 85: [2, 82] }, { 25: 54, 38: 56, 39: [1, 58], 43: 57, 44: [1, 59], 45: 55, 47: [2, 54] }, { 28: 60, 43: 61, 44: [1, 59], 47: [2, 56] }, { 13: 63, 15: [1, 20], 18: [1, 62] }, { 15: [2, 48], 18: [2, 48] }, { 33: [2, 86], 57: 64, 65: [2, 86], 72: [2, 86], 80: [2, 86], 81: [2, 86], 82: [2, 86], 83: [2, 86], 84: [2, 86], 85: [2, 86] }, { 33: [2, 40], 65: [2, 40], 72: [2, 40], 80: [2, 40], 81: [2, 40], 82: [2, 40], 83: [2, 40], 84: [2, 40], 85: [2, 40] }, { 33: [2, 41], 65: [2, 41], 72: [2, 41], 80: [2, 41], 81: [2, 41], 82: [2, 41], 83: [2, 41], 84: [2, 41], 85: [2, 41] }, { 20: 65, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 66, 47: [1, 67] }, { 30: 68, 33: [2, 58], 65: [2, 58], 72: [2, 58], 75: [2, 58], 80: [2, 58], 81: [2, 58], 82: [2, 58], 83: [2, 58], 84: [2, 58], 85: [2, 58] }, { 33: [2, 64], 35: 69, 65: [2, 64], 72: [2, 64], 75: [2, 64], 80: [2, 64], 81: [2, 64], 82: [2, 64], 83: [2, 64], 84: [2, 64], 85: [2, 64] }, { 21: 70, 23: [2, 50], 65: [2, 50], 72: [2, 50], 80: [2, 50], 81: [2, 50], 82: [2, 50], 83: [2, 50], 84: [2, 50], 85: [2, 50] }, { 33: [2, 90], 61: 71, 65: [2, 90], 72: [2, 90], 80: [2, 90], 81: [2, 90], 82: [2, 90], 83: [2, 90], 84: [2, 90], 85: [2, 90] }, { 20: 75, 33: [2, 80], 50: 72, 63: 73, 64: 76, 65: [1, 44], 69: 74, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 72: [1, 80] }, { 23: [2, 42], 33: [2, 42], 54: [2, 42], 65: [2, 42], 68: [2, 42], 72: [2, 42], 75: [2, 42], 80: [2, 42], 81: [2, 42], 82: [2, 42], 83: [2, 42], 84: [2, 42], 85: [2, 42], 87: [1, 51] }, { 20: 75, 53: 81, 54: [2, 84], 63: 82, 64: 76, 65: [1, 44], 69: 83, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 84, 47: [1, 67] }, { 47: [2, 55] }, { 4: 85, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 47: [2, 20] }, { 20: 86, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 87, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 26: 88, 47: [1, 67] }, { 47: [2, 57] }, { 5: [2, 11], 14: [2, 11], 15: [2, 11], 19: [2, 11], 29: [2, 11], 34: [2, 11], 39: [2, 11], 44: [2, 11], 47: [2, 11], 48: [2, 11], 51: [2, 11], 55: [2, 11], 60: [2, 11] }, { 15: [2, 49], 18: [2, 49] }, { 20: 75, 33: [2, 88], 58: 89, 63: 90, 64: 76, 65: [1, 44], 69: 91, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 65: [2, 94], 66: 92, 68: [2, 94], 72: [2, 94], 80: [2, 94], 81: [2, 94], 82: [2, 94], 83: [2, 94], 84: [2, 94], 85: [2, 94] }, { 5: [2, 25], 14: [2, 25], 15: [2, 25], 19: [2, 25], 29: [2, 25], 34: [2, 25], 39: [2, 25], 44: [2, 25], 47: [2, 25], 48: [2, 25], 51: [2, 25], 55: [2, 25], 60: [2, 25] }, { 20: 93, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 31: 94, 33: [2, 60], 63: 95, 64: 76, 65: [1, 44], 69: 96, 70: 77, 71: 78, 72: [1, 79], 75: [2, 60], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 33: [2, 66], 36: 97, 63: 98, 64: 76, 65: [1, 44], 69: 99, 70: 77, 71: 78, 72: [1, 79], 75: [2, 66], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 22: 100, 23: [2, 52], 63: 101, 64: 76, 65: [1, 44], 69: 102, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 33: [2, 92], 62: 103, 63: 104, 64: 76, 65: [1, 44], 69: 105, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 106] }, { 33: [2, 79], 65: [2, 79], 72: [2, 79], 80: [2, 79], 81: [2, 79], 82: [2, 79], 83: [2, 79], 84: [2, 79], 85: [2, 79] }, { 33: [2, 81] }, { 23: [2, 27], 33: [2, 27], 54: [2, 27], 65: [2, 27], 68: [2, 27], 72: [2, 27], 75: [2, 27], 80: [2, 27], 81: [2, 27], 82: [2, 27], 83: [2, 27], 84: [2, 27], 85: [2, 27] }, { 23: [2, 28], 33: [2, 28], 54: [2, 28], 65: [2, 28], 68: [2, 28], 72: [2, 28], 75: [2, 28], 80: [2, 28], 81: [2, 28], 82: [2, 28], 83: [2, 28], 84: [2, 28], 85: [2, 28] }, { 23: [2, 30], 33: [2, 30], 54: [2, 30], 68: [2, 30], 71: 107, 72: [1, 108], 75: [2, 30] }, { 23: [2, 98], 33: [2, 98], 54: [2, 98], 68: [2, 98], 72: [2, 98], 75: [2, 98] }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 73: [1, 109], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 23: [2, 44], 33: [2, 44], 54: [2, 44], 65: [2, 44], 68: [2, 44], 72: [2, 44], 75: [2, 44], 80: [2, 44], 81: [2, 44], 82: [2, 44], 83: [2, 44], 84: [2, 44], 85: [2, 44], 87: [2, 44] }, { 54: [1, 110] }, { 54: [2, 83], 65: [2, 83], 72: [2, 83], 80: [2, 83], 81: [2, 83], 82: [2, 83], 83: [2, 83], 84: [2, 83], 85: [2, 83] }, { 54: [2, 85] }, { 5: [2, 13], 14: [2, 13], 15: [2, 13], 19: [2, 13], 29: [2, 13], 34: [2, 13], 39: [2, 13], 44: [2, 13], 47: [2, 13], 48: [2, 13], 51: [2, 13], 55: [2, 13], 60: [2, 13] }, { 38: 56, 39: [1, 58], 43: 57, 44: [1, 59], 45: 112, 46: 111, 47: [2, 76] }, { 33: [2, 70], 40: 113, 65: [2, 70], 72: [2, 70], 75: [2, 70], 80: [2, 70], 81: [2, 70], 82: [2, 70], 83: [2, 70], 84: [2, 70], 85: [2, 70] }, { 47: [2, 18] }, { 5: [2, 14], 14: [2, 14], 15: [2, 14], 19: [2, 14], 29: [2, 14], 34: [2, 14], 39: [2, 14], 44: [2, 14], 47: [2, 14], 48: [2, 14], 51: [2, 14], 55: [2, 14], 60: [2, 14] }, { 33: [1, 114] }, { 33: [2, 87], 65: [2, 87], 72: [2, 87], 80: [2, 87], 81: [2, 87], 82: [2, 87], 83: [2, 87], 84: [2, 87], 85: [2, 87] }, { 33: [2, 89] }, { 20: 75, 63: 116, 64: 76, 65: [1, 44], 67: 115, 68: [2, 96], 69: 117, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 118] }, { 32: 119, 33: [2, 62], 74: 120, 75: [1, 121] }, { 33: [2, 59], 65: [2, 59], 72: [2, 59], 75: [2, 59], 80: [2, 59], 81: [2, 59], 82: [2, 59], 83: [2, 59], 84: [2, 59], 85: [2, 59] }, { 33: [2, 61], 75: [2, 61] }, { 33: [2, 68], 37: 122, 74: 123, 75: [1, 121] }, { 33: [2, 65], 65: [2, 65], 72: [2, 65], 75: [2, 65], 80: [2, 65], 81: [2, 65], 82: [2, 65], 83: [2, 65], 84: [2, 65], 85: [2, 65] }, { 33: [2, 67], 75: [2, 67] }, { 23: [1, 124] }, { 23: [2, 51], 65: [2, 51], 72: [2, 51], 80: [2, 51], 81: [2, 51], 82: [2, 51], 83: [2, 51], 84: [2, 51], 85: [2, 51] }, { 23: [2, 53] }, { 33: [1, 125] }, { 33: [2, 91], 65: [2, 91], 72: [2, 91], 80: [2, 91], 81: [2, 91], 82: [2, 91], 83: [2, 91], 84: [2, 91], 85: [2, 91] }, { 33: [2, 93] }, { 5: [2, 22], 14: [2, 22], 15: [2, 22], 19: [2, 22], 29: [2, 22], 34: [2, 22], 39: [2, 22], 44: [2, 22], 47: [2, 22], 48: [2, 22], 51: [2, 22], 55: [2, 22], 60: [2, 22] }, { 23: [2, 99], 33: [2, 99], 54: [2, 99], 68: [2, 99], 72: [2, 99], 75: [2, 99] }, { 73: [1, 109] }, { 20: 75, 63: 126, 64: 76, 65: [1, 44], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 23], 14: [2, 23], 15: [2, 23], 19: [2, 23], 29: [2, 23], 34: [2, 23], 39: [2, 23], 44: [2, 23], 47: [2, 23], 48: [2, 23], 51: [2, 23], 55: [2, 23], 60: [2, 23] }, { 47: [2, 19] }, { 47: [2, 77] }, { 20: 75, 33: [2, 72], 41: 127, 63: 128, 64: 76, 65: [1, 44], 69: 129, 70: 77, 71: 78, 72: [1, 79], 75: [2, 72], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 24], 14: [2, 24], 15: [2, 24], 19: [2, 24], 29: [2, 24], 34: [2, 24], 39: [2, 24], 44: [2, 24], 47: [2, 24], 48: [2, 24], 51: [2, 24], 55: [2, 24], 60: [2, 24] }, { 68: [1, 130] }, { 65: [2, 95], 68: [2, 95], 72: [2, 95], 80: [2, 95], 81: [2, 95], 82: [2, 95], 83: [2, 95], 84: [2, 95], 85: [2, 95] }, { 68: [2, 97] }, { 5: [2, 21], 14: [2, 21], 15: [2, 21], 19: [2, 21], 29: [2, 21], 34: [2, 21], 39: [2, 21], 44: [2, 21], 47: [2, 21], 48: [2, 21], 51: [2, 21], 55: [2, 21], 60: [2, 21] }, { 33: [1, 131] }, { 33: [2, 63] }, { 72: [1, 133], 76: 132 }, { 33: [1, 134] }, { 33: [2, 69] }, { 15: [2, 12] }, { 14: [2, 26], 15: [2, 26], 19: [2, 26], 29: [2, 26], 34: [2, 26], 47: [2, 26], 48: [2, 26], 51: [2, 26], 55: [2, 26], 60: [2, 26] }, { 23: [2, 31], 33: [2, 31], 54: [2, 31], 68: [2, 31], 72: [2, 31], 75: [2, 31] }, { 33: [2, 74], 42: 135, 74: 136, 75: [1, 121] }, { 33: [2, 71], 65: [2, 71], 72: [2, 71], 75: [2, 71], 80: [2, 71], 81: [2, 71], 82: [2, 71], 83: [2, 71], 84: [2, 71], 85: [2, 71] }, { 33: [2, 73], 75: [2, 73] }, { 23: [2, 29], 33: [2, 29], 54: [2, 29], 65: [2, 29], 68: [2, 29], 72: [2, 29], 75: [2, 29], 80: [2, 29], 81: [2, 29], 82: [2, 29], 83: [2, 29], 84: [2, 29], 85: [2, 29] }, { 14: [2, 15], 15: [2, 15], 19: [2, 15], 29: [2, 15], 34: [2, 15], 39: [2, 15], 44: [2, 15], 47: [2, 15], 48: [2, 15], 51: [2, 15], 55: [2, 15], 60: [2, 15] }, { 72: [1, 138], 77: [1, 137] }, { 72: [2, 100], 77: [2, 100] }, { 14: [2, 16], 15: [2, 16], 19: [2, 16], 29: [2, 16], 34: [2, 16], 44: [2, 16], 47: [2, 16], 48: [2, 16], 51: [2, 16], 55: [2, 16], 60: [2, 16] }, { 33: [1, 139] }, { 33: [2, 75] }, { 33: [2, 32] }, { 72: [2, 101], 77: [2, 101] }, { 14: [2, 17], 15: [2, 17], 19: [2, 17], 29: [2, 17], 34: [2, 17], 39: [2, 17], 44: [2, 17], 47: [2, 17], 48: [2, 17], 51: [2, 17], 55: [2, 17], 60: [2, 17] }], + defaultActions: { 4: [2, 1], 55: [2, 55], 57: [2, 20], 61: [2, 57], 74: [2, 81], 83: [2, 85], 87: [2, 18], 91: [2, 89], 102: [2, 53], 105: [2, 93], 111: [2, 19], 112: [2, 77], 117: [2, 97], 120: [2, 63], 123: [2, 69], 124: [2, 12], 136: [2, 75], 137: [2, 32] }, + parseError: function parseError(str, hash) { + throw new Error(str); + }, + parse: function parse(input) { + var self = this, + stack = [0], + vstack = [null], + lstack = [], + table = this.table, + yytext = "", + yylineno = 0, + yyleng = 0, + recovering = 0, + TERROR = 2, + EOF = 1; + this.lexer.setInput(input); + this.lexer.yy = this.yy; + this.yy.lexer = this.lexer; + this.yy.parser = this; + if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {}; + var yyloc = this.lexer.yylloc; + lstack.push(yyloc); + var ranges = this.lexer.options && this.lexer.options.ranges; + if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError; + function popStack(n) { + stack.length = stack.length - 2 * n; + vstack.length = vstack.length - n; + lstack.length = lstack.length - n; + } + function lex() { + var token; + token = self.lexer.lex() || 1; + if (typeof token !== "number") { + token = self.symbols_[token] || token; + } + return token; + } + var symbol, + preErrorSymbol, + state, + action, + a, + r, + yyval = {}, + p, + len, + newState, + expected; + while (true) { + state = stack[stack.length - 1]; + if (this.defaultActions[state]) { + action = this.defaultActions[state]; + } else { + if (symbol === null || typeof symbol == "undefined") { + symbol = lex(); + } + action = table[state] && table[state][symbol]; + } + if (typeof action === "undefined" || !action.length || !action[0]) { + var errStr = ""; + if (!recovering) { + expected = []; + for (p in table[state]) if (this.terminals_[p] && p > 2) { + expected.push("'" + this.terminals_[p] + "'"); + } + if (this.lexer.showPosition) { + errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'"; + } else { + errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'"); + } + this.parseError(errStr, { text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected }); + } + } + if (action[0] instanceof Array && action.length > 1) { + throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol); + } + switch (action[0]) { + case 1: + stack.push(symbol); + vstack.push(this.lexer.yytext); + lstack.push(this.lexer.yylloc); + stack.push(action[1]); + symbol = null; + if (!preErrorSymbol) { + yyleng = this.lexer.yyleng; + yytext = this.lexer.yytext; + yylineno = this.lexer.yylineno; + yyloc = this.lexer.yylloc; + if (recovering > 0) recovering--; + } else { + symbol = preErrorSymbol; + preErrorSymbol = null; + } + break; + case 2: + len = this.productions_[action[1]][1]; + yyval.$ = vstack[vstack.length - len]; + yyval._$ = { first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column }; + if (ranges) { + yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]]; + } + r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack); + if (typeof r !== "undefined") { + return r; + } + if (len) { + stack = stack.slice(0, -1 * len * 2); + vstack = vstack.slice(0, -1 * len); + lstack = lstack.slice(0, -1 * len); + } + stack.push(this.productions_[action[1]][0]); + vstack.push(yyval.$); + lstack.push(yyval._$); + newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; + stack.push(newState); + break; + case 3: + return true; + } + } + return true; + } + }; + /* Jison generated lexer */ + var lexer = (function () { + var lexer = { EOF: 1, + parseError: function parseError(str, hash) { + if (this.yy.parser) { + this.yy.parser.parseError(str, hash); + } else { + throw new Error(str); + } + }, + setInput: function setInput(input) { + this._input = input; + this._more = this._less = this.done = false; + this.yylineno = this.yyleng = 0; + this.yytext = this.matched = this.match = ''; + this.conditionStack = ['INITIAL']; + this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0 }; + if (this.options.ranges) this.yylloc.range = [0, 0]; + this.offset = 0; + return this; + }, + input: function input() { + var ch = this._input[0]; + this.yytext += ch; + this.yyleng++; + this.offset++; + this.match += ch; + this.matched += ch; + var lines = ch.match(/(?:\r\n?|\n).*/g); + if (lines) { + this.yylineno++; + this.yylloc.last_line++; + } else { + this.yylloc.last_column++; + } + if (this.options.ranges) this.yylloc.range[1]++; + + this._input = this._input.slice(1); + return ch; + }, + unput: function unput(ch) { + var len = ch.length; + var lines = ch.split(/(?:\r\n?|\n)/g); + + this._input = ch + this._input; + this.yytext = this.yytext.substr(0, this.yytext.length - len - 1); + //this.yyleng -= len; + this.offset -= len; + var oldLines = this.match.split(/(?:\r\n?|\n)/g); + this.match = this.match.substr(0, this.match.length - 1); + this.matched = this.matched.substr(0, this.matched.length - 1); + + if (lines.length - 1) this.yylineno -= lines.length - 1; + var r = this.yylloc.range; + + this.yylloc = { first_line: this.yylloc.first_line, + last_line: this.yylineno + 1, + first_column: this.yylloc.first_column, + last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len + }; + + if (this.options.ranges) { + this.yylloc.range = [r[0], r[0] + this.yyleng - len]; + } + return this; + }, + more: function more() { + this._more = true; + return this; + }, + less: function less(n) { + this.unput(this.match.slice(n)); + }, + pastInput: function pastInput() { + var past = this.matched.substr(0, this.matched.length - this.match.length); + return (past.length > 20 ? '...' : '') + past.substr(-20).replace(/\n/g, ""); + }, + upcomingInput: function upcomingInput() { + var next = this.match; + if (next.length < 20) { + next += this._input.substr(0, 20 - next.length); + } + return (next.substr(0, 20) + (next.length > 20 ? '...' : '')).replace(/\n/g, ""); + }, + showPosition: function showPosition() { + var pre = this.pastInput(); + var c = new Array(pre.length + 1).join("-"); + return pre + this.upcomingInput() + "\n" + c + "^"; + }, + next: function next() { + if (this.done) { + return this.EOF; + } + if (!this._input) this.done = true; + + var token, match, tempMatch, index, col, lines; + if (!this._more) { + this.yytext = ''; + this.match = ''; + } + var rules = this._currentRules(); + for (var i = 0; i < rules.length; i++) { + tempMatch = this._input.match(this.rules[rules[i]]); + if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { + match = tempMatch; + index = i; + if (!this.options.flex) break; + } + } + if (match) { + lines = match[0].match(/(?:\r\n?|\n).*/g); + if (lines) this.yylineno += lines.length; + this.yylloc = { first_line: this.yylloc.last_line, + last_line: this.yylineno + 1, + first_column: this.yylloc.last_column, + last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length }; + this.yytext += match[0]; + this.match += match[0]; + this.matches = match; + this.yyleng = this.yytext.length; + if (this.options.ranges) { + this.yylloc.range = [this.offset, this.offset += this.yyleng]; + } + this._more = false; + this._input = this._input.slice(match[0].length); + this.matched += match[0]; + token = this.performAction.call(this, this.yy, this, rules[index], this.conditionStack[this.conditionStack.length - 1]); + if (this.done && this._input) this.done = false; + if (token) return token;else return; + } + if (this._input === "") { + return this.EOF; + } else { + return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { text: "", token: null, line: this.yylineno }); + } + }, + lex: function lex() { + var r = this.next(); + if (typeof r !== 'undefined') { + return r; + } else { + return this.lex(); + } + }, + begin: function begin(condition) { + this.conditionStack.push(condition); + }, + popState: function popState() { + return this.conditionStack.pop(); + }, + _currentRules: function _currentRules() { + return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules; + }, + topState: function topState() { + return this.conditionStack[this.conditionStack.length - 2]; + }, + pushState: function begin(condition) { + this.begin(condition); + } }; + lexer.options = {}; + lexer.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START + /**/) { + + function strip(start, end) { + return yy_.yytext = yy_.yytext.substr(start, yy_.yyleng - end); + } + + var YYSTATE = YY_START; + switch ($avoiding_name_collisions) { + case 0: + if (yy_.yytext.slice(-2) === "\\\\") { + strip(0, 1); + this.begin("mu"); + } else if (yy_.yytext.slice(-1) === "\\") { + strip(0, 1); + this.begin("emu"); + } else { + this.begin("mu"); + } + if (yy_.yytext) return 15; + + break; + case 1: + return 15; + break; + case 2: + this.popState(); + return 15; + + break; + case 3: + this.begin('raw');return 15; + break; + case 4: + this.popState(); + // Should be using `this.topState()` below, but it currently + // returns the second top instead of the first top. Opened an + // issue about it at https://github.com/zaach/jison/issues/291 + if (this.conditionStack[this.conditionStack.length - 1] === 'raw') { + return 15; + } else { + yy_.yytext = yy_.yytext.substr(5, yy_.yyleng - 9); + return 'END_RAW_BLOCK'; + } + + break; + case 5: + return 15; + break; + case 6: + this.popState(); + return 14; + + break; + case 7: + return 65; + break; + case 8: + return 68; + break; + case 9: + return 19; + break; + case 10: + this.popState(); + this.begin('raw'); + return 23; + + break; + case 11: + return 55; + break; + case 12: + return 60; + break; + case 13: + return 29; + break; + case 14: + return 47; + break; + case 15: + this.popState();return 44; + break; + case 16: + this.popState();return 44; + break; + case 17: + return 34; + break; + case 18: + return 39; + break; + case 19: + return 51; + break; + case 20: + return 48; + break; + case 21: + this.unput(yy_.yytext); + this.popState(); + this.begin('com'); + + break; + case 22: + this.popState(); + return 14; + + break; + case 23: + return 48; + break; + case 24: + return 73; + break; + case 25: + return 72; + break; + case 26: + return 72; + break; + case 27: + return 87; + break; + case 28: + // ignore whitespace + break; + case 29: + this.popState();return 54; + break; + case 30: + this.popState();return 33; + break; + case 31: + yy_.yytext = strip(1, 2).replace(/\\"/g, '"');return 80; + break; + case 32: + yy_.yytext = strip(1, 2).replace(/\\'/g, "'");return 80; + break; + case 33: + return 85; + break; + case 34: + return 82; + break; + case 35: + return 82; + break; + case 36: + return 83; + break; + case 37: + return 84; + break; + case 38: + return 81; + break; + case 39: + return 75; + break; + case 40: + return 77; + break; + case 41: + return 72; + break; + case 42: + yy_.yytext = yy_.yytext.replace(/\\([\\\]])/g, '$1');return 72; + break; + case 43: + return 'INVALID'; + break; + case 44: + return 5; + break; + } + }; + lexer.rules = [/^(?:[^\x00]*?(?=(\{\{)))/, /^(?:[^\x00]+)/, /^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/, /^(?:\{\{\{\{(?=[^/]))/, /^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/, /^(?:[^\x00]*?(?=(\{\{\{\{)))/, /^(?:[\s\S]*?--(~)?\}\})/, /^(?:\()/, /^(?:\))/, /^(?:\{\{\{\{)/, /^(?:\}\}\}\})/, /^(?:\{\{(~)?>)/, /^(?:\{\{(~)?#>)/, /^(?:\{\{(~)?#\*?)/, /^(?:\{\{(~)?\/)/, /^(?:\{\{(~)?\^\s*(~)?\}\})/, /^(?:\{\{(~)?\s*else\s*(~)?\}\})/, /^(?:\{\{(~)?\^)/, /^(?:\{\{(~)?\s*else\b)/, /^(?:\{\{(~)?\{)/, /^(?:\{\{(~)?&)/, /^(?:\{\{(~)?!--)/, /^(?:\{\{(~)?![\s\S]*?\}\})/, /^(?:\{\{(~)?\*?)/, /^(?:=)/, /^(?:\.\.)/, /^(?:\.(?=([=~}\s\/.)|])))/, /^(?:[\/.])/, /^(?:\s+)/, /^(?:\}(~)?\}\})/, /^(?:(~)?\}\})/, /^(?:"(\\["]|[^"])*")/, /^(?:'(\\[']|[^'])*')/, /^(?:@)/, /^(?:true(?=([~}\s)])))/, /^(?:false(?=([~}\s)])))/, /^(?:undefined(?=([~}\s)])))/, /^(?:null(?=([~}\s)])))/, /^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/, /^(?:as\s+\|)/, /^(?:\|)/, /^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/, /^(?:\[(\\\]|[^\]])*\])/, /^(?:.)/, /^(?:$)/]; + lexer.conditions = { "mu": { "rules": [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44], "inclusive": false }, "emu": { "rules": [2], "inclusive": false }, "com": { "rules": [6], "inclusive": false }, "raw": { "rules": [3, 4, 5], "inclusive": false }, "INITIAL": { "rules": [0, 1, 44], "inclusive": true } }; + return lexer; + })(); + parser.lexer = lexer; + function Parser() { + this.yy = {}; + }Parser.prototype = parser;parser.Parser = Parser; + return new Parser(); + })();exports.__esModule = true; + exports['default'] = handlebars; + +/***/ }, +/* 24 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var _interopRequireDefault = __webpack_require__(1)['default']; + + exports.__esModule = true; + + var _visitor = __webpack_require__(25); + + var _visitor2 = _interopRequireDefault(_visitor); + + function WhitespaceControl() { + var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; + + this.options = options; + } + WhitespaceControl.prototype = new _visitor2['default'](); + + WhitespaceControl.prototype.Program = function (program) { + var doStandalone = !this.options.ignoreStandalone; + + var isRoot = !this.isRootSeen; + this.isRootSeen = true; + + var body = program.body; + for (var i = 0, l = body.length; i < l; i++) { + var current = body[i], + strip = this.accept(current); + + if (!strip) { + continue; + } + + var _isPrevWhitespace = isPrevWhitespace(body, i, isRoot), + _isNextWhitespace = isNextWhitespace(body, i, isRoot), + openStandalone = strip.openStandalone && _isPrevWhitespace, + closeStandalone = strip.closeStandalone && _isNextWhitespace, + inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace; + + if (strip.close) { + omitRight(body, i, true); + } + if (strip.open) { + omitLeft(body, i, true); + } + + if (doStandalone && inlineStandalone) { + omitRight(body, i); + + if (omitLeft(body, i)) { + // If we are on a standalone node, save the indent info for partials + if (current.type === 'PartialStatement') { + // Pull out the whitespace from the final line + current.indent = /([ \t]+$)/.exec(body[i - 1].original)[1]; + } + } + } + if (doStandalone && openStandalone) { + omitRight((current.program || current.inverse).body); + + // Strip out the previous content node if it's whitespace only + omitLeft(body, i); + } + if (doStandalone && closeStandalone) { + // Always strip the next node + omitRight(body, i); + + omitLeft((current.inverse || current.program).body); + } + } + + return program; + }; + + WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function (block) { + this.accept(block.program); + this.accept(block.inverse); + + // Find the inverse program that is involed with whitespace stripping. + var program = block.program || block.inverse, + inverse = block.program && block.inverse, + firstInverse = inverse, + lastInverse = inverse; + + if (inverse && inverse.chained) { + firstInverse = inverse.body[0].program; + + // Walk the inverse chain to find the last inverse that is actually in the chain. + while (lastInverse.chained) { + lastInverse = lastInverse.body[lastInverse.body.length - 1].program; + } + } + + var strip = { + open: block.openStrip.open, + close: block.closeStrip.close, + + // Determine the standalone candiacy. Basically flag our content as being possibly standalone + // so our parent can determine if we actually are standalone + openStandalone: isNextWhitespace(program.body), + closeStandalone: isPrevWhitespace((firstInverse || program).body) + }; + + if (block.openStrip.close) { + omitRight(program.body, null, true); + } + + if (inverse) { + var inverseStrip = block.inverseStrip; + + if (inverseStrip.open) { + omitLeft(program.body, null, true); + } + + if (inverseStrip.close) { + omitRight(firstInverse.body, null, true); + } + if (block.closeStrip.open) { + omitLeft(lastInverse.body, null, true); + } + + // Find standalone else statments + if (!this.options.ignoreStandalone && isPrevWhitespace(program.body) && isNextWhitespace(firstInverse.body)) { + omitLeft(program.body); + omitRight(firstInverse.body); + } + } else if (block.closeStrip.open) { + omitLeft(program.body, null, true); + } + + return strip; + }; + + WhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function (mustache) { + return mustache.strip; + }; + + WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function (node) { + /* istanbul ignore next */ + var strip = node.strip || {}; + return { + inlineStandalone: true, + open: strip.open, + close: strip.close + }; + }; + + function isPrevWhitespace(body, i, isRoot) { + if (i === undefined) { + i = body.length; + } + + // Nodes that end with newlines are considered whitespace (but are special + // cased for strip operations) + var prev = body[i - 1], + sibling = body[i - 2]; + if (!prev) { + return isRoot; + } + + if (prev.type === 'ContentStatement') { + return (sibling || !isRoot ? /\r?\n\s*?$/ : /(^|\r?\n)\s*?$/).test(prev.original); + } + } + function isNextWhitespace(body, i, isRoot) { + if (i === undefined) { + i = -1; + } + + var next = body[i + 1], + sibling = body[i + 2]; + if (!next) { + return isRoot; + } + + if (next.type === 'ContentStatement') { + return (sibling || !isRoot ? /^\s*?\r?\n/ : /^\s*?(\r?\n|$)/).test(next.original); + } + } + + // Marks the node to the right of the position as omitted. + // I.e. {{foo}}' ' will mark the ' ' node as omitted. + // + // If i is undefined, then the first child will be marked as such. + // + // If mulitple is truthy then all whitespace will be stripped out until non-whitespace + // content is met. + function omitRight(body, i, multiple) { + var current = body[i == null ? 0 : i + 1]; + if (!current || current.type !== 'ContentStatement' || !multiple && current.rightStripped) { + return; + } + + var original = current.value; + current.value = current.value.replace(multiple ? /^\s+/ : /^[ \t]*\r?\n?/, ''); + current.rightStripped = current.value !== original; + } + + // Marks the node to the left of the position as omitted. + // I.e. ' '{{foo}} will mark the ' ' node as omitted. + // + // If i is undefined then the last child will be marked as such. + // + // If mulitple is truthy then all whitespace will be stripped out until non-whitespace + // content is met. + function omitLeft(body, i, multiple) { + var current = body[i == null ? body.length - 1 : i - 1]; + if (!current || current.type !== 'ContentStatement' || !multiple && current.leftStripped) { + return; + } + + // We omit the last node if it's whitespace only and not preceeded by a non-content node. + var original = current.value; + current.value = current.value.replace(multiple ? /\s+$/ : /[ \t]+$/, ''); + current.leftStripped = current.value !== original; + return current.leftStripped; + } + + exports['default'] = WhitespaceControl; + module.exports = exports['default']; + +/***/ }, +/* 25 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var _interopRequireDefault = __webpack_require__(1)['default']; + + exports.__esModule = true; + + var _exception = __webpack_require__(6); + + var _exception2 = _interopRequireDefault(_exception); + + function Visitor() { + this.parents = []; + } + + Visitor.prototype = { + constructor: Visitor, + mutating: false, + + // Visits a given value. If mutating, will replace the value if necessary. + acceptKey: function acceptKey(node, name) { + var value = this.accept(node[name]); + if (this.mutating) { + // Hacky sanity check: This may have a few false positives for type for the helper + // methods but will generally do the right thing without a lot of overhead. + if (value && !Visitor.prototype[value.type]) { + throw new _exception2['default']('Unexpected node type "' + value.type + '" found when accepting ' + name + ' on ' + node.type); + } + node[name] = value; + } + }, + + // Performs an accept operation with added sanity check to ensure + // required keys are not removed. + acceptRequired: function acceptRequired(node, name) { + this.acceptKey(node, name); + + if (!node[name]) { + throw new _exception2['default'](node.type + ' requires ' + name); + } + }, + + // Traverses a given array. If mutating, empty respnses will be removed + // for child elements. + acceptArray: function acceptArray(array) { + for (var i = 0, l = array.length; i < l; i++) { + this.acceptKey(array, i); + + if (!array[i]) { + array.splice(i, 1); + i--; + l--; + } + } + }, + + accept: function accept(object) { + if (!object) { + return; + } + + /* istanbul ignore next: Sanity code */ + if (!this[object.type]) { + throw new _exception2['default']('Unknown type: ' + object.type, object); + } + + if (this.current) { + this.parents.unshift(this.current); + } + this.current = object; + + var ret = this[object.type](object); + + this.current = this.parents.shift(); + + if (!this.mutating || ret) { + return ret; + } else if (ret !== false) { + return object; + } + }, + + Program: function Program(program) { + this.acceptArray(program.body); + }, + + MustacheStatement: visitSubExpression, + Decorator: visitSubExpression, + + BlockStatement: visitBlock, + DecoratorBlock: visitBlock, + + PartialStatement: visitPartial, + PartialBlockStatement: function PartialBlockStatement(partial) { + visitPartial.call(this, partial); + + this.acceptKey(partial, 'program'); + }, + + ContentStatement: function ContentStatement() /* content */{}, + CommentStatement: function CommentStatement() /* comment */{}, + + SubExpression: visitSubExpression, + + PathExpression: function PathExpression() /* path */{}, + + StringLiteral: function StringLiteral() /* string */{}, + NumberLiteral: function NumberLiteral() /* number */{}, + BooleanLiteral: function BooleanLiteral() /* bool */{}, + UndefinedLiteral: function UndefinedLiteral() /* literal */{}, + NullLiteral: function NullLiteral() /* literal */{}, + + Hash: function Hash(hash) { + this.acceptArray(hash.pairs); + }, + HashPair: function HashPair(pair) { + this.acceptRequired(pair, 'value'); + } + }; + + function visitSubExpression(mustache) { + this.acceptRequired(mustache, 'path'); + this.acceptArray(mustache.params); + this.acceptKey(mustache, 'hash'); + } + function visitBlock(block) { + visitSubExpression.call(this, block); + + this.acceptKey(block, 'program'); + this.acceptKey(block, 'inverse'); + } + function visitPartial(partial) { + this.acceptRequired(partial, 'name'); + this.acceptArray(partial.params); + this.acceptKey(partial, 'hash'); + } + + exports['default'] = Visitor; + module.exports = exports['default']; + +/***/ }, +/* 26 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var _interopRequireDefault = __webpack_require__(1)['default']; + + exports.__esModule = true; + exports.SourceLocation = SourceLocation; + exports.id = id; + exports.stripFlags = stripFlags; + exports.stripComment = stripComment; + exports.preparePath = preparePath; + exports.prepareMustache = prepareMustache; + exports.prepareRawBlock = prepareRawBlock; + exports.prepareBlock = prepareBlock; + exports.prepareProgram = prepareProgram; + exports.preparePartialBlock = preparePartialBlock; + + var _exception = __webpack_require__(6); + + var _exception2 = _interopRequireDefault(_exception); + + function validateClose(open, close) { + close = close.path ? close.path.original : close; + + if (open.path.original !== close) { + var errorNode = { loc: open.path.loc }; + + throw new _exception2['default'](open.path.original + " doesn't match " + close, errorNode); + } + } + + function SourceLocation(source, locInfo) { + this.source = source; + this.start = { + line: locInfo.first_line, + column: locInfo.first_column + }; + this.end = { + line: locInfo.last_line, + column: locInfo.last_column + }; + } + + function id(token) { + if (/^\[.*\]$/.test(token)) { + return token.substr(1, token.length - 2); + } else { + return token; + } + } + + function stripFlags(open, close) { + return { + open: open.charAt(2) === '~', + close: close.charAt(close.length - 3) === '~' + }; + } + + function stripComment(comment) { + return comment.replace(/^\{\{~?\!-?-?/, '').replace(/-?-?~?\}\}$/, ''); + } + + function preparePath(data, parts, loc) { + loc = this.locInfo(loc); + + var original = data ? '@' : '', + dig = [], + depth = 0, + depthString = ''; + + for (var i = 0, l = parts.length; i < l; i++) { + var part = parts[i].part, + + // If we have [] syntax then we do not treat path references as operators, + // i.e. foo.[this] resolves to approximately context.foo['this'] + isLiteral = parts[i].original !== part; + original += (parts[i].separator || '') + part; + + if (!isLiteral && (part === '..' || part === '.' || part === 'this')) { + if (dig.length > 0) { + throw new _exception2['default']('Invalid path: ' + original, { loc: loc }); + } else if (part === '..') { + depth++; + depthString += '../'; + } + } else { + dig.push(part); + } + } + + return { + type: 'PathExpression', + data: data, + depth: depth, + parts: dig, + original: original, + loc: loc + }; + } + + function prepareMustache(path, params, hash, open, strip, locInfo) { + // Must use charAt to support IE pre-10 + var escapeFlag = open.charAt(3) || open.charAt(2), + escaped = escapeFlag !== '{' && escapeFlag !== '&'; + + var decorator = /\*/.test(open); + return { + type: decorator ? 'Decorator' : 'MustacheStatement', + path: path, + params: params, + hash: hash, + escaped: escaped, + strip: strip, + loc: this.locInfo(locInfo) + }; + } + + function prepareRawBlock(openRawBlock, contents, close, locInfo) { + validateClose(openRawBlock, close); + + locInfo = this.locInfo(locInfo); + var program = { + type: 'Program', + body: contents, + strip: {}, + loc: locInfo + }; + + return { + type: 'BlockStatement', + path: openRawBlock.path, + params: openRawBlock.params, + hash: openRawBlock.hash, + program: program, + openStrip: {}, + inverseStrip: {}, + closeStrip: {}, + loc: locInfo + }; + } + + function prepareBlock(openBlock, program, inverseAndProgram, close, inverted, locInfo) { + if (close && close.path) { + validateClose(openBlock, close); + } + + var decorator = /\*/.test(openBlock.open); + + program.blockParams = openBlock.blockParams; + + var inverse = undefined, + inverseStrip = undefined; + + if (inverseAndProgram) { + if (decorator) { + throw new _exception2['default']('Unexpected inverse block on decorator', inverseAndProgram); + } + + if (inverseAndProgram.chain) { + inverseAndProgram.program.body[0].closeStrip = close.strip; + } + + inverseStrip = inverseAndProgram.strip; + inverse = inverseAndProgram.program; + } + + if (inverted) { + inverted = inverse; + inverse = program; + program = inverted; + } + + return { + type: decorator ? 'DecoratorBlock' : 'BlockStatement', + path: openBlock.path, + params: openBlock.params, + hash: openBlock.hash, + program: program, + inverse: inverse, + openStrip: openBlock.strip, + inverseStrip: inverseStrip, + closeStrip: close && close.strip, + loc: this.locInfo(locInfo) + }; + } + + function prepareProgram(statements, loc) { + if (!loc && statements.length) { + var firstLoc = statements[0].loc, + lastLoc = statements[statements.length - 1].loc; + + /* istanbul ignore else */ + if (firstLoc && lastLoc) { + loc = { + source: firstLoc.source, + start: { + line: firstLoc.start.line, + column: firstLoc.start.column + }, + end: { + line: lastLoc.end.line, + column: lastLoc.end.column + } + }; + } + } + + return { + type: 'Program', + body: statements, + strip: {}, + loc: loc + }; + } + + function preparePartialBlock(open, program, close, locInfo) { + validateClose(open, close); + + return { + type: 'PartialBlockStatement', + name: open.path, + params: open.params, + hash: open.hash, + program: program, + openStrip: open.strip, + closeStrip: close && close.strip, + loc: this.locInfo(locInfo) + }; + } + +/***/ }, +/* 27 */ +/***/ function(module, exports, __webpack_require__) { + + /* eslint-disable new-cap */ + + 'use strict'; + + var _interopRequireDefault = __webpack_require__(1)['default']; + + exports.__esModule = true; + exports.Compiler = Compiler; + exports.precompile = precompile; + exports.compile = compile; + + var _exception = __webpack_require__(6); + + var _exception2 = _interopRequireDefault(_exception); + + var _utils = __webpack_require__(5); + + var _ast = __webpack_require__(21); + + var _ast2 = _interopRequireDefault(_ast); + + var slice = [].slice; + + function Compiler() {} + + // the foundHelper register will disambiguate helper lookup from finding a + // function in a context. This is necessary for mustache compatibility, which + // requires that context functions in blocks are evaluated by blockHelperMissing, + // and then proceed as if the resulting value was provided to blockHelperMissing. + + Compiler.prototype = { + compiler: Compiler, + + equals: function equals(other) { + var len = this.opcodes.length; + if (other.opcodes.length !== len) { + return false; + } + + for (var i = 0; i < len; i++) { + var opcode = this.opcodes[i], + otherOpcode = other.opcodes[i]; + if (opcode.opcode !== otherOpcode.opcode || !argEquals(opcode.args, otherOpcode.args)) { + return false; + } + } + + // We know that length is the same between the two arrays because they are directly tied + // to the opcode behavior above. + len = this.children.length; + for (var i = 0; i < len; i++) { + if (!this.children[i].equals(other.children[i])) { + return false; + } + } + + return true; + }, + + guid: 0, + + compile: function compile(program, options) { + this.sourceNode = []; + this.opcodes = []; + this.children = []; + this.options = options; + this.stringParams = options.stringParams; + this.trackIds = options.trackIds; + + options.blockParams = options.blockParams || []; + + // These changes will propagate to the other compiler components + var knownHelpers = options.knownHelpers; + options.knownHelpers = { + 'helperMissing': true, + 'blockHelperMissing': true, + 'each': true, + 'if': true, + 'unless': true, + 'with': true, + 'log': true, + 'lookup': true + }; + if (knownHelpers) { + for (var _name in knownHelpers) { + /* istanbul ignore else */ + if (_name in knownHelpers) { + options.knownHelpers[_name] = knownHelpers[_name]; + } + } + } + + return this.accept(program); + }, + + compileProgram: function compileProgram(program) { + var childCompiler = new this.compiler(), + // eslint-disable-line new-cap + result = childCompiler.compile(program, this.options), + guid = this.guid++; + + this.usePartial = this.usePartial || result.usePartial; + + this.children[guid] = result; + this.useDepths = this.useDepths || result.useDepths; + + return guid; + }, + + accept: function accept(node) { + /* istanbul ignore next: Sanity code */ + if (!this[node.type]) { + throw new _exception2['default']('Unknown type: ' + node.type, node); + } + + this.sourceNode.unshift(node); + var ret = this[node.type](node); + this.sourceNode.shift(); + return ret; + }, + + Program: function Program(program) { + this.options.blockParams.unshift(program.blockParams); + + var body = program.body, + bodyLength = body.length; + for (var i = 0; i < bodyLength; i++) { + this.accept(body[i]); + } + + this.options.blockParams.shift(); + + this.isSimple = bodyLength === 1; + this.blockParams = program.blockParams ? program.blockParams.length : 0; + + return this; + }, + + BlockStatement: function BlockStatement(block) { + transformLiteralToPath(block); + + var program = block.program, + inverse = block.inverse; + + program = program && this.compileProgram(program); + inverse = inverse && this.compileProgram(inverse); + + var type = this.classifySexpr(block); + + if (type === 'helper') { + this.helperSexpr(block, program, inverse); + } else if (type === 'simple') { + this.simpleSexpr(block); + + // now that the simple mustache is resolved, we need to + // evaluate it by executing `blockHelperMissing` + this.opcode('pushProgram', program); + this.opcode('pushProgram', inverse); + this.opcode('emptyHash'); + this.opcode('blockValue', block.path.original); + } else { + this.ambiguousSexpr(block, program, inverse); + + // now that the simple mustache is resolved, we need to + // evaluate it by executing `blockHelperMissing` + this.opcode('pushProgram', program); + this.opcode('pushProgram', inverse); + this.opcode('emptyHash'); + this.opcode('ambiguousBlockValue'); + } + + this.opcode('append'); + }, + + DecoratorBlock: function DecoratorBlock(decorator) { + var program = decorator.program && this.compileProgram(decorator.program); + var params = this.setupFullMustacheParams(decorator, program, undefined), + path = decorator.path; + + this.useDecorators = true; + this.opcode('registerDecorator', params.length, path.original); + }, + + PartialStatement: function PartialStatement(partial) { + this.usePartial = true; + + var program = partial.program; + if (program) { + program = this.compileProgram(partial.program); + } + + var params = partial.params; + if (params.length > 1) { + throw new _exception2['default']('Unsupported number of partial arguments: ' + params.length, partial); + } else if (!params.length) { + if (this.options.explicitPartialContext) { + this.opcode('pushLiteral', 'undefined'); + } else { + params.push({ type: 'PathExpression', parts: [], depth: 0 }); + } + } + + var partialName = partial.name.original, + isDynamic = partial.name.type === 'SubExpression'; + if (isDynamic) { + this.accept(partial.name); + } + + this.setupFullMustacheParams(partial, program, undefined, true); + + var indent = partial.indent || ''; + if (this.options.preventIndent && indent) { + this.opcode('appendContent', indent); + indent = ''; + } + + this.opcode('invokePartial', isDynamic, partialName, indent); + this.opcode('append'); + }, + PartialBlockStatement: function PartialBlockStatement(partialBlock) { + this.PartialStatement(partialBlock); + }, + + MustacheStatement: function MustacheStatement(mustache) { + this.SubExpression(mustache); + + if (mustache.escaped && !this.options.noEscape) { + this.opcode('appendEscaped'); + } else { + this.opcode('append'); + } + }, + Decorator: function Decorator(decorator) { + this.DecoratorBlock(decorator); + }, + + ContentStatement: function ContentStatement(content) { + if (content.value) { + this.opcode('appendContent', content.value); + } + }, + + CommentStatement: function CommentStatement() {}, + + SubExpression: function SubExpression(sexpr) { + transformLiteralToPath(sexpr); + var type = this.classifySexpr(sexpr); + + if (type === 'simple') { + this.simpleSexpr(sexpr); + } else if (type === 'helper') { + this.helperSexpr(sexpr); + } else { + this.ambiguousSexpr(sexpr); + } + }, + ambiguousSexpr: function ambiguousSexpr(sexpr, program, inverse) { + var path = sexpr.path, + name = path.parts[0], + isBlock = program != null || inverse != null; + + this.opcode('getContext', path.depth); + + this.opcode('pushProgram', program); + this.opcode('pushProgram', inverse); + + path.strict = true; + this.accept(path); + + this.opcode('invokeAmbiguous', name, isBlock); + }, + + simpleSexpr: function simpleSexpr(sexpr) { + var path = sexpr.path; + path.strict = true; + this.accept(path); + this.opcode('resolvePossibleLambda'); + }, + + helperSexpr: function helperSexpr(sexpr, program, inverse) { + var params = this.setupFullMustacheParams(sexpr, program, inverse), + path = sexpr.path, + name = path.parts[0]; + + if (this.options.knownHelpers[name]) { + this.opcode('invokeKnownHelper', params.length, name); + } else if (this.options.knownHelpersOnly) { + throw new _exception2['default']('You specified knownHelpersOnly, but used the unknown helper ' + name, sexpr); + } else { + path.strict = true; + path.falsy = true; + + this.accept(path); + this.opcode('invokeHelper', params.length, path.original, _ast2['default'].helpers.simpleId(path)); + } + }, + + PathExpression: function PathExpression(path) { + this.addDepth(path.depth); + this.opcode('getContext', path.depth); + + var name = path.parts[0], + scoped = _ast2['default'].helpers.scopedId(path), + blockParamId = !path.depth && !scoped && this.blockParamIndex(name); + + if (blockParamId) { + this.opcode('lookupBlockParam', blockParamId, path.parts); + } else if (!name) { + // Context reference, i.e. `{{foo .}}` or `{{foo ..}}` + this.opcode('pushContext'); + } else if (path.data) { + this.options.data = true; + this.opcode('lookupData', path.depth, path.parts, path.strict); + } else { + this.opcode('lookupOnContext', path.parts, path.falsy, path.strict, scoped); + } + }, + + StringLiteral: function StringLiteral(string) { + this.opcode('pushString', string.value); + }, + + NumberLiteral: function NumberLiteral(number) { + this.opcode('pushLiteral', number.value); + }, + + BooleanLiteral: function BooleanLiteral(bool) { + this.opcode('pushLiteral', bool.value); + }, + + UndefinedLiteral: function UndefinedLiteral() { + this.opcode('pushLiteral', 'undefined'); + }, + + NullLiteral: function NullLiteral() { + this.opcode('pushLiteral', 'null'); + }, + + Hash: function Hash(hash) { + var pairs = hash.pairs, + i = 0, + l = pairs.length; + + this.opcode('pushHash'); + + for (; i < l; i++) { + this.pushParam(pairs[i].value); + } + while (i--) { + this.opcode('assignToHash', pairs[i].key); + } + this.opcode('popHash'); + }, + + // HELPERS + opcode: function opcode(name) { + this.opcodes.push({ opcode: name, args: slice.call(arguments, 1), loc: this.sourceNode[0].loc }); + }, + + addDepth: function addDepth(depth) { + if (!depth) { + return; + } + + this.useDepths = true; + }, + + classifySexpr: function classifySexpr(sexpr) { + var isSimple = _ast2['default'].helpers.simpleId(sexpr.path); + + var isBlockParam = isSimple && !!this.blockParamIndex(sexpr.path.parts[0]); + + // a mustache is an eligible helper if: + // * its id is simple (a single part, not `this` or `..`) + var isHelper = !isBlockParam && _ast2['default'].helpers.helperExpression(sexpr); + + // if a mustache is an eligible helper but not a definite + // helper, it is ambiguous, and will be resolved in a later + // pass or at runtime. + var isEligible = !isBlockParam && (isHelper || isSimple); + + // if ambiguous, we can possibly resolve the ambiguity now + // An eligible helper is one that does not have a complex path, i.e. `this.foo`, `../foo` etc. + if (isEligible && !isHelper) { + var _name2 = sexpr.path.parts[0], + options = this.options; + + if (options.knownHelpers[_name2]) { + isHelper = true; + } else if (options.knownHelpersOnly) { + isEligible = false; + } + } + + if (isHelper) { + return 'helper'; + } else if (isEligible) { + return 'ambiguous'; + } else { + return 'simple'; + } + }, + + pushParams: function pushParams(params) { + for (var i = 0, l = params.length; i < l; i++) { + this.pushParam(params[i]); + } + }, + + pushParam: function pushParam(val) { + var value = val.value != null ? val.value : val.original || ''; + + if (this.stringParams) { + if (value.replace) { + value = value.replace(/^(\.?\.\/)*/g, '').replace(/\//g, '.'); + } + + if (val.depth) { + this.addDepth(val.depth); + } + this.opcode('getContext', val.depth || 0); + this.opcode('pushStringParam', value, val.type); + + if (val.type === 'SubExpression') { + // SubExpressions get evaluated and passed in + // in string params mode. + this.accept(val); + } + } else { + if (this.trackIds) { + var blockParamIndex = undefined; + if (val.parts && !_ast2['default'].helpers.scopedId(val) && !val.depth) { + blockParamIndex = this.blockParamIndex(val.parts[0]); + } + if (blockParamIndex) { + var blockParamChild = val.parts.slice(1).join('.'); + this.opcode('pushId', 'BlockParam', blockParamIndex, blockParamChild); + } else { + value = val.original || value; + if (value.replace) { + value = value.replace(/^this(?:\.|$)/, '').replace(/^\.\//, '').replace(/^\.$/, ''); + } + + this.opcode('pushId', val.type, value); + } + } + this.accept(val); + } + }, + + setupFullMustacheParams: function setupFullMustacheParams(sexpr, program, inverse, omitEmpty) { + var params = sexpr.params; + this.pushParams(params); + + this.opcode('pushProgram', program); + this.opcode('pushProgram', inverse); + + if (sexpr.hash) { + this.accept(sexpr.hash); + } else { + this.opcode('emptyHash', omitEmpty); + } + + return params; + }, + + blockParamIndex: function blockParamIndex(name) { + for (var depth = 0, len = this.options.blockParams.length; depth < len; depth++) { + var blockParams = this.options.blockParams[depth], + param = blockParams && _utils.indexOf(blockParams, name); + if (blockParams && param >= 0) { + return [depth, param]; + } + } + } + }; + + function precompile(input, options, env) { + if (input == null || typeof input !== 'string' && input.type !== 'Program') { + throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.precompile. You passed ' + input); + } + + options = options || {}; + if (!('data' in options)) { + options.data = true; + } + if (options.compat) { + options.useDepths = true; + } + + var ast = env.parse(input, options), + environment = new env.Compiler().compile(ast, options); + return new env.JavaScriptCompiler().compile(environment, options); + } + + function compile(input, options, env) { + if (options === undefined) options = {}; + + if (input == null || typeof input !== 'string' && input.type !== 'Program') { + throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.compile. You passed ' + input); + } + + if (!('data' in options)) { + options.data = true; + } + if (options.compat) { + options.useDepths = true; + } + + var compiled = undefined; + + function compileInput() { + var ast = env.parse(input, options), + environment = new env.Compiler().compile(ast, options), + templateSpec = new env.JavaScriptCompiler().compile(environment, options, undefined, true); + return env.template(templateSpec); + } + + // Template is only compiled on first use and cached after that point. + function ret(context, execOptions) { + if (!compiled) { + compiled = compileInput(); + } + return compiled.call(this, context, execOptions); + } + ret._setup = function (setupOptions) { + if (!compiled) { + compiled = compileInput(); + } + return compiled._setup(setupOptions); + }; + ret._child = function (i, data, blockParams, depths) { + if (!compiled) { + compiled = compileInput(); + } + return compiled._child(i, data, blockParams, depths); + }; + return ret; + } + + function argEquals(a, b) { + if (a === b) { + return true; + } + + if (_utils.isArray(a) && _utils.isArray(b) && a.length === b.length) { + for (var i = 0; i < a.length; i++) { + if (!argEquals(a[i], b[i])) { + return false; + } + } + return true; + } + } + + function transformLiteralToPath(sexpr) { + if (!sexpr.path.parts) { + var literal = sexpr.path; + // Casting to string here to make false and 0 literal values play nicely with the rest + // of the system. + sexpr.path = { + type: 'PathExpression', + data: false, + depth: 0, + parts: [literal.original + ''], + original: literal.original + '', + loc: literal.loc + }; + } + } + +/***/ }, +/* 28 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var _interopRequireDefault = __webpack_require__(1)['default']; + + exports.__esModule = true; + + var _base = __webpack_require__(4); + + var _exception = __webpack_require__(6); + + var _exception2 = _interopRequireDefault(_exception); + + var _utils = __webpack_require__(5); + + var _codeGen = __webpack_require__(29); + + var _codeGen2 = _interopRequireDefault(_codeGen); + + function Literal(value) { + this.value = value; + } + + function JavaScriptCompiler() {} + + JavaScriptCompiler.prototype = { + // PUBLIC API: You can override these methods in a subclass to provide + // alternative compiled forms for name lookup and buffering semantics + nameLookup: function nameLookup(parent, name /* , type*/) { + if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) { + return [parent, '.', name]; + } else { + return [parent, '[', JSON.stringify(name), ']']; + } + }, + depthedLookup: function depthedLookup(name) { + return [this.aliasable('container.lookup'), '(depths, "', name, '")']; + }, + + compilerInfo: function compilerInfo() { + var revision = _base.COMPILER_REVISION, + versions = _base.REVISION_CHANGES[revision]; + return [revision, versions]; + }, + + appendToBuffer: function appendToBuffer(source, location, explicit) { + // Force a source as this simplifies the merge logic. + if (!_utils.isArray(source)) { + source = [source]; + } + source = this.source.wrap(source, location); + + if (this.environment.isSimple) { + return ['return ', source, ';']; + } else if (explicit) { + // This is a case where the buffer operation occurs as a child of another + // construct, generally braces. We have to explicitly output these buffer + // operations to ensure that the emitted code goes in the correct location. + return ['buffer += ', source, ';']; + } else { + source.appendToBuffer = true; + return source; + } + }, + + initializeBuffer: function initializeBuffer() { + return this.quotedString(''); + }, + // END PUBLIC API + + compile: function compile(environment, options, context, asObject) { + this.environment = environment; + this.options = options; + this.stringParams = this.options.stringParams; + this.trackIds = this.options.trackIds; + this.precompile = !asObject; + + this.name = this.environment.name; + this.isChild = !!context; + this.context = context || { + decorators: [], + programs: [], + environments: [] + }; + + this.preamble(); + + this.stackSlot = 0; + this.stackVars = []; + this.aliases = {}; + this.registers = { list: [] }; + this.hashes = []; + this.compileStack = []; + this.inlineStack = []; + this.blockParams = []; + + this.compileChildren(environment, options); + + this.useDepths = this.useDepths || environment.useDepths || environment.useDecorators || this.options.compat; + this.useBlockParams = this.useBlockParams || environment.useBlockParams; + + var opcodes = environment.opcodes, + opcode = undefined, + firstLoc = undefined, + i = undefined, + l = undefined; + + for (i = 0, l = opcodes.length; i < l; i++) { + opcode = opcodes[i]; + + this.source.currentLocation = opcode.loc; + firstLoc = firstLoc || opcode.loc; + this[opcode.opcode].apply(this, opcode.args); + } + + // Flush any trailing content that might be pending. + this.source.currentLocation = firstLoc; + this.pushSource(''); + + /* istanbul ignore next */ + if (this.stackSlot || this.inlineStack.length || this.compileStack.length) { + throw new _exception2['default']('Compile completed with content left on stack'); + } + + if (!this.decorators.isEmpty()) { + this.useDecorators = true; + + this.decorators.prepend('var decorators = container.decorators;\n'); + this.decorators.push('return fn;'); + + if (asObject) { + this.decorators = Function.apply(this, ['fn', 'props', 'container', 'depth0', 'data', 'blockParams', 'depths', this.decorators.merge()]); + } else { + this.decorators.prepend('function(fn, props, container, depth0, data, blockParams, depths) {\n'); + this.decorators.push('}\n'); + this.decorators = this.decorators.merge(); + } + } else { + this.decorators = undefined; + } + + var fn = this.createFunctionContext(asObject); + if (!this.isChild) { + var ret = { + compiler: this.compilerInfo(), + main: fn + }; + + if (this.decorators) { + ret.main_d = this.decorators; // eslint-disable-line camelcase + ret.useDecorators = true; + } + + var _context = this.context; + var programs = _context.programs; + var decorators = _context.decorators; + + for (i = 0, l = programs.length; i < l; i++) { + if (programs[i]) { + ret[i] = programs[i]; + if (decorators[i]) { + ret[i + '_d'] = decorators[i]; + ret.useDecorators = true; + } + } + } + + if (this.environment.usePartial) { + ret.usePartial = true; + } + if (this.options.data) { + ret.useData = true; + } + if (this.useDepths) { + ret.useDepths = true; + } + if (this.useBlockParams) { + ret.useBlockParams = true; + } + if (this.options.compat) { + ret.compat = true; + } + + if (!asObject) { + ret.compiler = JSON.stringify(ret.compiler); + + this.source.currentLocation = { start: { line: 1, column: 0 } }; + ret = this.objectLiteral(ret); + + if (options.srcName) { + ret = ret.toStringWithSourceMap({ file: options.destName }); + ret.map = ret.map && ret.map.toString(); + } else { + ret = ret.toString(); + } + } else { + ret.compilerOptions = this.options; + } + + return ret; + } else { + return fn; + } + }, + + preamble: function preamble() { + // track the last context pushed into place to allow skipping the + // getContext opcode when it would be a noop + this.lastContext = 0; + this.source = new _codeGen2['default'](this.options.srcName); + this.decorators = new _codeGen2['default'](this.options.srcName); + }, + + createFunctionContext: function createFunctionContext(asObject) { + var varDeclarations = ''; + + var locals = this.stackVars.concat(this.registers.list); + if (locals.length > 0) { + varDeclarations += ', ' + locals.join(', '); + } + + // Generate minimizer alias mappings + // + // When using true SourceNodes, this will update all references to the given alias + // as the source nodes are reused in situ. For the non-source node compilation mode, + // aliases will not be used, but this case is already being run on the client and + // we aren't concern about minimizing the template size. + var aliasCount = 0; + for (var alias in this.aliases) { + // eslint-disable-line guard-for-in + var node = this.aliases[alias]; + + if (this.aliases.hasOwnProperty(alias) && node.children && node.referenceCount > 1) { + varDeclarations += ', alias' + ++aliasCount + '=' + alias; + node.children[0] = 'alias' + aliasCount; + } + } + + var params = ['container', 'depth0', 'helpers', 'partials', 'data']; + + if (this.useBlockParams || this.useDepths) { + params.push('blockParams'); + } + if (this.useDepths) { + params.push('depths'); + } + + // Perform a second pass over the output to merge content when possible + var source = this.mergeSource(varDeclarations); + + if (asObject) { + params.push(source); + + return Function.apply(this, params); + } else { + return this.source.wrap(['function(', params.join(','), ') {\n ', source, '}']); + } + }, + mergeSource: function mergeSource(varDeclarations) { + var isSimple = this.environment.isSimple, + appendOnly = !this.forceBuffer, + appendFirst = undefined, + sourceSeen = undefined, + bufferStart = undefined, + bufferEnd = undefined; + this.source.each(function (line) { + if (line.appendToBuffer) { + if (bufferStart) { + line.prepend(' + '); + } else { + bufferStart = line; + } + bufferEnd = line; + } else { + if (bufferStart) { + if (!sourceSeen) { + appendFirst = true; + } else { + bufferStart.prepend('buffer += '); + } + bufferEnd.add(';'); + bufferStart = bufferEnd = undefined; + } + + sourceSeen = true; + if (!isSimple) { + appendOnly = false; + } + } + }); + + if (appendOnly) { + if (bufferStart) { + bufferStart.prepend('return '); + bufferEnd.add(';'); + } else if (!sourceSeen) { + this.source.push('return "";'); + } + } else { + varDeclarations += ', buffer = ' + (appendFirst ? '' : this.initializeBuffer()); + + if (bufferStart) { + bufferStart.prepend('return buffer + '); + bufferEnd.add(';'); + } else { + this.source.push('return buffer;'); + } + } + + if (varDeclarations) { + this.source.prepend('var ' + varDeclarations.substring(2) + (appendFirst ? '' : ';\n')); + } + + return this.source.merge(); + }, + + // [blockValue] + // + // On stack, before: hash, inverse, program, value + // On stack, after: return value of blockHelperMissing + // + // The purpose of this opcode is to take a block of the form + // `{{#this.foo}}...{{/this.foo}}`, resolve the value of `foo`, and + // replace it on the stack with the result of properly + // invoking blockHelperMissing. + blockValue: function blockValue(name) { + var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'), + params = [this.contextName(0)]; + this.setupHelperArgs(name, 0, params); + + var blockName = this.popStack(); + params.splice(1, 0, blockName); + + this.push(this.source.functionCall(blockHelperMissing, 'call', params)); + }, + + // [ambiguousBlockValue] + // + // On stack, before: hash, inverse, program, value + // Compiler value, before: lastHelper=value of last found helper, if any + // On stack, after, if no lastHelper: same as [blockValue] + // On stack, after, if lastHelper: value + ambiguousBlockValue: function ambiguousBlockValue() { + // We're being a bit cheeky and reusing the options value from the prior exec + var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'), + params = [this.contextName(0)]; + this.setupHelperArgs('', 0, params, true); + + this.flushInline(); + + var current = this.topStack(); + params.splice(1, 0, current); + + this.pushSource(['if (!', this.lastHelper, ') { ', current, ' = ', this.source.functionCall(blockHelperMissing, 'call', params), '}']); + }, + + // [appendContent] + // + // On stack, before: ... + // On stack, after: ... + // + // Appends the string value of `content` to the current buffer + appendContent: function appendContent(content) { + if (this.pendingContent) { + content = this.pendingContent + content; + } else { + this.pendingLocation = this.source.currentLocation; + } + + this.pendingContent = content; + }, + + // [append] + // + // On stack, before: value, ... + // On stack, after: ... + // + // Coerces `value` to a String and appends it to the current buffer. + // + // If `value` is truthy, or 0, it is coerced into a string and appended + // Otherwise, the empty string is appended + append: function append() { + if (this.isInline()) { + this.replaceStack(function (current) { + return [' != null ? ', current, ' : ""']; + }); + + this.pushSource(this.appendToBuffer(this.popStack())); + } else { + var local = this.popStack(); + this.pushSource(['if (', local, ' != null) { ', this.appendToBuffer(local, undefined, true), ' }']); + if (this.environment.isSimple) { + this.pushSource(['else { ', this.appendToBuffer("''", undefined, true), ' }']); + } + } + }, + + // [appendEscaped] + // + // On stack, before: value, ... + // On stack, after: ... + // + // Escape `value` and append it to the buffer + appendEscaped: function appendEscaped() { + this.pushSource(this.appendToBuffer([this.aliasable('container.escapeExpression'), '(', this.popStack(), ')'])); + }, + + // [getContext] + // + // On stack, before: ... + // On stack, after: ... + // Compiler value, after: lastContext=depth + // + // Set the value of the `lastContext` compiler value to the depth + getContext: function getContext(depth) { + this.lastContext = depth; + }, + + // [pushContext] + // + // On stack, before: ... + // On stack, after: currentContext, ... + // + // Pushes the value of the current context onto the stack. + pushContext: function pushContext() { + this.pushStackLiteral(this.contextName(this.lastContext)); + }, + + // [lookupOnContext] + // + // On stack, before: ... + // On stack, after: currentContext[name], ... + // + // Looks up the value of `name` on the current context and pushes + // it onto the stack. + lookupOnContext: function lookupOnContext(parts, falsy, strict, scoped) { + var i = 0; + + if (!scoped && this.options.compat && !this.lastContext) { + // The depthed query is expected to handle the undefined logic for the root level that + // is implemented below, so we evaluate that directly in compat mode + this.push(this.depthedLookup(parts[i++])); + } else { + this.pushContext(); + } + + this.resolvePath('context', parts, i, falsy, strict); + }, + + // [lookupBlockParam] + // + // On stack, before: ... + // On stack, after: blockParam[name], ... + // + // Looks up the value of `parts` on the given block param and pushes + // it onto the stack. + lookupBlockParam: function lookupBlockParam(blockParamId, parts) { + this.useBlockParams = true; + + this.push(['blockParams[', blockParamId[0], '][', blockParamId[1], ']']); + this.resolvePath('context', parts, 1); + }, + + // [lookupData] + // + // On stack, before: ... + // On stack, after: data, ... + // + // Push the data lookup operator + lookupData: function lookupData(depth, parts, strict) { + if (!depth) { + this.pushStackLiteral('data'); + } else { + this.pushStackLiteral('container.data(data, ' + depth + ')'); + } + + this.resolvePath('data', parts, 0, true, strict); + }, + + resolvePath: function resolvePath(type, parts, i, falsy, strict) { + // istanbul ignore next + + var _this = this; + + if (this.options.strict || this.options.assumeObjects) { + this.push(strictLookup(this.options.strict && strict, this, parts, type)); + return; + } + + var len = parts.length; + for (; i < len; i++) { + /* eslint-disable no-loop-func */ + this.replaceStack(function (current) { + var lookup = _this.nameLookup(current, parts[i], type); + // We want to ensure that zero and false are handled properly if the context (falsy flag) + // needs to have the special handling for these values. + if (!falsy) { + return [' != null ? ', lookup, ' : ', current]; + } else { + // Otherwise we can use generic falsy handling + return [' && ', lookup]; + } + }); + /* eslint-enable no-loop-func */ + } + }, + + // [resolvePossibleLambda] + // + // On stack, before: value, ... + // On stack, after: resolved value, ... + // + // If the `value` is a lambda, replace it on the stack by + // the return value of the lambda + resolvePossibleLambda: function resolvePossibleLambda() { + this.push([this.aliasable('container.lambda'), '(', this.popStack(), ', ', this.contextName(0), ')']); + }, + + // [pushStringParam] + // + // On stack, before: ... + // On stack, after: string, currentContext, ... + // + // This opcode is designed for use in string mode, which + // provides the string value of a parameter along with its + // depth rather than resolving it immediately. + pushStringParam: function pushStringParam(string, type) { + this.pushContext(); + this.pushString(type); + + // If it's a subexpression, the string result + // will be pushed after this opcode. + if (type !== 'SubExpression') { + if (typeof string === 'string') { + this.pushString(string); + } else { + this.pushStackLiteral(string); + } + } + }, + + emptyHash: function emptyHash(omitEmpty) { + if (this.trackIds) { + this.push('{}'); // hashIds + } + if (this.stringParams) { + this.push('{}'); // hashContexts + this.push('{}'); // hashTypes + } + this.pushStackLiteral(omitEmpty ? 'undefined' : '{}'); + }, + pushHash: function pushHash() { + if (this.hash) { + this.hashes.push(this.hash); + } + this.hash = { values: [], types: [], contexts: [], ids: [] }; + }, + popHash: function popHash() { + var hash = this.hash; + this.hash = this.hashes.pop(); + + if (this.trackIds) { + this.push(this.objectLiteral(hash.ids)); + } + if (this.stringParams) { + this.push(this.objectLiteral(hash.contexts)); + this.push(this.objectLiteral(hash.types)); + } + + this.push(this.objectLiteral(hash.values)); + }, + + // [pushString] + // + // On stack, before: ... + // On stack, after: quotedString(string), ... + // + // Push a quoted version of `string` onto the stack + pushString: function pushString(string) { + this.pushStackLiteral(this.quotedString(string)); + }, + + // [pushLiteral] + // + // On stack, before: ... + // On stack, after: value, ... + // + // Pushes a value onto the stack. This operation prevents + // the compiler from creating a temporary variable to hold + // it. + pushLiteral: function pushLiteral(value) { + this.pushStackLiteral(value); + }, + + // [pushProgram] + // + // On stack, before: ... + // On stack, after: program(guid), ... + // + // Push a program expression onto the stack. This takes + // a compile-time guid and converts it into a runtime-accessible + // expression. + pushProgram: function pushProgram(guid) { + if (guid != null) { + this.pushStackLiteral(this.programExpression(guid)); + } else { + this.pushStackLiteral(null); + } + }, + + // [registerDecorator] + // + // On stack, before: hash, program, params..., ... + // On stack, after: ... + // + // Pops off the decorator's parameters, invokes the decorator, + // and inserts the decorator into the decorators list. + registerDecorator: function registerDecorator(paramSize, name) { + var foundDecorator = this.nameLookup('decorators', name, 'decorator'), + options = this.setupHelperArgs(name, paramSize); + + this.decorators.push(['fn = ', this.decorators.functionCall(foundDecorator, '', ['fn', 'props', 'container', options]), ' || fn;']); + }, + + // [invokeHelper] + // + // On stack, before: hash, inverse, program, params..., ... + // On stack, after: result of helper invocation + // + // Pops off the helper's parameters, invokes the helper, + // and pushes the helper's return value onto the stack. + // + // If the helper is not found, `helperMissing` is called. + invokeHelper: function invokeHelper(paramSize, name, isSimple) { + var nonHelper = this.popStack(), + helper = this.setupHelper(paramSize, name), + simple = isSimple ? [helper.name, ' || '] : ''; + + var lookup = ['('].concat(simple, nonHelper); + if (!this.options.strict) { + lookup.push(' || ', this.aliasable('helpers.helperMissing')); + } + lookup.push(')'); + + this.push(this.source.functionCall(lookup, 'call', helper.callParams)); + }, + + // [invokeKnownHelper] + // + // On stack, before: hash, inverse, program, params..., ... + // On stack, after: result of helper invocation + // + // This operation is used when the helper is known to exist, + // so a `helperMissing` fallback is not required. + invokeKnownHelper: function invokeKnownHelper(paramSize, name) { + var helper = this.setupHelper(paramSize, name); + this.push(this.source.functionCall(helper.name, 'call', helper.callParams)); + }, + + // [invokeAmbiguous] + // + // On stack, before: hash, inverse, program, params..., ... + // On stack, after: result of disambiguation + // + // This operation is used when an expression like `{{foo}}` + // is provided, but we don't know at compile-time whether it + // is a helper or a path. + // + // This operation emits more code than the other options, + // and can be avoided by passing the `knownHelpers` and + // `knownHelpersOnly` flags at compile-time. + invokeAmbiguous: function invokeAmbiguous(name, helperCall) { + this.useRegister('helper'); + + var nonHelper = this.popStack(); + + this.emptyHash(); + var helper = this.setupHelper(0, name, helperCall); + + var helperName = this.lastHelper = this.nameLookup('helpers', name, 'helper'); + + var lookup = ['(', '(helper = ', helperName, ' || ', nonHelper, ')']; + if (!this.options.strict) { + lookup[0] = '(helper = '; + lookup.push(' != null ? helper : ', this.aliasable('helpers.helperMissing')); + } + + this.push(['(', lookup, helper.paramsInit ? ['),(', helper.paramsInit] : [], '),', '(typeof helper === ', this.aliasable('"function"'), ' ? ', this.source.functionCall('helper', 'call', helper.callParams), ' : helper))']); + }, + + // [invokePartial] + // + // On stack, before: context, ... + // On stack after: result of partial invocation + // + // This operation pops off a context, invokes a partial with that context, + // and pushes the result of the invocation back. + invokePartial: function invokePartial(isDynamic, name, indent) { + var params = [], + options = this.setupParams(name, 1, params); + + if (isDynamic) { + name = this.popStack(); + delete options.name; + } + + if (indent) { + options.indent = JSON.stringify(indent); + } + options.helpers = 'helpers'; + options.partials = 'partials'; + options.decorators = 'container.decorators'; + + if (!isDynamic) { + params.unshift(this.nameLookup('partials', name, 'partial')); + } else { + params.unshift(name); + } + + if (this.options.compat) { + options.depths = 'depths'; + } + options = this.objectLiteral(options); + params.push(options); + + this.push(this.source.functionCall('container.invokePartial', '', params)); + }, + + // [assignToHash] + // + // On stack, before: value, ..., hash, ... + // On stack, after: ..., hash, ... + // + // Pops a value off the stack and assigns it to the current hash + assignToHash: function assignToHash(key) { + var value = this.popStack(), + context = undefined, + type = undefined, + id = undefined; + + if (this.trackIds) { + id = this.popStack(); + } + if (this.stringParams) { + type = this.popStack(); + context = this.popStack(); + } + + var hash = this.hash; + if (context) { + hash.contexts[key] = context; + } + if (type) { + hash.types[key] = type; + } + if (id) { + hash.ids[key] = id; + } + hash.values[key] = value; + }, + + pushId: function pushId(type, name, child) { + if (type === 'BlockParam') { + this.pushStackLiteral('blockParams[' + name[0] + '].path[' + name[1] + ']' + (child ? ' + ' + JSON.stringify('.' + child) : '')); + } else if (type === 'PathExpression') { + this.pushString(name); + } else if (type === 'SubExpression') { + this.pushStackLiteral('true'); + } else { + this.pushStackLiteral('null'); + } + }, + + // HELPERS + + compiler: JavaScriptCompiler, + + compileChildren: function compileChildren(environment, options) { + var children = environment.children, + child = undefined, + compiler = undefined; + + for (var i = 0, l = children.length; i < l; i++) { + child = children[i]; + compiler = new this.compiler(); // eslint-disable-line new-cap + + var index = this.matchExistingProgram(child); + + if (index == null) { + this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children + index = this.context.programs.length; + child.index = index; + child.name = 'program' + index; + this.context.programs[index] = compiler.compile(child, options, this.context, !this.precompile); + this.context.decorators[index] = compiler.decorators; + this.context.environments[index] = child; + + this.useDepths = this.useDepths || compiler.useDepths; + this.useBlockParams = this.useBlockParams || compiler.useBlockParams; + } else { + child.index = index; + child.name = 'program' + index; + + this.useDepths = this.useDepths || child.useDepths; + this.useBlockParams = this.useBlockParams || child.useBlockParams; + } + } + }, + matchExistingProgram: function matchExistingProgram(child) { + for (var i = 0, len = this.context.environments.length; i < len; i++) { + var environment = this.context.environments[i]; + if (environment && environment.equals(child)) { + return i; + } + } + }, + + programExpression: function programExpression(guid) { + var child = this.environment.children[guid], + programParams = [child.index, 'data', child.blockParams]; + + if (this.useBlockParams || this.useDepths) { + programParams.push('blockParams'); + } + if (this.useDepths) { + programParams.push('depths'); + } + + return 'container.program(' + programParams.join(', ') + ')'; + }, + + useRegister: function useRegister(name) { + if (!this.registers[name]) { + this.registers[name] = true; + this.registers.list.push(name); + } + }, + + push: function push(expr) { + if (!(expr instanceof Literal)) { + expr = this.source.wrap(expr); + } + + this.inlineStack.push(expr); + return expr; + }, + + pushStackLiteral: function pushStackLiteral(item) { + this.push(new Literal(item)); + }, + + pushSource: function pushSource(source) { + if (this.pendingContent) { + this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent), this.pendingLocation)); + this.pendingContent = undefined; + } + + if (source) { + this.source.push(source); + } + }, + + replaceStack: function replaceStack(callback) { + var prefix = ['('], + stack = undefined, + createdStack = undefined, + usedLiteral = undefined; + + /* istanbul ignore next */ + if (!this.isInline()) { + throw new _exception2['default']('replaceStack on non-inline'); + } + + // We want to merge the inline statement into the replacement statement via ',' + var top = this.popStack(true); + + if (top instanceof Literal) { + // Literals do not need to be inlined + stack = [top.value]; + prefix = ['(', stack]; + usedLiteral = true; + } else { + // Get or create the current stack name for use by the inline + createdStack = true; + var _name = this.incrStack(); + + prefix = ['((', this.push(_name), ' = ', top, ')']; + stack = this.topStack(); + } + + var item = callback.call(this, stack); + + if (!usedLiteral) { + this.popStack(); + } + if (createdStack) { + this.stackSlot--; + } + this.push(prefix.concat(item, ')')); + }, + + incrStack: function incrStack() { + this.stackSlot++; + if (this.stackSlot > this.stackVars.length) { + this.stackVars.push('stack' + this.stackSlot); + } + return this.topStackName(); + }, + topStackName: function topStackName() { + return 'stack' + this.stackSlot; + }, + flushInline: function flushInline() { + var inlineStack = this.inlineStack; + this.inlineStack = []; + for (var i = 0, len = inlineStack.length; i < len; i++) { + var entry = inlineStack[i]; + /* istanbul ignore if */ + if (entry instanceof Literal) { + this.compileStack.push(entry); + } else { + var stack = this.incrStack(); + this.pushSource([stack, ' = ', entry, ';']); + this.compileStack.push(stack); + } + } + }, + isInline: function isInline() { + return this.inlineStack.length; + }, + + popStack: function popStack(wrapped) { + var inline = this.isInline(), + item = (inline ? this.inlineStack : this.compileStack).pop(); + + if (!wrapped && item instanceof Literal) { + return item.value; + } else { + if (!inline) { + /* istanbul ignore next */ + if (!this.stackSlot) { + throw new _exception2['default']('Invalid stack pop'); + } + this.stackSlot--; + } + return item; + } + }, + + topStack: function topStack() { + var stack = this.isInline() ? this.inlineStack : this.compileStack, + item = stack[stack.length - 1]; + + /* istanbul ignore if */ + if (item instanceof Literal) { + return item.value; + } else { + return item; + } + }, + + contextName: function contextName(context) { + if (this.useDepths && context) { + return 'depths[' + context + ']'; + } else { + return 'depth' + context; + } + }, + + quotedString: function quotedString(str) { + return this.source.quotedString(str); + }, + + objectLiteral: function objectLiteral(obj) { + return this.source.objectLiteral(obj); + }, + + aliasable: function aliasable(name) { + var ret = this.aliases[name]; + if (ret) { + ret.referenceCount++; + return ret; + } + + ret = this.aliases[name] = this.source.wrap(name); + ret.aliasable = true; + ret.referenceCount = 1; + + return ret; + }, + + setupHelper: function setupHelper(paramSize, name, blockHelper) { + var params = [], + paramsInit = this.setupHelperArgs(name, paramSize, params, blockHelper); + var foundHelper = this.nameLookup('helpers', name, 'helper'), + callContext = this.aliasable(this.contextName(0) + ' != null ? ' + this.contextName(0) + ' : {}'); + + return { + params: params, + paramsInit: paramsInit, + name: foundHelper, + callParams: [callContext].concat(params) + }; + }, + + setupParams: function setupParams(helper, paramSize, params) { + var options = {}, + contexts = [], + types = [], + ids = [], + objectArgs = !params, + param = undefined; + + if (objectArgs) { + params = []; + } + + options.name = this.quotedString(helper); + options.hash = this.popStack(); + + if (this.trackIds) { + options.hashIds = this.popStack(); + } + if (this.stringParams) { + options.hashTypes = this.popStack(); + options.hashContexts = this.popStack(); + } + + var inverse = this.popStack(), + program = this.popStack(); + + // Avoid setting fn and inverse if neither are set. This allows + // helpers to do a check for `if (options.fn)` + if (program || inverse) { + options.fn = program || 'container.noop'; + options.inverse = inverse || 'container.noop'; + } + + // The parameters go on to the stack in order (making sure that they are evaluated in order) + // so we need to pop them off the stack in reverse order + var i = paramSize; + while (i--) { + param = this.popStack(); + params[i] = param; + + if (this.trackIds) { + ids[i] = this.popStack(); + } + if (this.stringParams) { + types[i] = this.popStack(); + contexts[i] = this.popStack(); + } + } + + if (objectArgs) { + options.args = this.source.generateArray(params); + } + + if (this.trackIds) { + options.ids = this.source.generateArray(ids); + } + if (this.stringParams) { + options.types = this.source.generateArray(types); + options.contexts = this.source.generateArray(contexts); + } + + if (this.options.data) { + options.data = 'data'; + } + if (this.useBlockParams) { + options.blockParams = 'blockParams'; + } + return options; + }, + + setupHelperArgs: function setupHelperArgs(helper, paramSize, params, useRegister) { + var options = this.setupParams(helper, paramSize, params); + options = this.objectLiteral(options); + if (useRegister) { + this.useRegister('options'); + params.push('options'); + return ['options=', options]; + } else if (params) { + params.push(options); + return ''; + } else { + return options; + } + } + }; + + (function () { + var reservedWords = ('break else new var' + ' case finally return void' + ' catch for switch while' + ' continue function this with' + ' default if throw' + ' delete in try' + ' do instanceof typeof' + ' abstract enum int short' + ' boolean export interface static' + ' byte extends long super' + ' char final native synchronized' + ' class float package throws' + ' const goto private transient' + ' debugger implements protected volatile' + ' double import public let yield await' + ' null true false').split(' '); + + var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {}; + + for (var i = 0, l = reservedWords.length; i < l; i++) { + compilerWords[reservedWords[i]] = true; + } + })(); + + JavaScriptCompiler.isValidJavaScriptVariableName = function (name) { + return !JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name); + }; + + function strictLookup(requireTerminal, compiler, parts, type) { + var stack = compiler.popStack(), + i = 0, + len = parts.length; + if (requireTerminal) { + len--; + } + + for (; i < len; i++) { + stack = compiler.nameLookup(stack, parts[i], type); + } + + if (requireTerminal) { + return [compiler.aliasable('container.strict'), '(', stack, ', ', compiler.quotedString(parts[i]), ')']; + } else { + return stack; + } + } + + exports['default'] = JavaScriptCompiler; + module.exports = exports['default']; + +/***/ }, +/* 29 */ +/***/ function(module, exports, __webpack_require__) { + + /* global define */ + 'use strict'; + + exports.__esModule = true; + + var _utils = __webpack_require__(5); + + var SourceNode = undefined; + + try { + /* istanbul ignore next */ + if (false) { + // We don't support this in AMD environments. For these environments, we asusme that + // they are running on the browser and thus have no need for the source-map library. + var SourceMap = require('source-map'); + SourceNode = SourceMap.SourceNode; + } + } catch (err) {} + /* NOP */ + + /* istanbul ignore if: tested but not covered in istanbul due to dist build */ + if (!SourceNode) { + SourceNode = function (line, column, srcFile, chunks) { + this.src = ''; + if (chunks) { + this.add(chunks); + } + }; + /* istanbul ignore next */ + SourceNode.prototype = { + add: function add(chunks) { + if (_utils.isArray(chunks)) { + chunks = chunks.join(''); + } + this.src += chunks; + }, + prepend: function prepend(chunks) { + if (_utils.isArray(chunks)) { + chunks = chunks.join(''); + } + this.src = chunks + this.src; + }, + toStringWithSourceMap: function toStringWithSourceMap() { + return { code: this.toString() }; + }, + toString: function toString() { + return this.src; + } + }; + } + + function castChunk(chunk, codeGen, loc) { + if (_utils.isArray(chunk)) { + var ret = []; + + for (var i = 0, len = chunk.length; i < len; i++) { + ret.push(codeGen.wrap(chunk[i], loc)); + } + return ret; + } else if (typeof chunk === 'boolean' || typeof chunk === 'number') { + // Handle primitives that the SourceNode will throw up on + return chunk + ''; + } + return chunk; + } + + function CodeGen(srcFile) { + this.srcFile = srcFile; + this.source = []; + } + + CodeGen.prototype = { + isEmpty: function isEmpty() { + return !this.source.length; + }, + prepend: function prepend(source, loc) { + this.source.unshift(this.wrap(source, loc)); + }, + push: function push(source, loc) { + this.source.push(this.wrap(source, loc)); + }, + + merge: function merge() { + var source = this.empty(); + this.each(function (line) { + source.add([' ', line, '\n']); + }); + return source; + }, + + each: function each(iter) { + for (var i = 0, len = this.source.length; i < len; i++) { + iter(this.source[i]); + } + }, + + empty: function empty() { + var loc = this.currentLocation || { start: {} }; + return new SourceNode(loc.start.line, loc.start.column, this.srcFile); + }, + wrap: function wrap(chunk) { + var loc = arguments.length <= 1 || arguments[1] === undefined ? this.currentLocation || { start: {} } : arguments[1]; + + if (chunk instanceof SourceNode) { + return chunk; + } + + chunk = castChunk(chunk, this, loc); + + return new SourceNode(loc.start.line, loc.start.column, this.srcFile, chunk); + }, + + functionCall: function functionCall(fn, type, params) { + params = this.generateList(params); + return this.wrap([fn, type ? '.' + type + '(' : '(', params, ')']); + }, + + quotedString: function quotedString(str) { + return '"' + (str + '').replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4 + .replace(/\u2029/g, '\\u2029') + '"'; + }, + + objectLiteral: function objectLiteral(obj) { + var pairs = []; + + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + var value = castChunk(obj[key], this); + if (value !== 'undefined') { + pairs.push([this.quotedString(key), ':', value]); + } + } + } + + var ret = this.generateList(pairs); + ret.prepend('{'); + ret.add('}'); + return ret; + }, + + generateList: function generateList(entries) { + var ret = this.empty(); + + for (var i = 0, len = entries.length; i < len; i++) { + if (i) { + ret.add(','); + } + + ret.add(castChunk(entries[i], this)); + } + + return ret; + }, + + generateArray: function generateArray(entries) { + var ret = this.generateList(entries); + ret.prepend('['); + ret.add(']'); + + return ret; + } + }; + + exports['default'] = CodeGen; + module.exports = exports['default']; + +/***/ } +/******/ ]) +}); +; \ No newline at end of file diff --git a/data/web/common/style.css b/data/web/common/style.css new file mode 100644 index 0000000000..ac82e9fe77 --- /dev/null +++ b/data/web/common/style.css @@ -0,0 +1,197 @@ +/* Documentation */ + +.documentation-name, .documentation-name:hover, .documentation-name:focus { + text-decoration: none; + color: #333; + outline: none; +} + +.documentation-item { + background-color: #f4f4f4; + border-left: 2px solid #888; + padding-left: 10px; + padding-top: 5px; + padding-right: 5px; + margin-bottom: 5px; +} + +.documentation-item .documentation-item { + border-left: 2px solid #f00; + background-color: #fff; +} + +.documentation-item .documentation-item .documentation-item { + border-left: 2px solid #080; + background-color: #f4f4f4; +} + +.documentation-item .documentation-item .documentation-item .documentation-item { + border-left: 2px solid #00f; + background-color: #fff; +} + +.documentation-item.remote-scripting { + border-left: 2px solid #4c1315; + background-color: #fcdcdc; + color: #4c1315; +} + +.documentation-item.local-scripting { + border-left: 2px solid #2d4256; + background-color: #dcf1f9; + color: #2d4256; +} + +.documentation-type { + color: #888; + font-size: 0.8em; + font-style: italic; +} + +.documentation-key { + color: #333; + font-weight: bold; +} + +.documentation-description { + font-size: 0.9em; +} + +.documentation-container { + font-size: 1.2em; +} + +.documentation-small { + font-size: 0.8em; +} + + +/*! + * Start Bootstrap - Simple Sidebar (http://startbootstrap.com/) + * Copyright 2013-2016 Start Bootstrap + * Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap/blob/gh-pages/LICENSE) + */ + + body { + overflow-x: hidden; + } + +/* Toggle Styles */ + +#wrapper { + padding-left: 0; + -webkit-transition: all 0.5s ease; + -moz-transition: all 0.5s ease; + -o-transition: all 0.5s ease; + transition: all 0.5s ease; +} + +#wrapper.toggled { + padding-left: 280px; +} + +#sidebar-wrapper { + z-index: 1000; + position: fixed; + left: 280px; + width: 0; + height: 100%; + margin-left: -280px; + overflow-y: auto; + background: #000; + -webkit-transition: all 0.5s ease; + -moz-transition: all 0.5s ease; + -o-transition: all 0.5s ease; + transition: all 0.5s ease; +} + +#wrapper.toggled #sidebar-wrapper { + width: 280px; +} + +#page-content-wrapper { + width: 100%; + position: absolute; + padding: 15px; +} + +#wrapper.toggled #page-content-wrapper { + position: absolute; + margin-right: -280px; +} + +/* Sidebar Styles */ + +.sidebar-nav { + position: absolute; + top: 0; + width: 280px; + margin: 0; + padding: 0; + list-style: none; +} + +.sidebar-nav li { + text-indent: 20px; + line-height: 40px; +} + +.sidebar-nav li a { + display: block; + text-decoration: none; + color: #999999; +} + +.sidebar-nav li a:hover { + text-decoration: none; + color: #fff; + background: rgba(255,255,255,0.2); +} + +.sidebar-nav li a:active, +.sidebar-nav li a:focus { + text-decoration: none; +} + +.sidebar-nav > .sidebar-brand { + height: 65px; + font-size: 18px; + line-height: 60px; +} + +.sidebar-nav > .sidebar-brand a { + color: #999999; +} + +.sidebar-nav > .sidebar-brand a:hover { + color: #fff; + background: none; +} + +@media(min-width:768px) { + #wrapper { + padding-left: 280px; + } + + #wrapper.toggled { + padding-left: 0; + } + + #sidebar-wrapper { + width: 280px; + } + + #wrapper.toggled #sidebar-wrapper { + width: 0; + } + + #page-content-wrapper { + padding: 20px; + position: relative; + } + + #wrapper.toggled #page-content-wrapper { + position: relative; + margin-right: 0; + } +} \ No newline at end of file diff --git a/data/web/documentation/documentation.hbs b/data/web/documentation/documentation.hbs new file mode 100644 index 0000000000..2b7bbbd84d --- /dev/null +++ b/data/web/documentation/documentation.hbs @@ -0,0 +1,29 @@ +{{#each entries}} +
+
+
+

+ + {{type}} + {{key}} + {{#if optional}} + (Optional) + {{/if}} + +

+

{{description}}

+

{{documentation}}

+ {{#with restrictions}} + {{>documentation}} + {{/with}} + {{#if reference}} + {{#if reference.found}} +

An object of type '{{reference.name}}'

+ {{else}} +

Missing reference

+ {{/if}} + {{/if}} +
+
+
+{{/each}} diff --git a/data/web/documentation/main.hbs b/data/web/documentation/main.hbs new file mode 100644 index 0000000000..e96f942df9 --- /dev/null +++ b/data/web/documentation/main.hbs @@ -0,0 +1,32 @@ +
+ + +
+
+

OpenSpace Documentation

+

Version: {{version.[0]}}.{{version.[1]}}.{{version.[2]}}

+ + {{#each documentation}} +
+
+

{{name}}

+ {{> documentation}} +
+
+ {{/each}} +
+
+
diff --git a/data/web/documentation/script.js b/data/web/documentation/script.js new file mode 100644 index 0000000000..f9af37e558 --- /dev/null +++ b/data/web/documentation/script.js @@ -0,0 +1,32 @@ +window.onload = function () { + var mainTemplateElement = document.getElementById('mainTemplate'); + var mainTemplate = Handlebars.compile(mainTemplateElement.innerHTML); + + var documentationTemplateElement = document.getElementById('documentationTemplate'); + Handlebars.registerPartial('documentation', documentationTemplateElement.innerHTML); + + Handlebars.registerHelper('urlify', function(options, context) { + var data = context.data; + var identifier = options.replace(" ", "-").toLowerCase(); + + while (data = data._parent) { + if (data.key !== undefined) { + identifier = data.key + "-" + identifier; + } + } + + return identifier; + }); + + documentation.sort(function (a, b) { + return a.name < b.name ? -1 : (a.name > b.name ? 1 : 0); + }); + + var data = { + documentation: documentation, + version: version + } + + var contents = mainTemplate(data); + document.body.innerHTML = contents; +} \ No newline at end of file diff --git a/data/web/factories/factory.hbs b/data/web/factories/factory.hbs new file mode 100644 index 0000000000..ea23b014fc --- /dev/null +++ b/data/web/factories/factory.hbs @@ -0,0 +1,13 @@ +{{#each classes}} +
+
+ +
+
+{{/each}} diff --git a/data/web/factories/main.hbs b/data/web/factories/main.hbs new file mode 100644 index 0000000000..56f1a3187d --- /dev/null +++ b/data/web/factories/main.hbs @@ -0,0 +1,35 @@ +
+ + +
+
+

OpenSpace Factories

+

Version: {{version.[0]}}.{{version.[1]}}.{{version.[2]}}

+ {{#each factories}} +
+
+

+ + {{name}} + +

+ {{> factory}} +
+
+ {{/each}} +
+
+
diff --git a/data/web/factories/script.js b/data/web/factories/script.js new file mode 100644 index 0000000000..4776d5656e --- /dev/null +++ b/data/web/factories/script.js @@ -0,0 +1,32 @@ +window.onload = function () { + var mainTemplateElement = document.getElementById('mainTemplate'); + var mainTemplate = Handlebars.compile(mainTemplateElement.innerHTML); + + var factoryTemplateElement = document.getElementById('factoryTemplate'); + Handlebars.registerPartial('factory', factoryTemplateElement.innerHTML); + + Handlebars.registerHelper('urlify', function(options, context) { + var data = context.data; + var identifier = options.replace(" ", "-").toLowerCase(); + + while (data = data._parent) { + if (data.key !== undefined) { + identifier = data.key + "-" + identifier; + } + } + + return identifier; + }); + + factories.sort(function (a, b) { + return a.name < b.name ? -1 : (a.name > b.name ? 1 : 0); + }); + + var data = { + factories: factories, + version: version + } + + var contents = mainTemplate(data); + document.body.innerHTML = contents; +} \ No newline at end of file diff --git a/data/web/keybindings/keybinding.hbs b/data/web/keybindings/keybinding.hbs new file mode 100644 index 0000000000..29773e357e --- /dev/null +++ b/data/web/keybindings/keybinding.hbs @@ -0,0 +1,12 @@ + diff --git a/data/web/keybindings/main.hbs b/data/web/keybindings/main.hbs new file mode 100644 index 0000000000..655be726d7 --- /dev/null +++ b/data/web/keybindings/main.hbs @@ -0,0 +1,10 @@ +
+
+

OpenSpace Keybindings

+

Version: {{version.[0]}}.{{version.[1]}}.{{version.[2]}}

+

Generated: {{generationTime}}

+ {{#each keybindings}} + {{> keybinding}} + {{/each}} +
+
\ No newline at end of file diff --git a/data/web/keybindings/script.js b/data/web/keybindings/script.js new file mode 100644 index 0000000000..6b4bdd444e --- /dev/null +++ b/data/web/keybindings/script.js @@ -0,0 +1,33 @@ +window.onload = function () { + var mainTemplateElement = document.getElementById('mainTemplate'); + var mainTemplate = Handlebars.compile(mainTemplateElement.innerHTML); + + var keybindingTemplateElement = document.getElementById('keybindingTemplate'); + Handlebars.registerPartial('keybinding', keybindingTemplateElement.innerHTML); + + Handlebars.registerHelper('urlify', function(options, context) { + var data = context.data; + var identifier = options.replace(" ", "-").toLowerCase(); + + while (data = data._parent) { + if (data.key !== undefined) { + identifier = data.key + "-" + identifier; + } + } + + return identifier; + }); + + keybindings.sort(function (a, b) { + return a.key < b.key ? -1 : (a.key > b.key ? 1 : 0); + }); + + var data = { + keybindings: keybindings, + version: version, + generationTime: generationTime + } + + var contents = mainTemplate(data); + document.body.innerHTML = contents; +} \ No newline at end of file diff --git a/data/web/log/script.js b/data/web/log/script.js new file mode 100644 index 0000000000..fea743117f --- /dev/null +++ b/data/web/log/script.js @@ -0,0 +1,128 @@ +var levels = ['debug', 'info', 'warning', 'error', 'fatal']; +var filterLevel = 0; + +function insertAfter(newNode, referenceNode) { + referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); +} + +function remove(node) { + node.parentNode.removeChild(node); +} + +function scrollTo(selector) { + var element = document.querySelector(selector); + if (element && element.scrollIntoView) { + element.scrollIntoView(); + } +} + +function getLevel(element) { + return levels.findIndex(function (levelString, level) { + var className = 'log-level-' + levelString; + if (element.classList.contains(className)) { + return true; + } + }); +} + +function pluralize(nItems, singular, plural) { + if (nItems === 1) { + return [1, singular].join(' '); + } + plural = plural || [singular, 's'].join(''); + return [nItems.toString(), plural].join(' '); +} + +function scrollLink(content, selector) { + var html = '' + content + ""; + return html; +} + +function getSummary() { + var nFatals = document.getElementsByClassName('log-level-fatal').length; + var nErrors = document.getElementsByClassName('log-level-error').length; + var nWarnings = document.getElementsByClassName('log-level-warning').length; + + if (nFatals > 0) { + return '' + scrollLink(pluralize(nFatals, 'fatal error'), '.log-level-fatal') + + ', ' + scrollLink(pluralize(nErrors, 'other error'), '.log-level-error') + ' and ' + scrollLink(pluralize(nWarnings, 'warning'), '.log-level-warning') + ''; + } else if (nErrors > 0) { + return '' + scrollLink(pluralize(nErrors, 'error'), '.log-level-error') + ' and ' + + scrollLink(pluralize(nWarnings, 'warning'), '.log-level-warning') + ''; + } else if (nWarnings > 0) { + return '' + scrollLink(pluralize(nWarnings, 'warning'), '.log-level-warning') + ''; + } else { + return 'No errors or warnings'; + } +} + +function updateFilter() { + var table = document.getElementsByTagName('table')[0]; + table.classList.remove('hidden'); + + var noMessages = document.getElementById('no-messages'); + if (noMessages) { + remove(noMessages); + } + + var rows = document.getElementsByTagName('tr'); + var nShown = 0; + [].forEach.call(rows, function (row) { + if (row.classList.length === 0) { + return; + } + var rowLevel = getLevel(row); + if (rowLevel >= filterLevel) { + row.classList.remove('hidden'); + nShown++; + } else { + row.classList.add('hidden'); + } + }); + if (nShown === 0) { + var select = document.getElementsByTagName('select')[0]; + var p = document.createElement("p"); + p.id = "no-messages"; + p.innerHTML = "There are no log messages with the level '" + levels[filterLevel] + "' or higher."; + insertAfter(p, select); + table.classList.add('hidden'); + } +} + +window.onload = function () { + var header = document.getElementsByTagName('h1')[0]; + header.innerHTML = "OpenSpace Log"; + + var summary = document.createElement('p'); + summary.innerHTML = getSummary(); + + var select = document.createElement('select'); + select.id = 'filter-level-selector'; + + var selectLabel = document.createElement('label'); + selectLabel.for = 'filter-level-selector'; + selectLabel.innerHTML = "Lowest log level to show: "; + + levels.forEach(function (level) { + var option = document.createElement('option'); + option.value = level; + option.innerHTML = level; + select.appendChild(option); + }); + + insertAfter(summary, header); + insertAfter(selectLabel, summary); + insertAfter(select, selectLabel); + + var preselectedIndex = levels.indexOf(window.location.hash.slice(1)); + if (preselectedIndex >= 0) { + filterLevel = select.selectedIndex = preselectedIndex; + updateFilter(); + } + + select.onchange = function (evt) { + filterLevel = select.selectedIndex; + updateFilter(); + window.location.hash = '#' + select.options[select.selectedIndex].value; + }; +} \ No newline at end of file diff --git a/data/web/log/style.css b/data/web/log/style.css new file mode 100644 index 0000000000..3aa140b30e --- /dev/null +++ b/data/web/log/style.css @@ -0,0 +1,93 @@ +table { + width: 100%; +} + +td, th { + padding: 4px 15px 3px; +} + +.log-date { + width: 8em; +} + +h1 { + padding-left: 15px; +} + +.hidden { + display: none; +} + +p, label { + margin-left: 15px; + margin-bottom: 15px; +} + +label { + margin-right: 0.5em; +} + +.log-level-debug { + background-color: #bbdda9; + border-bottom: 1px solid #7bc142; + color: #265127; +} +.log-level-debug td:first-child { + border-left: 10px solid #7bc142; +} + +thead, .log-level-info { + color: #333333; + background-color: #ffffff; + border-bottom: 1px solid #eaeaea; +} +.log-level-info td:first-child { + border-left: 10px solid #eaeaea; +} + +thead th:first-child { + border-left 10px solid #fff; +} + +.log-level-warning { + color: #3e3115; + background-color: #fef8c3; + border-bottom: 1px solid #efcd3f; +} +.log-level-warning td:first-child { + border-left: 10px solid #efcd3f; +} + +.log-level-error { + color: #4c1315; + background-color: #fcdcdc; + border-bottom: 1px solid #d66767; +} +.log-level-error td:first-child { + border-left: 10px solid #d66767; +} + +.log-level-fatal { + color: #220f21; + background-color: #ff7dc1; + border-bottom: 1px solid #b84398; +} +.log-level-fatal td:first-child { + border-left: 10px solid #b84398; +} + +.summary { + padding: 5px; +} +.summary-warning { + background-color: #fef8c3; +} +.summary-error { + background-color: #fcdcdc; +} +.summary-fatal { + background-color: #ff7dc1; +} +.summary-ok { + background-color: #bbdda9; +} \ No newline at end of file diff --git a/data/web/luascripting/main.hbs b/data/web/luascripting/main.hbs new file mode 100644 index 0000000000..1d67289346 --- /dev/null +++ b/data/web/luascripting/main.hbs @@ -0,0 +1,35 @@ +
+ + +
+
+

OpenSpace Lua Scripting

+

Version: {{version.[0]}}.{{version.[1]}}.{{version.[2]}}

+ {{#each scripting}} + + {{/each}} +
+
+
diff --git a/data/web/luascripting/script.js b/data/web/luascripting/script.js new file mode 100644 index 0000000000..6d43a33b07 --- /dev/null +++ b/data/web/luascripting/script.js @@ -0,0 +1,32 @@ +window.onload = function () { + var mainTemplateElement = document.getElementById('mainTemplate'); + var mainTemplate = Handlebars.compile(mainTemplateElement.innerHTML); + + var scriptingTemplateElement = document.getElementById('scriptingTemplate'); + Handlebars.registerPartial('scripting', scriptingTemplateElement.innerHTML); + + Handlebars.registerHelper('urlify', function(options, context) { + var data = context.data; + var identifier = options.replace(" ", "-").toLowerCase(); + + while (data = data._parent) { + if (data.key !== undefined) { + identifier = data.key + "-" + identifier; + } + } + + return identifier; + }); + + scripting.sort(function (a, b) { + return a.library < b.library ? -1 : (a.library > b.library ? 1 : 0); + }); + + var data = { + scripting: scripting, + version: version + } + + var contents = mainTemplate(data); + document.body.innerHTML = contents; +} \ No newline at end of file diff --git a/data/web/luascripting/scripting.hbs b/data/web/luascripting/scripting.hbs new file mode 100644 index 0000000000..00313e3372 --- /dev/null +++ b/data/web/luascripting/scripting.hbs @@ -0,0 +1,17 @@ +{{#each functions}} +
+ +
+{{/each}} diff --git a/data/web/properties/main.hbs b/data/web/properties/main.hbs new file mode 100644 index 0000000000..fc56bca0b8 --- /dev/null +++ b/data/web/properties/main.hbs @@ -0,0 +1,41 @@ +
+ + +
+
+

OpenSpace Scene Properties

+

Version: {{version.[0]}}.{{version.[1]}}.{{version.[2]}}

+

Scene name: {{sceneFilename}}

+

Generated: {{generationTime}}

+ + {{#each propertyOwners}} +
+
+

{{name}}

+ {{#each properties}} + {{> property}} + {{/each}} + {{#each propertyOwners}} + {{> propertyOwner}} + {{else}} +

{{name}} has no property owners

+ {{/each}} +
+
+ {{/each}} +
+
+
diff --git a/data/web/properties/property.hbs b/data/web/properties/property.hbs new file mode 100644 index 0000000000..b01807229d --- /dev/null +++ b/data/web/properties/property.hbs @@ -0,0 +1,15 @@ +
+
+
+

+ + {{type}} + {{id}} + +

+

{{fullyQualifiedId}} + copy +

+
+
+
diff --git a/data/web/properties/propertyowner.hbs b/data/web/properties/propertyowner.hbs new file mode 100644 index 0000000000..9d0885e0a1 --- /dev/null +++ b/data/web/properties/propertyowner.hbs @@ -0,0 +1,18 @@ +
+
+
+

+ + {{name}} + +

+ {{#each properties}} + {{> property}} + {{/each}} + {{#each propertyOwners}} + {{> propertyOwner}} + {{/each}} +
+
+
+ diff --git a/data/web/properties/script.js b/data/web/properties/script.js new file mode 100644 index 0000000000..f7302a5e0b --- /dev/null +++ b/data/web/properties/script.js @@ -0,0 +1,62 @@ +function copyTextToClipboard(text) { + var textArea = document.createElement("textarea"); + textArea.style.position = 'fixed'; + textArea.style.top = 0; + textArea.style.left = 0; + + textArea.style.width = '2em'; + textArea.style.height = '2em'; + + textArea.style.padding = 0; + + textArea.style.border = 'none'; + textArea.style.outline = 'none'; + textArea.style.boxShadow = 'none'; + + textArea.style.background = 'transparent'; + textArea.value = text; + + document.body.appendChild(textArea); + + textArea.select(); + document.execCommand('copy'); + + document.body.removeChild(textArea); +} + +window.onload = function () { + var mainTemplateElement = document.getElementById('mainTemplate'); + var mainTemplate = Handlebars.compile(mainTemplateElement.innerHTML); + + var propertyOwnerTemplateElement = document.getElementById('propertyOwnerTemplate'); + Handlebars.registerPartial('propertyOwner', propertyOwnerTemplateElement.innerHTML); + + var propertyTemplateElement = document.getElementById('propertyTemplate'); + Handlebars.registerPartial('property', propertyTemplateElement.innerHTML); + + Handlebars.registerHelper('urlify', function(options, context) { + var data = context.data; + var identifier = options.replace(" ", "-").toLowerCase(); + + while (data = data._parent) { + if (data.key !== undefined) { + identifier = data.key + "-" + identifier; + } + } + return identifier; + }); + + propertyOwners.sort(function (a, b) { + return a.name < b.name ? -1 : (a.name > b.name ? 1 : 0); + }); + + var data = { + propertyOwners: propertyOwners, + version: version, + sceneFilename: sceneFilename, + generationTime: generationTime + } + + var contents = mainTemplate(data); + document.body.innerHTML = contents; +} diff --git a/ext/ghoul b/ext/ghoul index 7779a2e87c..f341d33a3b 160000 --- a/ext/ghoul +++ b/ext/ghoul @@ -1 +1 @@ -Subproject commit 7779a2e87c178a2b0a59c03f71b909018b2c4d77 +Subproject commit f341d33a3bf968d7d6304039a111ad295b315939 diff --git a/ext/sgct b/ext/sgct index fb95dc335b..d47e9d6d1d 160000 --- a/ext/sgct +++ b/ext/sgct @@ -1 +1 @@ -Subproject commit fb95dc335ba7d396723fbfeca64aa3b7451376c8 +Subproject commit d47e9d6d1d55a1730a6f3a8f58abee4a4a0b95de diff --git a/include/openspace/documentation/core_registration.h b/include/openspace/documentation/core_registration.h index d29259daf2..5688a6c24e 100644 --- a/include/openspace/documentation/core_registration.h +++ b/include/openspace/documentation/core_registration.h @@ -22,17 +22,17 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __CORE_REGISTRATION_H__ -#define __CORE_REGISTRATION_H__ +#ifndef __OPENSPACE_CORE___REGISTRATION___H__ +#define __OPENSPACE_CORE___REGISTRATION___H__ namespace openspace { -namespace documentation { -class DocumentationEngine; +namespace documentation { class DocumentationEngine; } +namespace scripting { class ScriptEngine; } void registerCoreClasses(documentation::DocumentationEngine& engine); +void registerCoreClasses(scripting::ScriptEngine& engine); -} // namespace documentation } // namespace openspace -#endif // __CORE_REGISTRATION_H__ +#endif // __OPENSPACE_CORE___REGISTRATION___H__ diff --git a/include/openspace/documentation/documentation.h b/include/openspace/documentation/documentation.h index 39015df384..2c4e39fcf2 100644 --- a/include/openspace/documentation/documentation.h +++ b/include/openspace/documentation/documentation.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __DOCUMENTATION_H__ -#define __DOCUMENTATION_H__ +#ifndef __OPENSPACE_CORE___DOCUMENTATION___H__ +#define __OPENSPACE_CORE___DOCUMENTATION___H__ #include #include @@ -317,6 +317,6 @@ namespace std { std::string to_string(openspace::documentation::TestResult::Offense::Reason reason); -} // namespace +} // namespace std -#endif // __DOCUMENTATION_H__ +#endif // __OPENSPACE_CORE___DOCUMENTATION___H__ diff --git a/include/openspace/documentation/documentationengine.h b/include/openspace/documentation/documentationengine.h index 7f8851686b..95fcca5f98 100644 --- a/include/openspace/documentation/documentationengine.h +++ b/include/openspace/documentation/documentationengine.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __DOCUMENTATIONENGINE_H__ -#define __DOCUMENTATIONENGINE_H__ +#ifndef __OPENSPACE_CORE___DOCUMENTATIONENGINE___H__ +#define __OPENSPACE_CORE___DOCUMENTATIONENGINE___H__ #include @@ -99,4 +99,4 @@ private: #define DocEng (openspace::documentation::DocumentationEngine::ref()) -#endif // __DOCUMENTATIONENGINE_H__ +#endif // __OPENSPACE_CORE___DOCUMENTATIONENGINE___H__ diff --git a/include/openspace/documentation/verifier.h b/include/openspace/documentation/verifier.h index 1adcc9b140..22ae0452d5 100644 --- a/include/openspace/documentation/verifier.h +++ b/include/openspace/documentation/verifier.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __VERIFIER_H__ -#define __VERIFIER_H__ +#ifndef __OPENSPACE_CORE___VERIFIER___H__ +#define __OPENSPACE_CORE___VERIFIER___H__ #include @@ -199,6 +199,19 @@ struct TableVerifier : public TemplateVerifier { Exhaustive exhaustive; }; +/** + * A Verifier that checks whether all values contained in a Table are of type \c string. + */ +struct StringListVerifier : public TableVerifier { + /** + * Constructor for a StringListVerifier. + * \param elementDocumentation The documentation for each string in the list + */ + StringListVerifier(std::string elementDocumentation = ""); + + std::string type() const override; +}; + //---------------------------------------------------------------------------------------- // Vector verifiers //---------------------------------------------------------------------------------------- @@ -235,6 +248,100 @@ struct Vector4Verifier : public TemplateVerifier>, public VectorVe std::string type() const override; }; +//---------------------------------------------------------------------------------------- +// Matrix verifiers +//---------------------------------------------------------------------------------------- + +/** +* This struct is the base class for all Verifier%s that check for \c glm matrix types. +* The template parameter for the subclasses is the containing type, not the full matrix +* type. For example to check for glm::dmat4x3, one would create a +* Matrix4x3Verifier. +*/ +struct MatrixVerifier {}; + +/** +* This Verifier checks whether the value is of type glm::mat2x2 +*/ +template +struct Matrix2x2Verifier : + public TemplateVerifier>, public MatrixVerifier +{ + std::string type() const override; +}; + +/** +* This Verifier checks whether the value is of type glm::mat2x3 +*/ +template +struct Matrix2x3Verifier : + public TemplateVerifier>, public MatrixVerifier { + std::string type() const override; +}; + +/** +* This Verifier checks whether the value is of type glm::mat2x4 +*/ +template +struct Matrix2x4Verifier : + public TemplateVerifier>, public MatrixVerifier { + std::string type() const override; +}; + +/** +* This Verifier checks whether the value is of type glm::mat3x2 +*/ +template +struct Matrix3x2Verifier : + public TemplateVerifier>, public MatrixVerifier { + std::string type() const override; +}; + +/** +* This Verifier checks whether the value is of type glm::mat3x3 +*/ +template +struct Matrix3x3Verifier : + public TemplateVerifier>, public MatrixVerifier { + std::string type() const override; +}; + +/** +* This Verifier checks whether the value is of type glm::mat3x4 +*/ +template +struct Matrix3x4Verifier : + public TemplateVerifier>, public MatrixVerifier { + std::string type() const override; +}; + +/** +* This Verifier checks whether the value is of type glm::mat4x2 +*/ +template +struct Matrix4x2Verifier : + public TemplateVerifier>, public MatrixVerifier { + std::string type() const override; +}; + +/** +* This Verifier checks whether the value is of type glm::mat4x3 +*/ +template +struct Matrix4x3Verifier : + public TemplateVerifier>, public MatrixVerifier { + std::string type() const override; +}; + +/** +* This Verifier checks whether the value is of type glm::mat4x4 +*/ +template +struct Matrix4x4Verifier : + public TemplateVerifier>, public MatrixVerifier { + std::string type() const override; +}; + //---------------------------------------------------------------------------------------- // Operator verifiers //---------------------------------------------------------------------------------------- @@ -840,6 +947,28 @@ using IntVector4Verifier = Vector4Verifier; /// A short-hand definition for a Verifier checking for glm::dvec4 using DoubleVector4Verifier = Vector4Verifier; +/// A short-hand definition for a Verifier checking for glm::dmat2x2 +using DoubleMatrix2x2Verifier = Matrix2x2Verifier; +using DoubleMatrix2Verifier = DoubleMatrix2x2Verifier; +/// A short-hand definition for a Verifier checking for glm::dmat2x3 +using DoubleMatrix2x3Verifier = Matrix2x3Verifier; +/// A short-hand definition for a Verifier checking for glm::dmat2x4 +using DoubleMatrix2x4Verifier = Matrix2x4Verifier; +/// A short-hand definition for a Verifier checking for glm::dmat3x2 +using DoubleMatrix3x2Verifier = Matrix3x2Verifier; +/// A short-hand definition for a Verifier checking for glm::dmat3x3 +using DoubleMatrix3x3Verifier = Matrix3x3Verifier; +using DoubleMatrix3Verifier = DoubleMatrix3x3Verifier; +/// A short-hand definition for a Verifier checking for glm::dmat3x4 +using DoubleMatrix3x4Verifier = Matrix3x4Verifier; +/// A short-hand definition for a Verifier checking for glm::dmat4x2 +using DoubleMatrix4x2Verifier = Matrix4x2Verifier; +/// A short-hand definition for a Verifier checking for glm::dmat4x3 +using DoubleMatrix4x3Verifier = Matrix4x3Verifier; +/// A short-hand definition for a Verifier checking for glm::dmat4x4 +using DoubleMatrix4x4Verifier = Matrix4x4Verifier; +using DoubleMatrix4Verifier = DoubleMatrix4x4Verifier; + /// A short-hand definition for a LessVerifier with a type check for \c int using IntLessVerifier = LessVerifier; /// A short-hand definition for a LessVerifier with a type check for \c double @@ -936,6 +1065,16 @@ extern template struct Vector4Verifier; extern template struct Vector4Verifier; extern template struct Vector4Verifier; +extern template struct Matrix2x2Verifier; +extern template struct Matrix2x3Verifier; +extern template struct Matrix2x4Verifier; +extern template struct Matrix3x2Verifier; +extern template struct Matrix3x3Verifier; +extern template struct Matrix3x4Verifier; +extern template struct Matrix4x2Verifier; +extern template struct Matrix4x3Verifier; +extern template struct Matrix4x4Verifier; + extern template struct LessVerifier; extern template struct LessVerifier; extern template struct LessEqualVerifier; @@ -1002,4 +1141,4 @@ extern template struct DeprecatedVerifier; #include "verifier.inl" -#endif // __VERIFIER_H__ +#endif // __OPENSPACE_CORE___VERIFIER___H__ diff --git a/include/openspace/documentation/verifier.inl b/include/openspace/documentation/verifier.inl index 22770b5002..8df5f6e3f6 100644 --- a/include/openspace/documentation/verifier.inl +++ b/include/openspace/documentation/verifier.inl @@ -50,7 +50,7 @@ TestResult TemplateVerifier::operator()(const ghoul::Dictionary& dict, template std::string TemplateVerifier::documentation() const { - return "Type testing of '" + type() + "'"; + return "Value of type '" + type() + "'"; } template @@ -74,6 +74,69 @@ std::string Vector4Verifier::type() const { return "Vector4<"s + typeid(T).name() + ">"; } +template +std::string Matrix2x2Verifier::type() const { + using namespace std::string_literals; + + return "Matrix2x2<"s + typeid(T).name() + ">"; +} + +template +std::string Matrix2x3Verifier::type() const { + using namespace std::string_literals; + + return "Matrix2x3<"s + typeid(T).name() + ">"; +} + +template +std::string Matrix2x4Verifier::type() const { + using namespace std::string_literals; + + return "Matrix2x4<"s + typeid(T).name() + ">"; +} + +template +std::string Matrix3x2Verifier::type() const { + using namespace std::string_literals; + + return "Matrix3x2<"s + typeid(T).name() + ">"; +} + +template +std::string Matrix3x3Verifier::type() const { + using namespace std::string_literals; + + return "Matrix3x3<"s + typeid(T).name() + ">"; +} + +template +std::string Matrix3x4Verifier::type() const { + using namespace std::string_literals; + + return "Matrix3x4<"s + typeid(T).name() + ">"; +} + +template +std::string Matrix4x2Verifier::type() const { + using namespace std::string_literals; + + return "Matrix4x2<"s + typeid(T).name() + ">"; +} + +template +std::string Matrix4x3Verifier::type() const { + using namespace std::string_literals; + + return "Matrix4x3<"s + typeid(T).name() + ">"; +} + +template +std::string Matrix4x4Verifier::type() const { + using namespace std::string_literals; + + return "Matrix4x4<"s + typeid(T).name() + ">"; +} + template OperatorVerifier::OperatorVerifier(typename T::Type value) : value(std::move(value)) diff --git a/include/openspace/engine/configurationmanager.h b/include/openspace/engine/configurationmanager.h index 06b46babef..3fef274c62 100644 --- a/include/openspace/engine/configurationmanager.h +++ b/include/openspace/engine/configurationmanager.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __CONFIGURATIONMANAGER_H__ -#define __CONFIGURATIONMANAGER_H__ +#ifndef __OPENSPACE_CORE___CONFIGURATIONMANAGER___H__ +#define __OPENSPACE_CORE___CONFIGURATIONMANAGER___H__ #include @@ -97,6 +97,9 @@ public: /// The key that stores the time (in seconds) that the application will wait before /// shutting down after the shutdown call is made static const std::string KeyShutdownCountdown; + /// The key that stores whether the onscreen text should be scaled to the window size + /// or the window resolution + static const std::string KeyOnScreenTextScaling; /// The key that stores whether the master node should perform rendering just function /// as a pure manager static const std::string KeyDisableMasterRendering; @@ -106,6 +109,21 @@ public: /// The key that stores the switch for enabling/disabling the rendering on a master /// computer static const std::string KeyRenderingMethod; + /// The key that determines whether a new cache folder is used for each scene file + static const std::string KeyPerSceneCache; + /// The key that stores the http proxy settings for the downloadmanager + static const std::string KeyHttpProxy; + /// The key that stores the address of the http proxy + static const std::string PartHttpProxyAddress; + /// The key that stores the port of the http proxy + static const std::string PartHttpProxyPort; + /// The key that stores the authentication method of the http proxy + static const std::string PartHttpProxyAuthentication; + /// The key that stores the username to use for authentication to access the http proxy + static const std::string PartHttpProxyUser; + /// The key that stores the password to use for authentication to access the http proxy + static const std::string PartHttpProxyPassword; + /** * Iteratively walks the directory structure starting with \p filename to find the @@ -149,4 +167,4 @@ private: } // namespace openspace -#endif // __CONFIGURATIONMANAGER_H__ +#endif // __OPENSPACE_CORE___CONFIGURATIONMANAGER___H__ diff --git a/include/openspace/engine/downloadmanager.h b/include/openspace/engine/downloadmanager.h index cabcf0a14b..900c99eebc 100644 --- a/include/openspace/engine/downloadmanager.h +++ b/include/openspace/engine/downloadmanager.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __DOWNLOADMANAGER_H__ -#define __DOWNLOADMANAGER_H__ +#ifndef __OPENSPACE_CORE___DOWNLOADMANAGER___H__ +#define __OPENSPACE_CORE___DOWNLOADMANAGER___H__ #include #include @@ -119,4 +119,4 @@ private: } // namespace openspace -#endif // __DOWNLOADMANAGER_H__ +#endif // __OPENSPACE_CORE___DOWNLOADMANAGER___H__ diff --git a/include/openspace/engine/logfactory.h b/include/openspace/engine/logfactory.h index d3067f213c..a2fb2b3c21 100644 --- a/include/openspace/engine/logfactory.h +++ b/include/openspace/engine/logfactory.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __LOGFACTORY_H__ -#define __LOGFACTORY_H__ +#ifndef __OPENSPACE_CORE___LOGFACTORY___H__ +#define __OPENSPACE_CORE___LOGFACTORY___H__ #include @@ -55,4 +55,4 @@ std::unique_ptr createLog(const ghoul::Dictionary& dictiona } // namespace openspace -#endif // __LOGFACTORY_H__ +#endif // __OPENSPACE_CORE___LOGFACTORY___H__ diff --git a/include/openspace/engine/moduleengine.h b/include/openspace/engine/moduleengine.h index 6075ebe125..df40f23983 100644 --- a/include/openspace/engine/moduleengine.h +++ b/include/openspace/engine/moduleengine.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __MODULEENGINE_H__ -#define __MODULEENGINE_H__ +#ifndef __OPENSPACE_CORE___MODULEENGINE___H__ +#define __OPENSPACE_CORE___MODULEENGINE___H__ #include #include @@ -75,6 +75,14 @@ public: */ std::vector modules() const; + /** + * Returns the combined minimum OpenGL version. The return value is the maximum + * version of all registered modules' OpenGL versions. + * \return The combined minimum OpenGL version + */ + ghoul::systemcapabilities::OpenGLCapabilitiesComponent::Version + requiredOpenGLVersion() const; + /** * Returns the Lua library that contains all Lua functions available to affect the * modules. @@ -88,4 +96,4 @@ private: } // namespace openspace -#endif // __MODULEENGINE_H__ +#endif // __OPENSPACE_CORE___MODULEENGINE___H__ diff --git a/include/openspace/engine/openspaceengine.h b/include/openspace/engine/openspaceengine.h index 144a9fa8a3..9070e07f92 100644 --- a/include/openspace/engine/openspaceengine.h +++ b/include/openspace/engine/openspaceengine.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __OPENSPACEENGINE_H__ -#define __OPENSPACEENGINE_H__ +#ifndef __OPENSPACE_CORE___OPENSPACEENGINE___H__ +#define __OPENSPACE_CORE___OPENSPACEENGINE___H__ #include #include @@ -51,12 +51,13 @@ class RenderEngine; class ModuleEngine; class WindowWrapper; class SettingsEngine; +class TimeManager; class SyncEngine; +class ParallelConnection; namespace interaction { class InteractionHandler; } namespace gui { class GUI; } //namespace scripting { class ScriptEngine; } -namespace network { class ParallelConnection; } namespace properties { class PropertyOwner; } namespace scripting { struct LuaLibrary; } namespace scripting { class ScriptScheduler; } @@ -85,11 +86,12 @@ public: NetworkEngine& networkEngine(); LuaConsole& console(); ModuleEngine& moduleEngine(); - network::ParallelConnection& parallelConnection(); + ParallelConnection& parallelConnection(); properties::PropertyOwner& globalPropertyOwner(); WindowWrapper& windowWrapper(); ghoul::fontrendering::FontManager& fontManager(); DownloadManager& downloadManager(); + TimeManager& timeManager(); #ifdef OPENSPACE_MODULE_ONSCREENGUI_ENABLED gui::GUI& gui(); @@ -114,6 +116,7 @@ public: void enableBarrier(); void disableBarrier(); + void writeDocumentation(); void toggleShutdownMode(); bool useBusyWaitForDecode(); @@ -150,11 +153,12 @@ private: std::unique_ptr _console; std::unique_ptr _moduleEngine; std::unique_ptr _settingsEngine; + std::unique_ptr _timeManager; std::unique_ptr _downloadManager; #ifdef OPENSPACE_MODULE_ONSCREENGUI_ENABLED std::unique_ptr _gui; #endif - std::unique_ptr _parallelConnection; + std::unique_ptr _parallelConnection; std::unique_ptr _windowWrapper; std::unique_ptr _fontManager; @@ -181,6 +185,6 @@ private: #define OsEng (openspace::OpenSpaceEngine::ref()) -} // namespace openspace +} // namespace openspace -#endif // __OPENSPACEENGINE_H__ +#endif // __OPENSPACE_CORE___OPENSPACEENGINE___H__ diff --git a/include/openspace/engine/settingsengine.h b/include/openspace/engine/settingsengine.h index a3a962eac6..e42ab81f23 100644 --- a/include/openspace/engine/settingsengine.h +++ b/include/openspace/engine/settingsengine.h @@ -22,12 +22,14 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SETTINGSENGINE_H__ -#define __SETTINGSENGINE_H__ +#ifndef __OPENSPACE_CORE___SETTINGSENGINE___H__ +#define __OPENSPACE_CORE___SETTINGSENGINE___H__ #include -#include + #include +#include +#include #include @@ -61,9 +63,10 @@ private: properties::BoolProperty _busyWaitForDecode; properties::BoolProperty _logSGCTOutOfOrderErrors; properties::BoolProperty _useDoubleBuffering; + properties::BoolProperty _spiceUseExceptions; }; } // namespace openspace -#endif //#ifndef __SETTINGSENGINE_H__ +#endif // __OPENSPACE_CORE___SETTINGSENGINE___H__ diff --git a/include/openspace/engine/syncengine.h b/include/openspace/engine/syncengine.h index c10a7833d0..aa87c909f9 100644 --- a/include/openspace/engine/syncengine.h +++ b/include/openspace/engine/syncengine.h @@ -22,14 +22,12 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SYNCENGINE_H__ -#define __SYNCENGINE_H__ - +#ifndef __OPENSPACE_CORE___SYNCENGINE___H__ +#define __OPENSPACE_CORE___SYNCENGINE___H__ #include #include - namespace openspace { class Syncable; @@ -103,4 +101,4 @@ private: } // namespace openspace -#endif //#ifndef __SYNCENGINE_H__ +#endif // __OPENSPACE_CORE___SYNCENGINE___H__ diff --git a/include/openspace/engine/wrapper/sgctwindowwrapper.h b/include/openspace/engine/wrapper/sgctwindowwrapper.h index a9c4778005..377bda3f42 100644 --- a/include/openspace/engine/wrapper/sgctwindowwrapper.h +++ b/include/openspace/engine/wrapper/sgctwindowwrapper.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SGCTWINDOWWRAPPER_H__ -#define __SGCTWINDOWWRAPPER_H__ +#ifndef __OPENSPACE_CORE___SGCTWINDOWWRAPPER___H__ +#define __OPENSPACE_CORE___SGCTWINDOWWRAPPER___H__ #include @@ -49,6 +49,7 @@ public: glm::ivec2 currentWindowSize() const override; glm::ivec2 currentWindowResolution() const override; glm::ivec2 currentDrawBufferResolution() const override; + glm::vec2 dpiScaling() const override; int currentNumberOfAaSamples() const override; bool isRegularRendering() const override; @@ -74,4 +75,4 @@ public: } // namespace openspace -#endif // __SGCTWINDOWWRAPPER_H__ +#endif // __OPENSPACE_CORE___SGCTWINDOWWRAPPER___H__ diff --git a/include/openspace/engine/wrapper/windowwrapper.h b/include/openspace/engine/wrapper/windowwrapper.h index af26f105b4..89c92121f9 100644 --- a/include/openspace/engine/wrapper/windowwrapper.h +++ b/include/openspace/engine/wrapper/windowwrapper.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __WINDOWWRAPPER_H__ -#define __WINDOWWRAPPER_H__ +#ifndef __OPENSPACE_CORE___WINDOWWRAPPER___H__ +#define __OPENSPACE_CORE___WINDOWWRAPPER___H__ #include #include @@ -138,6 +138,13 @@ public: * \return The resolution of the currently active window in pixel coordinates */ virtual glm::ivec2 currentDrawBufferResolution() const; + + /** + * Returns the DPI scaling factor for the current window. This is normally 1 on all + * regular monitors and 2 on Retina screens. + * \return The DPI scaling factor for the current window + */ + virtual glm::vec2 dpiScaling() const; /** * Returns the number of anti-aliasing samples used in the current window. @@ -251,4 +258,4 @@ public: } // namespace openspace -#endif // _WINDOW_H__ +#endif // __OPENSPACE_CORE___WINDOWWRAPPER___H__ diff --git a/include/openspace/interaction/controller.h b/include/openspace/interaction/controller.h index 3afb45b8df..5daf93cd01 100644 --- a/include/openspace/interaction/controller.h +++ b/include/openspace/interaction/controller.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __CONTROLLER_H__ -#define __CONTROLLER_H__ +#ifndef __OPENSPACE_CORE___CONTROLLER___H__ +#define __OPENSPACE_CORE___CONTROLLER___H__ #include @@ -50,4 +50,4 @@ protected: } // namespace interaction } // namespace openspace -#endif // __CONTROLLER_H__ +#endif // __OPENSPACE_CORE___CONTROLLER___H__ diff --git a/include/openspace/interaction/deviceidentifier.h b/include/openspace/interaction/deviceidentifier.h index e021fac9aa..828bf4fa42 100644 --- a/include/openspace/interaction/deviceidentifier.h +++ b/include/openspace/interaction/deviceidentifier.h @@ -1,5 +1,29 @@ -#ifndef DEVICEIDENTIFIER_H -#define DEVICEIDENTIFIER_H +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___DEVICEIDENTIFIER___H__ +#define __OPENSPACE_CORE___DEVICEIDENTIFIER___H__ // std includes #include @@ -52,4 +76,4 @@ private: } // namespace openspace -#endif +#endif // __OPENSPACE_CORE___DEVICEIDENTIFIER___H__ diff --git a/include/openspace/interaction/externalcontrol/externalconnectioncontroller.h b/include/openspace/interaction/externalcontrol/externalconnectioncontroller.h deleted file mode 100644 index 6af23c76b4..0000000000 --- a/include/openspace/interaction/externalcontrol/externalconnectioncontroller.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef EXTERNALCONNECTIONCONTROLLER_H -#define EXTERNALCONNECTIONCONTROLLER_H - -#include -#include - -namespace openspace { - -class ExternalConnectionController: public ExternalControl { -public: - - // constructors & destructor - ExternalConnectionController(); - ~ExternalConnectionController(); - -private: - - std::vector controllers; - -}; - -} // namespace openspace - -#endif diff --git a/include/openspace/interaction/externalcontrol/externalcontrol.h b/include/openspace/interaction/externalcontrol/externalcontrol.h deleted file mode 100644 index 10dad0815e..0000000000 --- a/include/openspace/interaction/externalcontrol/externalcontrol.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef EXTERNALCONTROL_H -#define EXTERNALCONTROL_H - -#include -#include -#include - -namespace openspace { - -class ExternalControl { -public: - - // constructors & destructor - ExternalControl(); - virtual ~ExternalControl(); - - virtual void update(); - - void rotate(const glm::quat &rotation); - void orbit(const glm::quat &rotation); - void distance(const PowerScaledScalar &distance); - - -protected: -}; - -} // namespace openspace - -#endif diff --git a/include/openspace/interaction/externalcontrol/joystickexternalcontrol.h b/include/openspace/interaction/externalcontrol/joystickexternalcontrol.h deleted file mode 100644 index 4182d3c102..0000000000 --- a/include/openspace/interaction/externalcontrol/joystickexternalcontrol.h +++ /dev/null @@ -1,28 +0,0 @@ -//#ifndef JOYSTICKEXTERNALCONTROL_H -//#define JOYSTICKEXTERNALCONTROL_H -// -//#include "externalcontrol/pythonexternalcontrol.h" -// -//namespace openspace { -// -//class JoystickExternalControl: public PythonExternalControl { -//public: -// -// // constructors & destructor -// JoystickExternalControl(const char *filename); -// ~JoystickExternalControl(); -// -// void setInputDevice(const int device); -// void update(); -// -//private: -// -// // joystick -// int inputDevice_; -// int numberOfButtons_; -// int numberOfAxes_; -//}; -// -//} // namespace openspace -// -//#endif \ No newline at end of file diff --git a/include/openspace/interaction/externalcontrol/keyboardexternalcontrol.h b/include/openspace/interaction/externalcontrol/keyboardexternalcontrol.h deleted file mode 100644 index 9a01732944..0000000000 --- a/include/openspace/interaction/externalcontrol/keyboardexternalcontrol.h +++ /dev/null @@ -1,25 +0,0 @@ -//#ifndef KEYBOARDEXTERNALCONTROL_H -//#define KEYBOARDEXTERNALCONTROL_H -// -//#include "externalcontrol/pythonexternalcontrol.h" -// -//namespace openspace { -// -//class KeyboardExternalControl: public PythonExternalControl { -//public: -// -// // constructors & destructor -// KeyboardExternalControl(const char *filename); -// ~KeyboardExternalControl(); -// -// void update(); -// -// void keyboardCallback(int key, int action); -//private: -// int *keys_; -// -//}; -// -//} // namespace openspace -// -//#endif \ No newline at end of file diff --git a/include/openspace/interaction/externalcontrol/mouseexternalcontrol.h b/include/openspace/interaction/externalcontrol/mouseexternalcontrol.h deleted file mode 100644 index cbd5cec7d3..0000000000 --- a/include/openspace/interaction/externalcontrol/mouseexternalcontrol.h +++ /dev/null @@ -1,28 +0,0 @@ -//#ifndef MOUSEEXTERNALCONTROL_H -//#define MOUSEEXTERNALCONTROL_H -// -//#include "externalcontrol/pythonexternalcontrol.h" -// -//namespace openspace { -// -//class MouseExternalControl: public PythonExternalControl { -//public: -// -// // constructors & destructor -// MouseExternalControl(const char *filename); -// ~MouseExternalControl(); -// -// void update(); -// -// void mouseButtonCallback(int key, int action); -// void mousePosCallback(int x, int y); -// void mouseScrollCallback(int pos); -//private: -// -// int x_, y_, pos_, button1_, button2_, button3_; -// -//}; -// -//} // namespace openspace -// -//#endif \ No newline at end of file diff --git a/include/openspace/interaction/externalcontrol/pythonexternalcontrol.h b/include/openspace/interaction/externalcontrol/pythonexternalcontrol.h deleted file mode 100644 index 432f1c6d9a..0000000000 --- a/include/openspace/interaction/externalcontrol/pythonexternalcontrol.h +++ /dev/null @@ -1,35 +0,0 @@ -//#ifndef PYTHONEXTERNALCONTROL_H -//#define PYTHONEXTERNALCONTROL_H -// -//#include -//#include -// -//#include "externalcontrol/externalcontrol.h" -//#include "python/pythonscript.h" -// -//namespace openspace { -// -//class PythonExternalControl: public ExternalControl { -//public: -// -// // constructors & destructor -// PythonExternalControl(const char *filename); -// ~PythonExternalControl(); -// -// static PyMethodDef* getMethodDef(); -// -// void message(const char *text); -// virtual void update(); -// void clear(); -//private: -// PythonScript ps_; -// -//protected: -// void run(); -// int pyarrSize_; -// PyObject **pyarr_; -//}; -// -//} // namespace openspace -// -//#endif \ No newline at end of file diff --git a/include/openspace/interaction/externalcontrol/randomexternalcontrol.h b/include/openspace/interaction/externalcontrol/randomexternalcontrol.h deleted file mode 100644 index 171ab2c79a..0000000000 --- a/include/openspace/interaction/externalcontrol/randomexternalcontrol.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef RANDOMEXTERNALCONTROL_H -#define RANDOMEXTERNALCONTROL_H - -#include -#include - -#include - -namespace openspace { - -class RandomExternalControl: public ExternalControl { -public: - - // constructors & destructor - RandomExternalControl(); - ~RandomExternalControl(); - -private: - std::mutex inputGuard; - bool *keepGoing_; - // std::thread *backgroundThread; -}; - -} // namespace openspace - -#endif \ No newline at end of file diff --git a/include/openspace/interaction/interactionhandler.h b/include/openspace/interaction/interactionhandler.h index a7cb9644f5..f4e9589573 100644 --- a/include/openspace/interaction/interactionhandler.h +++ b/include/openspace/interaction/interactionhandler.h @@ -22,18 +22,20 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __INTERACTIONHANDLER_H__ -#define __INTERACTIONHANDLER_H__ +#ifndef __OPENSPACE_CORE___INTERACTIONHANDLER___H__ +#define __OPENSPACE_CORE___INTERACTIONHANDLER___H__ #include -#include #include #include #include #include +#include +#include #include #include +#include #include @@ -47,113 +49,15 @@ class SceneGraphNode; namespace interaction { -//#define USE_OLD_INTERACTIONHANDLER -#ifdef USE_OLD_INTERACTIONHANDLER - -class InteractionHandler : public properties::PropertyOwner { -public: - InteractionHandler(); - ~InteractionHandler(); - - // Mutators - void setKeyboardController(KeyboardController* controller); - void setMouseController(MouseController* controller); - void setFocusNode(SceneGraphNode* node); - void setCamera(Camera* camera); - void setInteractionSensitivity(float sensitivity); - void resetKeyBindings(); - void setInvertRoll(bool invert); - void setInvertRotation(bool invert); - - void addController(Controller* controller); - void addKeyframe(const network::datamessagestructures::PositionKeyframe &kf); - void clearKeyframes(); - - void bindKey(Key key, KeyModifier modifier, std::string lua); - - void lockControls(); - void unlockControls(); - - void update(double deltaTime); - - // Accessors - const SceneGraphNode* const focusNode() const; - const Camera* const camera() const; - double deltaTime() const; - float interactionSensitivity() const; - bool invertRoll() const; - bool invertRotation() const; - - /** - * Returns the Lua library that contains all Lua functions available to affect the - * interaction. The functions contained are - * - openspace::luascriptfunctions::setOrigin - * \return The Lua library that contains all Lua functions available to affect the - * interaction - */ - static scripting::LuaLibrary luaLibrary(); - - - // Callback functions - void keyboardCallback(Key key, KeyModifier modifier, KeyAction action); - void mouseButtonCallback(MouseButton button, MouseAction action); - void mousePositionCallback(double x, double y); - void mouseScrollWheelCallback(double pos); - - // Interaction functions - void orbitDelta(const glm::quat& rotation); - void orbit(const float &dx, const float &dy, const float &dz, const float &dist); - void rotateDelta(const glm::quat& rotation); - void distanceDelta(const PowerScaledScalar& distance, size_t iterations = 0); - void lookAt(const glm::quat& rotation); - void setRotation(const glm::quat& rotation); - - -private: - // Remove copy and move constructors - InteractionHandler(const InteractionHandler&) = delete; - InteractionHandler& operator=(const InteractionHandler&) = delete; - InteractionHandler(InteractionHandler&&) = delete; - InteractionHandler& operator=(InteractionHandler&&) = delete; - - // Settings - float _controllerSensitivity; - bool _invertRoll; - bool _invertRotation; - - // Pointers to entities to affect - Camera* _camera; - SceneGraphNode* _focusNode; - - // Cached data - double _deltaTime; - std::mutex _mutex; - - //bool _validKeyLua; - std::multimap _keyLua; - - - KeyboardController* _keyboardController; - MouseController* _mouseController; - std::vector _controllers; - - properties::StringProperty _origin; - properties::StringProperty _coordinateSystem; - - //remote controller - std::vector _keyframes; - double _currentKeyframeTime; - std::mutex _keyframeMutex; -}; - -#else // USE_OLD_INTERACTIONHANDLER - class InteractionHandler : public properties::PropertyOwner { public: InteractionHandler(); ~InteractionHandler(); + void initialize(); + void deinitialize(); + // Mutators void setFocusNode(SceneGraphNode* node); void setCamera(Camera* camera); @@ -162,18 +66,32 @@ public: // Interaction mode setters void setCameraStateFromDictionary(const ghoul::Dictionary& cameraDict); void setInteractionMode(const std::string& interactionModeKey); - + + void goToChunk(int x, int y, int level); + void goToGeo(double latitude, double longitude); + void resetKeyBindings(); - void addKeyframe(const network::datamessagestructures::PositionKeyframe &kf); + void addKeyframe(const datamessagestructures::CameraKeyframe &kf); void clearKeyframes(); - void bindKey(Key key, KeyModifier modifier, std::string lua); + void bindKeyLocal( + Key key, + KeyModifier modifier, + std::string luaCommand, + std::string documentation = "" + ); + void bindKey( + Key key, + KeyModifier modifier, + std::string luaCommand, + std::string documentation = "" + ); void lockControls(); void unlockControls(); //void update(double deltaTime); - void updateCamera(); + void updateCamera(double deltaTime); void updateInputStates(double timeSinceLastUpdate); // Accessors @@ -202,11 +120,19 @@ public: void writeKeyboardDocumentation(const std::string& type, const std::string& file); private: + using Synchronized = ghoul::Boolean; + + struct KeyInformation { + std::string command; + Synchronized synchronization; + std::string documentation; + }; + void setInteractionMode(std::shared_ptr interactionMode); bool _cameraUpdatedFromScript = false; - std::multimap _keyLua; + std::multimap _keyLua; std::unique_ptr _inputState; Camera* _camera; @@ -228,9 +154,7 @@ private: properties::FloatProperty _rapidness; }; -#endif // USE_OLD_INTERACTIONHANDLER - } // namespace interaction } // namespace openspace -#endif // __INTERACTIONHANDLER_H__ +#endif // __OPENSPACE_CORE___INTERACTIONHANDLER___H__ diff --git a/include/openspace/interaction/interactionmode.h b/include/openspace/interaction/interactionmode.h index 22c495266c..a3a479453f 100644 --- a/include/openspace/interaction/interactionmode.h +++ b/include/openspace/interaction/interactionmode.h @@ -22,15 +22,18 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __INTERACTION_MODE_H__ -#define __INTERACTION_MODE_H__ +#ifndef __OPENSPACE_CORE___INTERACTIONMODE___H__ +#define __OPENSPACE_CORE___INTERACTIONMODE___H__ #include -#include #include #include #include +#ifdef OPENSPACE_MODULE_GLOBEBROWSING_ENABLED +#include +#include +#endif #include @@ -38,10 +41,32 @@ namespace openspace { class Camera; class SceneGraphNode; -class RenderableGlobe; + +namespace globebrowsing { + class RenderableGlobe; +} namespace interaction { + template + class Interpolator + { + public: + Interpolator(std::function transferFunction) + : _t(0.0) + , _transferFunction(transferFunction) {}; + ~Interpolator() {}; + + void start() { _t = 0.0; }; + void end() { _t = 1.0; }; + void step(double delta) { _t += delta; }; + + T value() { return _transferFunction(_t); }; + bool isInterpolating() { return _t < 1.0; }; + private: + std::function _transferFunction; + double _t; + }; class InputState { @@ -56,17 +81,19 @@ namespace interaction { void mouseScrollWheelCallback(double mouseScrollDelta); // Mutators - void addKeyframe(const network::datamessagestructures::PositionKeyframe &kf); + void addKeyframe(const datamessagestructures::CameraKeyframe &kf); void clearKeyframes(); + void clearOldKeyframes(); // Accessors const std::list >& getPressedKeys() const; const std::list& getPressedMouseButtons() const; glm::dvec2 getMousePosition() const; double getMouseScrollDelta() const; - std::vector& getKeyFrames() const; + const std::vector& keyframes() const; bool isKeyPressed(std::pair keyModPair) const; + bool isKeyPressed(Key key) const; bool isMouseButtonPressed(MouseButton mouseButton) const; private: // Input from keyboard and mouse @@ -76,8 +103,7 @@ namespace interaction { double _mouseScrollDelta; // Remote input via keyframes - std::vector _keyframes; - std::mutex _keyframeMutex; + std::vector _keyframes; }; @@ -93,9 +119,10 @@ public: // Accessors SceneGraphNode* focusNode(); - + Interpolator& rotateToFocusNodeInterpolator(); + virtual void updateMouseStatesFromInput(const InputState& inputState, double deltaTime) = 0; - virtual void updateCameraStateFromMouseStates(Camera& camera) = 0; + virtual void updateCameraStateFromMouseStates(Camera& camera, double deltaTime) = 0; protected: /** @@ -156,6 +183,9 @@ protected: SceneGraphNode* _focusNode = nullptr; glm::dvec3 _previousFocusNodePosition; glm::dquat _previousFocusNodeRotation; + + + Interpolator _rotateToFocusNodeInterpolator; }; class KeyframeInteractionMode : public InteractionMode @@ -165,9 +195,10 @@ public: ~KeyframeInteractionMode(); virtual void updateMouseStatesFromInput(const InputState& inputState, double deltaTime); - virtual void updateCameraStateFromMouseStates(Camera& camera); + virtual void updateCameraStateFromMouseStates(Camera& camera, double deltaTime); private: + std::vector _keyframes; double _currentKeyframeTime; }; @@ -214,10 +245,10 @@ public: //virtual void update(Camera& camera, const InputState& inputState, double deltaTime); virtual void updateMouseStatesFromInput(const InputState& inputState, double deltaTime); - virtual void updateCameraStateFromMouseStates(Camera& camera); + virtual void updateCameraStateFromMouseStates(Camera& camera, double deltaTime); protected: - //void updateCameraStateFromMouseStates(Camera& camera); + //void updateCameraStateFromMouseStates(Camera& camera, double deltaTime); std::shared_ptr _mouseStates; }; @@ -229,14 +260,24 @@ public: virtual void setFocusNode(SceneGraphNode* focusNode); //virtual void update(Camera& camera, const InputState& inputState, double deltaTime); - virtual void updateCameraStateFromMouseStates(Camera& camera); - + virtual void updateCameraStateFromMouseStates(Camera& camera, double deltaTime); +#ifdef OPENSPACE_MODULE_GLOBEBROWSING_ENABLED + void goToChunk(Camera& camera, globebrowsing::TileIndex ti, glm::vec2 uv, + bool resetCameraDirection); + void goToGeodetic2(Camera& camera, globebrowsing::Geodetic2 geo2, + bool resetCameraDirection); + + void goToGeodetic3(Camera& camera, globebrowsing::Geodetic3 geo3); + void resetCameraDirection(Camera& camera, globebrowsing::Geodetic2 geo2); +#endif private: - //void updateCameraStateFromMouseStates(Camera& camera); - RenderableGlobe* _globe; + //void updateCameraStateFromMouseStates(Camera& camera, double deltaTime); +#ifdef OPENSPACE_MODULE_GLOBEBROWSING_ENABLED + globebrowsing::RenderableGlobe* _globe; +#endif }; } // namespace interaction } // namespace openspace -#endif // __INTERACTION_MODE_H__ +#endif // __OPENSPACE_CORE___INTERACTIONMODE___H__ diff --git a/include/openspace/interaction/keyboardcontroller.h b/include/openspace/interaction/keyboardcontroller.h index 94550e2869..07933e5bc7 100644 --- a/include/openspace/interaction/keyboardcontroller.h +++ b/include/openspace/interaction/keyboardcontroller.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __KEYBOARDCONTROLLER_H__ -#define __KEYBOARDCONTROLLER_H__ +#ifndef __OPENSPACE_CORE___KEYBOARDCONTROLLER___H__ +#define __OPENSPACE_CORE___KEYBOARDCONTROLLER___H__ #include @@ -54,4 +54,4 @@ protected: } // namespace interaction } // namespace openspace -#endif // __KEYBOARDCONTROLLER_H__ +#endif // __OPENSPACE_CORE___KEYBOARDCONTROLLER___H__ diff --git a/include/openspace/interaction/luaconsole.h b/include/openspace/interaction/luaconsole.h index 9273a717a7..cf863107b3 100644 --- a/include/openspace/interaction/luaconsole.h +++ b/include/openspace/interaction/luaconsole.h @@ -22,10 +22,11 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef LUACONSOLE_H -#define LUACONSOLE_H +#ifndef __OPENSPACE_CORE___LUACONSOLE___H__ +#define __OPENSPACE_CORE___LUACONSOLE___H__ #include +#include #include @@ -50,12 +51,16 @@ public: bool isVisible() const; void setVisible(bool visible); - void toggleVisibility(); + bool isRemoteScripting() const; + void setRemoteScripting(bool remoteScripting); + + void toggleMode(); static scripting::LuaLibrary luaLibrary(); private: + void parallelConnectionChanged(const ParallelConnection::Status& status); void addToCommand(std::string c); std::string UnicodeToUTF8(unsigned int codepoint); @@ -73,8 +78,9 @@ private: } _autoCompleteInfo; bool _isVisible; + bool _remoteScripting; }; } // namespace openspace -#endif +#endif // __OPENSPACE_CORE___LUACONSOLE___H__ diff --git a/include/openspace/mission/mission.h b/include/openspace/mission/mission.h index 65662dae9c..5783461813 100644 --- a/include/openspace/mission/mission.h +++ b/include/openspace/mission/mission.h @@ -22,12 +22,13 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __MISSION_H__ -#define __MISSION_H__ +#ifndef __OPENSPACE_CORE___MISSION___H__ +#define __OPENSPACE_CORE___MISSION___H__ #include #include +#include #include #include @@ -36,53 +37,110 @@ namespace ghoul { class Dictionary; } namespace openspace { /** -* Used to represent a named period of time within a mission. Allows nested phases, i.e. -* phases within phases. Designed for WORM usage (Write Once, Read Multiple), and therefor -* has only accessors. -*/ + * Used to represent a named period of time within a mission. Allows nested phases, i.e. + * phases within phases. Designed for WORM usage (Write Once, Read Multiple), and, + * therefore, has only accessors. + * + * Each MissionPhase is characterized by its MissionPhase::name, a TimeRange, an + * optional MissionPhase::description, and optional subphases. + */ class MissionPhase { public: - MissionPhase(const ghoul::Dictionary& dict); + /** + * Constructs a MissionPhase from the information provided in the \p dictionary. See + * the MissionPhase::Documentation for accepted ghoul::Dictionary values. + * \param dictionary The ghoul::Dictionary that contains information about the current + * MissionPhase + * \throw SpecificationError If the \p dictionary does not adhere to the Documentation + * \throw RuntimeError If the time range of subphases is smaller than the specified + * time range + * \throw RuntimeError If neither subphases or a time range is specified + */ + MissionPhase(const ghoul::Dictionary& dictionary); + /** + * Returns the name of the MissionPhase. + * \return The name of the MissionPhase + */ const std::string& name() const; + /** + * Returns the TimeRange of the MissionPhase. + * \return The TimeRange of the MissionPhase + */ const TimeRange& timeRange() const; + /** + * Returns the description of the MissionPhase. + * \return The description of the MissionPhase + */ const std::string& description() const; /** - * Returns all subphases sorted by start time - */ + * Returns all subphases sorted by start time. + * \return All subphases sorted by start time + */ const std::vector& phases() const; + + using Trace = std::vector>; + /** - * Returns the i:th subphase, sorted by start time - */ - const MissionPhase& phase(size_t i) const; - - std::vector phaseTrace(double time, int maxDepth = -1) const; + * Returns all MissionPhase%s whose MissionPhase::timeRange includes the provided + * \p time, up to a maximum subphase depth of \p maxDepth. + * \param time The time in which the subphases have to be active in order to be + * included + * \param maxDepth The maximum levels of subphases that will be considered. If this + * value is equal to -1, an infinite depth will be considered. + * \return A list of MissionPhases that cover the provided \p time + */ + Trace phaseTrace(double time, int maxDepth = -1) const; + /** + * Returns the Documentation that describes the ghoul::Dictionarty that this + * MissionPhase can be constructed from. + * \return The Documentation that describes the required structure for a Dictionary + */ static openspace::Documentation Documentation(); protected: - bool phaseTrace(double time, std::vector& trace, int maxDepth) const; + /** + * Recursive function that walks the subphases and adds the MissionPhase%s that cover + * the provided \p time and adds these to the list of \p trace%s. Each recursive call + * will decrease the \p maxDepth counter until it reaches 0. + * \param time The time which the subphases have to cover to be added to the \p trace + * \param trace The list of MissionPhase%s that are active during the time \p time + * \param maxDepth The maximum depth of levels that will be considered + */ + void phaseTrace(double time, Trace& trace, int maxDepth) const; + /// The name of the MissionPhase std::string _name; + /// The description of the MissionPhase std::string _description; + /// The range in time that is covered by this MissionPhase TimeRange _timeRange; + /// A list of subphases into which this MissionPhase is separated std::vector _subphases; }; +/** + * A Mission is a list of MissionPhases that has a name, an optional description, a + * TimeRange for which the Mission is active, and a potential list of subphases. + */ using Mission = MissionPhase; /** -* \pre \p filename must not be empty -* \pre \p filename must not contain tokens -* \pre \p filename must exist -*/ + * This function constructs a Mission from the provided \p filename. The file must be a + * Lua table that describes the Mission according to MissionPhase::Documentation + * \param filename The file that is used to create the Mission + * \return The constructed Mission + * \pre \p filename must not be empty + * \pre \p filename must not contain tokens + * \pre \p filename must exist + */ Mission missionFromFile(std::string filename); } // namespace openspace - -#endif // __MISSION_H__ +#endif // __OPENSPACE_CORE___MISSION___H__ diff --git a/include/openspace/mission/missionmanager.h b/include/openspace/mission/missionmanager.h index 9c08cb231c..56fee42f45 100644 --- a/include/openspace/mission/missionmanager.h +++ b/include/openspace/mission/missionmanager.h @@ -22,11 +22,12 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __MISSIONPHASEEQUENCER_H__ -#define __MISSIONPHASEEQUENCER_H__ +#ifndef __OPENSPACE_CORE___MISSIONMANAGER___H__ +#define __OPENSPACE_CORE___MISSIONMANAGER___H__ #include +#include #include #include @@ -39,16 +40,13 @@ namespace scripting { struct LuaLibrary; } /** * Singleton class keeping track of space missions. */ -class MissionManager { +class MissionManager : public ghoul::Singleton { public: struct MissionManagerException : public ghoul::RuntimeError { explicit MissionManagerException(std::string error); }; - static MissionManager& ref(); - - static void initialize(); - static void deinitialize(); + MissionManager(); /** * Reads a mission from file and maps the mission name to the Mission object. If @@ -71,6 +69,7 @@ public: /** * Sets the mission with the name as the current mission. The current * mission is what is return by `currentMission()`. + * \pre missionName must not be empty */ void setCurrentMission(const std::string& missionName); @@ -85,20 +84,16 @@ public: * loaded, a warning will be printed and a dummy mission will be returned. */ const Mission& currentMission(); - -private: - static scripting::LuaLibrary luaLibrary(); - static MissionManager _instance; + static scripting::LuaLibrary luaLibrary(); + +private: using MissionMap = std::map; MissionMap _missionMap; MissionMap::iterator _currentMission; - - // Singleton - MissionManager(); }; } // namespace openspace -#endif // __MISSIONPHASEEQUENCER_H__ +#endif // __OPENSPACE_CORE___MISSIONMANAGER___H__ diff --git a/include/openspace/network/messagestructures.h b/include/openspace/network/messagestructures.h index e2e3adc313..8b06233f2c 100644 --- a/include/openspace/network/messagestructures.h +++ b/include/openspace/network/messagestructures.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __MESSAGESTRUCTURES_H__ -#define __MESSAGESTRUCTURES_H__ +#ifndef __OPENSPACE_CORE___MESSAGESTRUCTURES___H__ +#define __OPENSPACE_CORE___MESSAGESTRUCTURES___H__ //std includes #include @@ -33,133 +33,135 @@ #include //openspace includes -#include +#include namespace openspace{ - - namespace network{ - - namespace datamessagestructures{ - enum type{ - PositionData = 0, - TimeData, - ScriptData - }; - - struct PositionKeyframe{ - glm::quat _viewRotationQuat; - psc _position; - double _timeStamp; - - void serialize(std::vector &buffer){ - //add position - buffer.insert(buffer.end(), reinterpret_cast(&_position), reinterpret_cast(&_position) + sizeof(_position)); - - //add orientation - buffer.insert(buffer.end(), reinterpret_cast(&_viewRotationQuat), reinterpret_cast(&_viewRotationQuat) + sizeof(_viewRotationQuat)); - - //add timestamp - buffer.insert(buffer.end(), reinterpret_cast(&_timeStamp), reinterpret_cast(&_timeStamp) + sizeof(_timeStamp)); - }; - - void deserialize(const std::vector &buffer){ - int offset = 0; - int size = 0; - - //position - size = sizeof(_position); - memcpy(&_position, buffer.data() + offset, size); - offset += size; - - //orientation - size = sizeof(_viewRotationQuat); - memcpy(&_viewRotationQuat, buffer.data() + offset, size); - offset += size; - - //timestamp - size = sizeof(_timeStamp); - memcpy(&_timeStamp, buffer.data() + offset, size); - }; - }; - - struct TimeKeyframe{ +namespace datamessagestructures { +enum class Type : uint32_t { + CameraData = 0, + TimeData, + ScriptData +}; - double _time; - double _dt; - bool _paused; - bool _requiresTimeJump; - - void serialize(std::vector &buffer){ - //add current time - buffer.insert(buffer.end(), reinterpret_cast(&_time), reinterpret_cast(&_time) + sizeof(_time)); - - //add delta time - buffer.insert(buffer.end(), reinterpret_cast(&_dt), reinterpret_cast(&_dt) + sizeof(_dt)); - - //add wether time is paused or not - buffer.insert(buffer.end(), reinterpret_cast(&_paused), reinterpret_cast(&_paused) + sizeof(_paused)); - - //add wether a time jump is necessary (recompute paths etc) - buffer.insert(buffer.end(), reinterpret_cast(&_requiresTimeJump), reinterpret_cast(&_requiresTimeJump) + sizeof(_requiresTimeJump)); - }; - - void deserialize(const std::vector &buffer){ - int offset = 0; - int size = 0; - - //current time - size = sizeof(_time); - memcpy(&_time, buffer.data() + offset, size); - offset += size; - - //delta time - size = sizeof(_dt); - memcpy(&_dt, buffer.data() + offset, size); - offset += size; - - //is time paused? - size = sizeof(_paused); - memcpy(&_paused, buffer.data() + offset, size); - offset += sizeof(_paused); - - //is a time jump required? - size = sizeof(_requiresTimeJump); - memcpy(&_requiresTimeJump, buffer.data() + offset, size); - }; - }; - - struct ScriptMessage{ - - uint16_t _scriptlen; - std::string _script; - - void serialize(std::vector &buffer){ - //add script length - buffer.insert(buffer.end(), reinterpret_cast(&_scriptlen), reinterpret_cast(&_scriptlen) + sizeof(_scriptlen)); - - //add script - buffer.insert(buffer.end(), _script.begin(), _script.end()); - - }; - - void deserialize(const std::vector &buffer){ - int offset = 0; - int size = 0; - - //size of script - size = sizeof(uint16_t); - memcpy(&_scriptlen, buffer.data() + offset, size); - offset += size; - - //actual script - _script.assign(buffer.begin() + offset, buffer.end()); - }; - }; - - } //namespace messagestructures +struct CameraKeyframe { + CameraKeyframe() {} + CameraKeyframe(const std::vector &buffer) { + deserialize(buffer); + } - } // namespace network + glm::dvec3 _position; + glm::dquat _rotation; + double _timestamp; + + void serialize(std::vector &buffer){ + //add position + buffer.insert(buffer.end(), reinterpret_cast(&_position), reinterpret_cast(&_position) + sizeof(_position)); + + //add orientation + buffer.insert(buffer.end(), reinterpret_cast(&_rotation), reinterpret_cast(&_rotation) + sizeof(_rotation)); + + //add timestamp + buffer.insert(buffer.end(), reinterpret_cast(&_timestamp), reinterpret_cast(&_timestamp) + sizeof(_timestamp)); + }; + + void deserialize(const std::vector &buffer){ + int offset = 0; + int size = 0; + + //position + size = sizeof(_position); + memcpy(&_position, buffer.data() + offset, size); + offset += size; + + //orientation + size = sizeof(_rotation); + memcpy(&_rotation, buffer.data() + offset, size); + offset += size; + + //timestamp + size = sizeof(_timestamp); + memcpy(&_timestamp, buffer.data() + offset, size); + }; +}; + +struct TimeKeyframe { + TimeKeyframe() {} + TimeKeyframe(const std::vector &buffer) { + deserialize(buffer); + } + + double _time; + double _dt; + bool _paused; + bool _requiresTimeJump; + double _timestamp; + + void serialize(std::vector &buffer){ + //add current time + buffer.insert(buffer.end(), reinterpret_cast(&_time), reinterpret_cast(&_time) + sizeof(_time)); + + //add delta time + buffer.insert(buffer.end(), reinterpret_cast(&_dt), reinterpret_cast(&_dt) + sizeof(_dt)); + + //add wether time is paused or not + buffer.insert(buffer.end(), reinterpret_cast(&_paused), reinterpret_cast(&_paused) + sizeof(_paused)); + + //add wether a time jump is necessary (recompute paths etc) + buffer.insert(buffer.end(), reinterpret_cast(&_requiresTimeJump), reinterpret_cast(&_requiresTimeJump) + sizeof(_requiresTimeJump)); + + //add timestamp + buffer.insert(buffer.end(), reinterpret_cast(&_timestamp), reinterpret_cast(&_timestamp) + sizeof(_timestamp)); + }; + + void deserialize(const std::vector &buffer){ + int offset = 0; + int size = 0; + + //current time + size = sizeof(_time); + memcpy(&_time, buffer.data() + offset, size); + offset += size; + + //delta time + size = sizeof(_dt); + memcpy(&_dt, buffer.data() + offset, size); + offset += size; + + //is time paused? + size = sizeof(_paused); + memcpy(&_paused, buffer.data() + offset, size); + offset += sizeof(_paused); + //is a time jump required? + size = sizeof(_requiresTimeJump); + memcpy(&_requiresTimeJump, buffer.data() + offset, size); + offset += size; + + // timestamp + size = sizeof(_timestamp); + memcpy(&_timestamp, buffer.data() + offset, size); + offset += size; + }; +}; + +struct ScriptMessage { + ScriptMessage() {} + ScriptMessage(const std::vector &buffer) { + deserialize(buffer); + } + + std::string _script; + + void serialize(std::vector &buffer){ + buffer.insert(buffer.end(), _script.begin(), _script.end()); + }; + + void deserialize(const std::vector &buffer){ + _script.assign(buffer.begin(), buffer.end()); + }; +}; + +} //namespace messagestructures } // namespace openspace -#endif // __MESSAGESTRUCTURES_H__ +#endif // __OPENSPACE_CORE___MESSAGESTRUCTURES___H__ diff --git a/include/openspace/network/networkengine.h b/include/openspace/network/networkengine.h index 9a4febd7aa..e3f92e3264 100644 --- a/include/openspace/network/networkengine.h +++ b/include/openspace/network/networkengine.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __NETWORKENGINE_H__ -#define __NETWORKENGINE_H__ +#ifndef __OPENSPACE_CORE___NETWORKENGINE___H__ +#define PARALLELCONNECTION__OPENSPACE_CORE___NETWORKENGINE___H__ #include #include @@ -75,4 +75,4 @@ private: } // namespace openspace -#endif // __NETWORKENGINE_H__ +#endif // __OPENSPACE_CORE___NETWORKENGINE___H__ diff --git a/include/openspace/network/parallelconnection.h b/include/openspace/network/parallelconnection.h index 9073d1f18b..2822b1e398 100644 --- a/include/openspace/network/parallelconnection.h +++ b/include/openspace/network/parallelconnection.h @@ -22,35 +22,29 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __PARALLELCONNECTION_H__ -#define __PARALLELCONNECTION_H__ +#ifndef __OPENSPACE_CORE___PARALLELCONNECTION___H__ +#define __OPENSPACE_CORE___PARALLELCONNECTION___H__ //openspace includes -#include -#include #include //glm includes #include +//ghoul includes +#include + //std includes #include #include +#include #include #include -#include #include #include #include -#ifdef WIN32 -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif -#include -#include -#include -#endif + #if defined(WIN32) || defined(__MING32__) || defined(__MING64__) typedef size_t _SOCKET; @@ -59,150 +53,151 @@ typedef int _SOCKET; #include #endif -namespace openspace{ - - namespace network{ - - class ParallelConnection{ - public: - - ParallelConnection(); - - ~ParallelConnection(); - - void clientConnect(); - - void setPort(const std::string &port); - - void setAddress(const std::string &address); - - void setName(const std::string& name); - - bool isHost(); - - void requestHostship(const std::string &password); +struct addrinfo; - void setPassword(const std::string &password); - - void signalDisconnect(); - - void preSynchronization(); - - void scriptMessage(const std::string propIdentifier, const std::string propValue); - - enum MessageTypes{ - Authentication=0, - Initialization, - Data, - Script, //obsolete now - HostInfo, - InitializationRequest, - HostshipRequest, - InitializationCompleted - }; - - /** - * Returns the Lua library that contains all Lua functions available to affect the - * remote OS parallel connection. The functions contained are - * - - * \return The Lua library that contains all Lua functions available to affect the - * interaction - */ - static scripting::LuaLibrary luaLibrary(); - - protected: - - private: - //@TODO change this into the ghoul hasher for client AND server - uint32_t hash(const std::string &val){ - uint32_t hashVal = 0, i; - size_t len = val.length(); +namespace openspace { - for (hashVal = i = 0; i < len; ++i){ - hashVal += val.c_str()[i]; - hashVal += (hashVal << 10); - hashVal ^= (hashVal >> 6); - } +class ParallelConnection { + public: + enum class Status : uint32_t { + Disconnected = 0, + ClientWithoutHost, + ClientWithHost, + Host + }; - hashVal += (hashVal << 3); - hashVal ^= (hashVal >> 11); - hashVal += (hashVal << 15); + enum class MessageType : uint32_t { + Authentication = 0, + Data, + ConnectionStatus, + HostshipRequest, + HostshipResignation, + NConnections + }; + + struct Message { + Message() {}; + Message(MessageType t, const std::vector& c) + : type(t) + , content(c) + {}; + + MessageType type; + std::vector content; + }; + + struct DataMessage { + DataMessage() {}; + DataMessage(datamessagestructures::Type t, const std::vector& c) + : type(t) + , content(c) + {}; + datamessagestructures::Type type; + std::vector content; + }; + + ParallelConnection(); + ~ParallelConnection(); + void clientConnect(); + void setPort(const std::string &port); + void setAddress(const std::string &address); + void setName(const std::string& name); + bool isHost(); + const std::string& hostName(); + void requestHostship(const std::string &password); + void resignHostship(); + void setPassword(const std::string &password); + void signalDisconnect(); + void preSynchronization(); + void sendScript(const std::string& script); + + /** + * Returns the Lua library that contains all Lua functions available to affect the + * remote OS parallel connection. The functions contained are + * - + * \return The Lua library that contains all Lua functions available to affect the + * interaction + */ + static scripting::LuaLibrary luaLibrary(); + Status status(); + size_t nConnections(); + std::shared_ptr> connectionEvent(); - return hashVal; - }; - void queueMessage(std::vector message); - void disconnect(); +private: + //@TODO change this into the ghoul hasher for client AND server + uint32_t hash(const std::string &val); + void queueOutMessage(const Message& message); + void queueOutDataMessage(const DataMessage& dataMessage); + void queueInMessage(const Message& message); + + void disconnect(); + void closeSocket(); + bool initNetworkAPI(); + void establishConnection(addrinfo *info); + void sendAuthentication(); + void listenCommunication(); + int receiveData(_SOCKET & socket, std::vector &buffer, int length, int flags); + + void handleMessage(const Message&); + void dataMessageReceived(const std::vector& messageContent); + void connectionStatusMessageReceived(const std::vector& messageContent); + void nConnectionsMessageReceived(const std::vector& messageContent); + + void broadcast(); + void sendCameraKeyframe(); + void sendTimeKeyframe(); + + void sendFunc(); + void threadManagement(); + + void setStatus(Status status); + void setHostName(const std::string& hostName); + void setNConnections(size_t nConnections); + + double calculateBufferedKeyframeTime(double originalTime); + + uint32_t _passCode; + std::string _port; + std::string _address; + std::string _name; - void writeHeader(std::vector &buffer, uint32_t messageType); + _SOCKET _clientSocket; - void closeSocket(); + std::atomic _isConnected; + std::atomic _isRunning; + std::atomic _tryConnect; + std::atomic _disconnect; + std::atomic _initializationTimejumpRequired; - bool initNetworkAPI(); + std::atomic _nConnections; + std::atomic _status; + std::string _hostName; - void establishConnection(addrinfo *info); - - void sendAuthentication(); - - void listenCommunication(); - - void delegateDecoding(uint32_t type); - - void initializationMessageReceived(); - - void dataMessageReceived(); - - void hostInfoMessageReceived(); + std::condition_variable _disconnectCondition; + std::mutex _disconnectMutex; - void initializationRequestMessageReceived(); + std::condition_variable _sendCondition; + std::deque _sendBuffer; + std::mutex _sendBufferMutex; - void broadcast(); + std::deque _receiveBuffer; + std::mutex _receiveBufferMutex; - int headerSize(); + std::atomic _timeJumped; + std::mutex _latencyMutex; + std::deque _latencyDiffs; + double _initialTimeDiff; - int receiveData(_SOCKET & socket, std::vector &buffer, int length, int flags); - - void sendFunc(); - - bool parseHints(addrinfo &info); - - void threadManagement(); - - std::string scriptFromPropertyAndValue(const std::string property, const std::string value); - - uint32_t _passCode; - std::string _port; - std::string _address; - std::string _name; - _SOCKET _clientSocket; - std::thread *_connectionThread; - std::thread *_broadcastThread; - std::thread *_sendThread; - std::thread *_listenThread; - std::thread *_handlerThread; - std::atomic _isHost; - std::atomic _isConnected; - std::atomic _performDisconnect; - std::atomic _isRunning; - std::atomic _tryConnect; - std::atomic _initializationTimejumpRequired; + std::unique_ptr _connectionThread; + std::unique_ptr _broadcastThread; + std::unique_ptr _sendThread; + std::unique_ptr _listenThread; + std::unique_ptr _handlerThread; + std::shared_ptr> _connectionEvent; +}; - std::condition_variable _disconnectCondition; - std::mutex _disconnectMutex; - - std::vector> _sendBuffer; - std::mutex _sendBufferMutex; - std::condition_variable _sendCondition; - - network::datamessagestructures::TimeKeyframe _latestTimeKeyframe; - std::mutex _timeKeyframeMutex; - std::atomic _latestTimeKeyframeValid; - std::map _currentState; - std::mutex _currentStateMutex; - }; - } // namespace network - } // namespace openspace -#endif // __OSPARALLELCONNECTION_H__ +#endif // __OPENSPACE_CORE___PARALLELCONNECTION___H__ diff --git a/include/openspace/openspace.h b/include/openspace/openspace.h index 3fbdcf642e..5359b5f360 100644 --- a/include/openspace/openspace.h +++ b/include/openspace/openspace.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __OPENSPACE_H__ -#define __OPENSPACE_H__ +#ifndef __OPENSPACE_CORE___OPENSPACE___H__ +#define __OPENSPACE_CORE___OPENSPACE___H__ #include @@ -32,11 +32,11 @@ namespace openspace { std::string licenseText(); const int OPENSPACE_VERSION_MAJOR = 0; -const int OPENSPACE_VERSION_MINOR = 5; +const int OPENSPACE_VERSION_MINOR = 6; const int OPENSPACE_VERSION_PATCH = 0; -const std::string OPENSPACE_VERSION_STRING = "prerelease-10 (Kulturnatten)"; +const std::string OPENSPACE_VERSION_STRING = "prerelease-11 (AGU)"; } // namespace openspace -#endif // __OPENSPACE_H__ +#endif // __OPENSPACE_CORE___OPENSPACE___H__ diff --git a/include/openspace/performance/performancelayout.h b/include/openspace/performance/performancelayout.h index 70568e67e5..29feabaca5 100644 --- a/include/openspace/performance/performancelayout.h +++ b/include/openspace/performance/performancelayout.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __PERFORMANCELAYOUT_H__ -#define __PERFORMANCELAYOUT_H__ +#ifndef __OPENSPACE_CORE___PERFORMANCELAYOUT___H__ +#define __OPENSPACE_CORE___PERFORMANCELAYOUT___H__ #include @@ -42,7 +42,9 @@ struct PerformanceLayout { char name[LengthName]; float renderTime[NumberValues]; float updateRenderable[NumberValues]; - float updateEphemeris[NumberValues]; + float updateTranslation[NumberValues]; + float updateRotation[NumberValues]; + float updateScaling[NumberValues]; }; SceneGraphPerformanceLayout sceneGraphEntries[MaxValues]; int16_t nScaleGraphEntries; @@ -58,4 +60,4 @@ struct PerformanceLayout { } // namespace performance } // namespace openspace -#endif // __PERFORMANCELAYOUT_H__ +#endif // __OPENSPACE_CORE___PERFORMANCELAYOUT___H__ diff --git a/include/openspace/performance/performancemanager.h b/include/openspace/performance/performancemanager.h index 5d54223dab..ebad4f61ff 100644 --- a/include/openspace/performance/performancemanager.h +++ b/include/openspace/performance/performancemanager.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __PERFORMANCEMANAGER_H__ -#define __PERFORMANCEMANAGER_H__ +#ifndef __OPENSPACE_CORE___PERFORMANCEMANAGER___H__ +#define __OPENSPACE_CORE___PERFORMANCEMANAGER___H__ #include @@ -71,4 +71,4 @@ private: } // namespace performance } // namespace openspace -#endif // __PERFORMANCEMANAGER_H__ +#endif // __OPENSPACE_CORE___PERFORMANCEMANAGER___H__ diff --git a/include/openspace/performance/performancemeasurement.h b/include/openspace/performance/performancemeasurement.h index 9bf1395d67..3be224cf1e 100644 --- a/include/openspace/performance/performancemeasurement.h +++ b/include/openspace/performance/performancemeasurement.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __PERFORMANCEMEASUREMENT_H__ -#define __PERFORMANCEMEASUREMENT_H__ +#ifndef __OPENSPACE_CORE___PERFORMANCEMEASUREMENT___H__ +#define __OPENSPACE_CORE___PERFORMANCEMEASUREMENT___H__ #include #include @@ -62,4 +62,4 @@ private: } // namespace performance } // namespace openspace -#endif // __PERFORMANCEMEASUREMENTHELPER_H__ +#endif // __OPENSPACE_CORE___PERFORMANCEMEASUREMENT___H__ diff --git a/include/openspace/properties/matrix/dmat2property.h b/include/openspace/properties/matrix/dmat2property.h new file mode 100644 index 0000000000..d50900234a --- /dev/null +++ b/include/openspace/properties/matrix/dmat2property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___DMAT2PROPERTY___H__ +#define __OPENSPACE_CORE___DMAT2PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(DMat2Property, glm::dmat2x2); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___DMAT2PROPERTY___H__ diff --git a/include/openspace/properties/matrix/dmat2x3property.h b/include/openspace/properties/matrix/dmat2x3property.h new file mode 100644 index 0000000000..c6ec775b38 --- /dev/null +++ b/include/openspace/properties/matrix/dmat2x3property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___DMAT2x3PROPERTY___H__ +#define __OPENSPACE_CORE___DMAT2x3PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(DMat2x3Property, glm::dmat2x3); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___DMAT2x3PROPERTY___H__ diff --git a/include/openspace/properties/matrix/dmat2x4property.h b/include/openspace/properties/matrix/dmat2x4property.h new file mode 100644 index 0000000000..060569bdb9 --- /dev/null +++ b/include/openspace/properties/matrix/dmat2x4property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___DMAT2x4PROPERTY___H__ +#define __OPENSPACE_CORE___DMAT2x4PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(DMat2x4Property, glm::dmat2x4); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___DMAT2x4PROPERTY___H__ diff --git a/include/openspace/properties/matrix/dmat3property.h b/include/openspace/properties/matrix/dmat3property.h new file mode 100644 index 0000000000..c94c94694b --- /dev/null +++ b/include/openspace/properties/matrix/dmat3property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___DMAT3PROPERTY___H__ +#define __OPENSPACE_CORE___DMAT3PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(DMat3Property, glm::dmat3x3); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___DMAT3PROPERTY___H__ diff --git a/include/openspace/properties/matrix/dmat3x2property.h b/include/openspace/properties/matrix/dmat3x2property.h new file mode 100644 index 0000000000..e94c0f7f13 --- /dev/null +++ b/include/openspace/properties/matrix/dmat3x2property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___DMAT3x2PROPERTY___H__ +#define __OPENSPACE_CORE___DMAT3x2PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(DMat3x2Property, glm::dmat3x2); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___DMAT3x2PROPERTY___H__ diff --git a/include/openspace/properties/matrix/dmat3x4property.h b/include/openspace/properties/matrix/dmat3x4property.h new file mode 100644 index 0000000000..7d6c190766 --- /dev/null +++ b/include/openspace/properties/matrix/dmat3x4property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___DMAT3x4PROPERTY___H__ +#define __OPENSPACE_CORE___DMAT3x4PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(DMat3x4Property, glm::dmat3x4); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___DMAT3x4PROPERTY___H__ diff --git a/include/openspace/properties/matrix/dmat4property.h b/include/openspace/properties/matrix/dmat4property.h new file mode 100644 index 0000000000..927587f1eb --- /dev/null +++ b/include/openspace/properties/matrix/dmat4property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___DMAT4PROPERTY___H__ +#define __OPENSPACE_CORE___DMAT4PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(DMat4Property, glm::dmat4x4); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___DMAT4PROPERTY___H__ diff --git a/include/openspace/properties/matrix/dmat4x2property.h b/include/openspace/properties/matrix/dmat4x2property.h new file mode 100644 index 0000000000..3ab7f82af6 --- /dev/null +++ b/include/openspace/properties/matrix/dmat4x2property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___DMAT4x2PROPERTY___H__ +#define __OPENSPACE_CORE___DMAT4x2PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(DMat4x2Property, glm::dmat4x2); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___DMAT4x2PROPERTY___H__ diff --git a/include/openspace/properties/matrix/dmat4x3property.h b/include/openspace/properties/matrix/dmat4x3property.h new file mode 100644 index 0000000000..013fe01794 --- /dev/null +++ b/include/openspace/properties/matrix/dmat4x3property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___DMAT4x3PROPERTY___H__ +#define __OPENSPACE_CORE___DMAT4x3PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(DMat4x3Property, glm::dmat4x3); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___DMAT4x3PROPERTY___H__ diff --git a/modules/base/shaders/ephemeris_fs.glsl b/include/openspace/properties/matrix/mat2property.h similarity index 84% rename from modules/base/shaders/ephemeris_fs.glsl rename to include/openspace/properties/matrix/mat2property.h index a77149b371..f8deb63b3d 100644 --- a/modules/base/shaders/ephemeris_fs.glsl +++ b/include/openspace/properties/matrix/mat2property.h @@ -22,21 +22,19 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -uniform float forceFade; -uniform vec3 color; +#ifndef __OPENSPACE_CORE___MAT2PROPERTY___H__ +#define __OPENSPACE_CORE___MAT2PROPERTY___H__ -in vec4 vs_positionScreenSpace; -in float fade; +#include -#include "PowerScaling/powerScaling_fs.hglsl" -#include "fragment.glsl" +#include -Fragment getFragment() { - vec4 c = vec4(color * fade * forceFade, 1.0); - Fragment frag; - frag.color = c; - frag.depth = vs_positionScreenSpace.w; - frag.blend = BLEND_MODE_ADDITIVE; +namespace openspace { +namespace properties { - return frag; -} +REGISTER_NUMERICALPROPERTY_HEADER(Mat2Property, glm::mat2x2); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___MAT2PROPERTY___H__ diff --git a/modules/base/shaders/renderabletrailnew_fs.glsl b/include/openspace/properties/matrix/mat2x3property.h similarity index 84% rename from modules/base/shaders/renderabletrailnew_fs.glsl rename to include/openspace/properties/matrix/mat2x3property.h index ea0f97a653..822a11d5b5 100644 --- a/modules/base/shaders/renderabletrailnew_fs.glsl +++ b/include/openspace/properties/matrix/mat2x3property.h @@ -22,25 +22,19 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -// Inputs -in vec4 vs_positionScreenSpace; -in float vs_alpha; +#ifndef __OPENSPACE_CORE___MAT2x3PROPERTY___H__ +#define __OPENSPACE_CORE___MAT2x3PROPERTY___H__ -// Uniforms -uniform float forceFade; -uniform vec3 color; +#include -#include "PowerScaling/powerScaling_fs.hglsl" -#include "fragment.glsl" +#include -Fragment getFragment() { - if (vs_alpha < 0.01) - discard; - vec4 c = vec4(color, vs_alpha); +namespace openspace { +namespace properties { - Fragment frag; - frag.color = c; - frag.depth = vs_positionScreenSpace.w; +REGISTER_NUMERICALPROPERTY_HEADER(Mat2x3Property, glm::mat2x3); - return frag; -} \ No newline at end of file +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___MAT2x3PROPERTY___H__ diff --git a/include/openspace/properties/matrix/mat2x4property.h b/include/openspace/properties/matrix/mat2x4property.h new file mode 100644 index 0000000000..19230ac699 --- /dev/null +++ b/include/openspace/properties/matrix/mat2x4property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___MAT2x4PROPERTY___H__ +#define __OPENSPACE_CORE___MAT2x4PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(Mat2x4Property, glm::mat2x4); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___MAT2x4PROPERTY___H__ diff --git a/include/openspace/properties/matrix/mat3property.h b/include/openspace/properties/matrix/mat3property.h new file mode 100644 index 0000000000..b9451c2d55 --- /dev/null +++ b/include/openspace/properties/matrix/mat3property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___MAT3PROPERTY___H__ +#define __OPENSPACE_CORE___MAT3PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(Mat3Property, glm::mat3x3); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___MAT3PROPERTY___H__ diff --git a/include/openspace/properties/matrix/mat3x2property.h b/include/openspace/properties/matrix/mat3x2property.h new file mode 100644 index 0000000000..a8caac4361 --- /dev/null +++ b/include/openspace/properties/matrix/mat3x2property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___MAT3x2PROPERTY___H__ +#define __OPENSPACE_CORE___MAT3x2PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(Mat3x2Property, glm::mat3x2); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___MAT3x2PROPERTY___H__ diff --git a/include/openspace/properties/matrix/mat3x4property.h b/include/openspace/properties/matrix/mat3x4property.h new file mode 100644 index 0000000000..bf65b1857a --- /dev/null +++ b/include/openspace/properties/matrix/mat3x4property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___MAT3x4PROPERTY___H__ +#define __OPENSPACE_CORE___MAT3x4PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(Mat3x4Property, glm::mat3x4); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___MAT3x4PROPERTY___H__ diff --git a/include/openspace/properties/matrix/mat4property.h b/include/openspace/properties/matrix/mat4property.h new file mode 100644 index 0000000000..edbab9cda2 --- /dev/null +++ b/include/openspace/properties/matrix/mat4property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___MAT4PROPERTY___H__ +#define __OPENSPACE_CORE___MAT4PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(Mat4Property, glm::mat4x4); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___MAT4PROPERTY___H__ diff --git a/include/openspace/properties/matrix/mat4x2property.h b/include/openspace/properties/matrix/mat4x2property.h new file mode 100644 index 0000000000..19ae107a6c --- /dev/null +++ b/include/openspace/properties/matrix/mat4x2property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___MAT4x2PROPERTY___H__ +#define __OPENSPACE_CORE___MAT4x2PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(Mat4x2Property, glm::mat4x2); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___MAT4x2PROPERTY___H__ diff --git a/include/openspace/properties/matrix/mat4x3property.h b/include/openspace/properties/matrix/mat4x3property.h new file mode 100644 index 0000000000..17621ab924 --- /dev/null +++ b/include/openspace/properties/matrix/mat4x3property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___MAT4x3PROPERTY___H__ +#define __OPENSPACE_CORE___MAT4x3PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(Mat4x3Property, glm::mat4x3); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___MAT4x3PROPERTY___H__ diff --git a/include/openspace/properties/matrixproperty.h b/include/openspace/properties/matrixproperty.h index 572d840933..2b26259c11 100644 --- a/include/openspace/properties/matrixproperty.h +++ b/include/openspace/properties/matrixproperty.h @@ -22,36 +22,29 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __MATRIXPROPERTY_H__ -#define __MATRIXPROPERTY_H__ +#ifndef __OPENSPACE_CORE___MATRIXPROPERTY___H__ +#define __OPENSPACE_CORE___MATRIXPROPERTY___H__ #include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -namespace openspace { -namespace properties { +#include +#include +#include +#include +#include +#include +#include +#include +#include -REGISTER_NUMERICALPROPERTY_HEADER(Mat2Property, glm::mat2x2); -REGISTER_NUMERICALPROPERTY_HEADER(Mat2x3Property, glm::mat2x3); -REGISTER_NUMERICALPROPERTY_HEADER(Mat2x4Property, glm::mat2x4); -REGISTER_NUMERICALPROPERTY_HEADER(Mat3x2Property, glm::mat3x2); -REGISTER_NUMERICALPROPERTY_HEADER(Mat3Property, glm::mat3x3); -REGISTER_NUMERICALPROPERTY_HEADER(Mat3x4Property, glm::mat3x4); -REGISTER_NUMERICALPROPERTY_HEADER(Mat4x2Property, glm::mat4x2); -REGISTER_NUMERICALPROPERTY_HEADER(Mat4x3Property, glm::mat4x3); -REGISTER_NUMERICALPROPERTY_HEADER(Mat4Property, glm::mat4x4); -REGISTER_NUMERICALPROPERTY_HEADER(DMat2Property, glm::dmat2x2); -REGISTER_NUMERICALPROPERTY_HEADER(DMat2x3Property, glm::dmat2x3); -REGISTER_NUMERICALPROPERTY_HEADER(DMat2x4Property, glm::dmat2x4); -REGISTER_NUMERICALPROPERTY_HEADER(DMat3x2Property, glm::dmat3x2); -REGISTER_NUMERICALPROPERTY_HEADER(DMat3Property, glm::dmat3x3); -REGISTER_NUMERICALPROPERTY_HEADER(DMat3x4Property, glm::dmat3x4); -REGISTER_NUMERICALPROPERTY_HEADER(DMat4x2Property, glm::dmat4x2); -REGISTER_NUMERICALPROPERTY_HEADER(DMat4x3Property, glm::dmat4x3); -REGISTER_NUMERICALPROPERTY_HEADER(DMat4Property, glm::dmat4x4); - -} // namespace properties -} // namespace openspace - -#endif // __MATRIXPROPERTY_H__ +#endif // __OPENSPACE_CORE___MATRIXPROPERTY___H__ diff --git a/include/openspace/properties/numericalproperty.h b/include/openspace/properties/numericalproperty.h index ffa257a16c..2a5a5a3c7a 100644 --- a/include/openspace/properties/numericalproperty.h +++ b/include/openspace/properties/numericalproperty.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __NUMERICALPROPERTY_H__ -#define __NUMERICALPROPERTY_H__ +#ifndef __OPENSPACE_CORE___NUMERICALPROPERTY___H__ +#define __OPENSPACE_CORE___NUMERICALPROPERTY___H__ #include @@ -33,12 +33,16 @@ namespace properties { template class NumericalProperty : public TemplateProperty { public: - NumericalProperty(std::string identifier, std::string guiName); - NumericalProperty(std::string identifier, std::string guiName, T value); + NumericalProperty(std::string identifier, std::string guiName, + Property::Visibility visibility = Property::Visibility::User); NumericalProperty(std::string identifier, std::string guiName, T value, - T minimumValue, T maximumValue); + Property::Visibility visibility = Property::Visibility::User); NumericalProperty(std::string identifier, std::string guiName, T value, - T minimumValue, T maximumValue, T steppingValue); + T minimumValue, T maximumValue, + Property::Visibility visibility = Property::Visibility::User); + NumericalProperty(std::string identifier, std::string guiName, T value, + T minimumValue, T maximumValue, T steppingValue, + Property::Visibility visibility = Property::Visibility::User); bool getLuaValue(lua_State* state) const override; bool setLuaValue(lua_State* state) override; @@ -74,4 +78,4 @@ protected: #include "openspace/properties/numericalproperty.inl" -#endif // __NUMERICALPROPERTY_H__ +#endif // __OPENSPACE_CORE___NUMERICALPROPERTY___H__ diff --git a/include/openspace/properties/numericalproperty.inl b/include/openspace/properties/numericalproperty.inl index 86f04e8f62..89a47f9b66 100644 --- a/include/openspace/properties/numericalproperty.inl +++ b/include/openspace/properties/numericalproperty.inl @@ -233,42 +233,50 @@ const std::string NumericalProperty::SteppingValueKey = "SteppingValue"; // a single constructor template -NumericalProperty::NumericalProperty(std::string identifier, std::string guiName) +NumericalProperty::NumericalProperty(std::string identifier, std::string guiName, + Property::Visibility visibility) : NumericalProperty( std::move(identifier), std::move(guiName), PropertyDelegate>::template defaultValue(), PropertyDelegate>::template defaultMinimumValue(), PropertyDelegate>::template defaultMaximumValue(), - PropertyDelegate>::template defaultSteppingValue() - ) -{} - -template -NumericalProperty::NumericalProperty(std::string identifier, - std::string guiName, T value) - : NumericalProperty( - std::move(identifier), std::move(guiName), std::move(value), - PropertyDelegate>::template defaultMinimumValue(), - PropertyDelegate>::template defaultMaximumValue(), - PropertyDelegate>::template defaultSteppingValue() - ) -{} - -template -NumericalProperty::NumericalProperty(std::string identifier, std::string guiName, - T value, T minimumValue, T maximumValue) - : NumericalProperty( - std::move(identifier) , std::move(guiName), std::move(value), - std::move(minimumValue), std::move(maximumValue), - PropertyDelegate>::template defaultSteppingValue() + PropertyDelegate>::template defaultSteppingValue(), + visibility ) {} template NumericalProperty::NumericalProperty(std::string identifier, std::string guiName, T value, - T minimumValue, T maximumValue, T steppingValue) - : TemplateProperty(std::move(identifier), std::move(guiName), std::move(value)) + Property::Visibility visibility) + : NumericalProperty( + std::move(identifier), std::move(guiName), std::move(value), + PropertyDelegate>::template defaultMinimumValue(), + PropertyDelegate>::template defaultMaximumValue(), + PropertyDelegate>::template defaultSteppingValue(), + visibility + ) +{} + +template +NumericalProperty::NumericalProperty(std::string identifier, std::string guiName, + T value, T minimumValue, T maximumValue, + Property::Visibility visibility) + : NumericalProperty( + std::move(identifier) , std::move(guiName), std::move(value), + std::move(minimumValue), std::move(maximumValue), + PropertyDelegate>::template defaultSteppingValue(), + visibility + ) +{} + +template +NumericalProperty::NumericalProperty(std::string identifier, + std::string guiName, T value, + T minimumValue, T maximumValue, T steppingValue, + Property::Visibility visibility) + : TemplateProperty(std::move(identifier), std::move(guiName), std::move(value), + visibility) , _minimumValue(std::move(minimumValue)) , _maximumValue(std::move(maximumValue)) , _stepping(std::move(steppingValue)) diff --git a/include/openspace/properties/optionproperty.h b/include/openspace/properties/optionproperty.h index 39466779cf..4263120deb 100644 --- a/include/openspace/properties/optionproperty.h +++ b/include/openspace/properties/optionproperty.h @@ -22,10 +22,10 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __OPTIONPROPERTY_H__ -#define __OPTIONPROPERTY_H__ +#ifndef __OPENSPACE_CORE___OPTIONPROPERTY___H__ +#define __OPENSPACE_CORE___OPTIONPROPERTY___H__ -#include +#include #include @@ -51,8 +51,8 @@ public: }; enum class DisplayType { - RADIO, - DROPDOWN + Radio, + Dropdown }; /** @@ -61,7 +61,8 @@ public: * \param identifier A unique identifier for this property * \param guiName The GUI name that should be used to represent this property */ - OptionProperty(std::string identifier, std::string guiName); + OptionProperty(std::string identifier, std::string guiName, + Property::Visibility visibility = Property::Visibility::User); /** * The constructor delegating the identifier and the guiName @@ -70,7 +71,8 @@ public: * \param guiName The GUI name that should be used to represent this property * \param displayType Optional DisplayType for GUI (default RADIO) */ - OptionProperty(std::string identifier, std::string guiName, DisplayType displayType); + OptionProperty(std::string identifier, std::string guiName, DisplayType displayType, + Property::Visibility visibility = Property::Visibility::User); /** * Returns the name of the class for reflection purposes. @@ -95,11 +97,11 @@ public: void addOption(int value, std::string desc); /** - * Appends options with vectors of values and descriptions - * \param values A std::vector of values for the options - * \param descs A std::vector of descriptions for each value + * Adds multiple options to the OptionProperty. Each value in the vector consists of + * an integer value and a string description. + * \param options Pairs of that are added to the OptionProperty */ - void addOptions(std::vector values, std::vector descs); + void addOptions(std::vector> options); /** * Returns the list of available options. @@ -132,4 +134,4 @@ private: } // namespace properties } // namespace openspace -#endif // __STRINGPROPERTY_H__ +#endif // __OPENSPACE_CORE___OPTIONPROPERTY___H__ diff --git a/include/openspace/properties/property.h b/include/openspace/properties/property.h index c3cdb71572..0baa569612 100644 --- a/include/openspace/properties/property.h +++ b/include/openspace/properties/property.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __PROPERTY_H__ -#define __PROPERTY_H__ +#ifndef __OPENSPACE_CORE___PROPERTY___H__ +#define __OPENSPACE_CORE___PROPERTY___H__ #include @@ -62,6 +62,17 @@ class PropertyOwner; */ class Property { public: + /** + * The visibility classes for Property%s. The classes are strictly ordered as + * All > Developer > User > None + */ + enum class Visibility { + All = 3, ///< Visible for all types, no matter what + Developer = 2, ///< Visible in Developer mode + User = 1, ///< Visible in User mode + None = 0 ///< Never visible + }; + /** * The constructor for the property. The identifier needs to be unique * for each PropertyOwner. The guiName will be stored in the metaData @@ -74,7 +85,8 @@ public: * \pre \p identifier must not be empty * \pre \p guiName must not be empty */ - Property(std::string identifier, std::string guiName); + Property(std::string identifier, std::string guiName, + Visibility visibility = Visibility::All); /** * The destructor taking care of deallocating all unused memory. This method will not @@ -255,20 +267,18 @@ public: std::string groupIdentifier() const; /** - * Determines a hint if this Property should be visible, or hidden. Each application - * accessing the properties is free to ignore this hint. It is stored in the metaData - * Dictionary with the key: isVisible. The default value is - * true. - * \param state true if the Property should be visible, - * false otherwise. + * Sets a hint about the visibility of the Property. Each application accessing the + * properties is free to ignore this hint. It is stored in the metaData Dictionary + * with the key: Visibility. + * \param visibility The new visibility of the Property */ - void setVisible(bool state); + void setVisibility(Visibility visibility); /** - * Returns whether this Property is visible or not. - * \return Whether this Property is visible or hidden + * Returns this Property%'s visibility setting + * \return This Property%'s visibility setting */ - bool isVisible() const; + Visibility visibility() const; /** * This method determines if this Property should be read-only in external @@ -378,4 +388,4 @@ protected: } // namespace properties } // namespace openspace -#endif // __PROPERTY_H__ +#endif // __OPENSPACE_CORE___PROPERTY___H__ diff --git a/include/openspace/properties/propertydelegate.h b/include/openspace/properties/propertydelegate.h index 7ce86e2566..ff63e25fa7 100644 --- a/include/openspace/properties/propertydelegate.h +++ b/include/openspace/properties/propertydelegate.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __PROPERTYDELEGATE_H__ -#define __PROPERTYDELEGATE_H__ +#ifndef __OPENSPACE_CORE___PROPERTYDELEGATE___H__ +#define __OPENSPACE_CORE___PROPERTYDELEGATE___H__ #include @@ -163,4 +163,4 @@ public: #include -#endif // __PROPERTYDELEGATE_H__ +#endif // __OPENSPACE_CORE___PROPERTYDELEGATE___H__ diff --git a/include/openspace/properties/propertyowner.h b/include/openspace/properties/propertyowner.h index 1c2de04952..51b26dac96 100644 --- a/include/openspace/properties/propertyowner.h +++ b/include/openspace/properties/propertyowner.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __PROPERTYOWNER_H__ -#define __PROPERTYOWNER_H__ +#ifndef __OPENSPACE_CORE___PROPERTYOWNER___H__ +#define __OPENSPACE_CORE___PROPERTYOWNER___H__ #include #include @@ -222,4 +222,4 @@ private: } // namespace properties } // namespace openspace -#endif // __PROPERTYOWNER_H__ +#endif // __OPENSPACE_CORE___PROPERTYOWNER___H__ diff --git a/include/openspace/properties/scalar/boolproperty.h b/include/openspace/properties/scalar/boolproperty.h new file mode 100644 index 0000000000..e615368b1c --- /dev/null +++ b/include/openspace/properties/scalar/boolproperty.h @@ -0,0 +1,53 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___BOOLPROPERTY___H__ +#define __OPENSPACE_CORE___BOOLPROPERTY___H__ + + /** + * \file boolproperty.h + * + * \addtogroup openspace + * @{ + * \addtogroup properties + * @{ + + * \class BoolProperty + * This class is a concrete implementation of openspace::properties::TemplateProperty with + * the type bool. + + * @} @} + */ + +#include + +namespace openspace { +namespace properties { + +REGISTER_TEMPLATEPROPERTY_HEADER(BoolProperty, bool); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___BOOLPROPERTY___H__ diff --git a/include/openspace/properties/scalar/charproperty.h b/include/openspace/properties/scalar/charproperty.h new file mode 100644 index 0000000000..3357d47c7e --- /dev/null +++ b/include/openspace/properties/scalar/charproperty.h @@ -0,0 +1,53 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___CHARPROPERTY___H__ +#define __OPENSPACE_CORE___CHARPROPERTY___H__ + + /** + * \file charproperty.h + * + * \addtogroup openspace + * @{ + * \addtogroup properties + * @{ + + * \class CharProperty + * This class is a concrete implementation of openspace::properties::TemplateProperty with + * the type char. + + * @} @} + */ + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(CharProperty, char); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___CHARPROPERTY___H__ diff --git a/include/openspace/properties/scalar/doubleproperty.h b/include/openspace/properties/scalar/doubleproperty.h new file mode 100644 index 0000000000..f47abe8b85 --- /dev/null +++ b/include/openspace/properties/scalar/doubleproperty.h @@ -0,0 +1,53 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___DOUBLEPROPERTY___H__ +#define __OPENSPACE_CORE___DOUBLEPROPERTY___H__ + + /** + * \file doubleproperty.h + * + * \addtogroup openspace + * @{ + * \addtogroup properties + * @{ + + * \class DoubleProperty + * This class is a concrete implementation of openspace::properties::TemplateProperty with + * the type double. + + * @} @} + */ + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(DoubleProperty, double); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___DOUBLEPROPERTY___H__ diff --git a/include/openspace/properties/scalar/floatproperty.h b/include/openspace/properties/scalar/floatproperty.h new file mode 100644 index 0000000000..11acdebbb4 --- /dev/null +++ b/include/openspace/properties/scalar/floatproperty.h @@ -0,0 +1,53 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___FLOATPROPERTY___H__ +#define __OPENSPACE_CORE___FLOATPROPERTY___H__ + + /** + * \file floatproperty.h + * + * \addtogroup openspace + * @{ + * \addtogroup properties + * @{ + + * \class FloatProperty + * This class is a concrete implementation of openspace::properties::TemplateProperty with + * the type float. + + * @} @} + */ + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(FloatProperty, float); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___FLOATPROPERTY___H__ diff --git a/modules/base/shaders/deltaE_calc_fs.glsl b/include/openspace/properties/scalar/intproperty.h similarity index 77% rename from modules/base/shaders/deltaE_calc_fs.glsl rename to include/openspace/properties/scalar/intproperty.h index b68cebd774..3aa9f82b62 100644 --- a/modules/base/shaders/deltaE_calc_fs.glsl +++ b/include/openspace/properties/scalar/intproperty.h @@ -21,28 +21,33 @@ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___INTPROPERTY___H__ +#define __OPENSPACE_CORE___INTPROPERTY___H__ + + /** + * \file intproperty.h + * + * \addtogroup openspace + * @{ + * \addtogroup properties + * @{ -#include "atmosphere_common.glsl" -#include "fragment.glsl" -#include "PowerScaling/powerScalingMath.hglsl" + * \class IntProperty + * This class is a concrete implementation of openspace::properties::TemplateProperty with + * the type int. -layout(location = 1) out vec4 renderTableColor; + * @} @} + */ -// See paper algorithm -uniform int line; -uniform sampler2D deltaETexture; +#include -Fragment getFragment() { - if (line == 4) - renderTableColor = vec4(0.0); - else if (line == 10) { - vec2 uv = gl_FragCoord.xy / vec2(OTHER_TEXTURES_W, OTHER_TEXTURES_H); - renderTableColor = texture(deltaETexture, uv); - } - - Fragment frag; - frag.color = vec4(1.0); - frag.depth = 1.0; - - return frag; -} \ No newline at end of file +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(IntProperty, int); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___INTPROPERTY___H__ diff --git a/include/openspace/properties/scalar/longdoubleproperty.h b/include/openspace/properties/scalar/longdoubleproperty.h new file mode 100644 index 0000000000..40358f602b --- /dev/null +++ b/include/openspace/properties/scalar/longdoubleproperty.h @@ -0,0 +1,53 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___LONGDOUBLEPROPERTY___H__ +#define __OPENSPACE_CORE___LONGDOUBLEPROPERTY___H__ + + /** + * \file longdoubleproperty.h + * + * \addtogroup openspace + * @{ + * \addtogroup properties + * @{ + + * \class LongDoubleProperty + * This class is a concrete implementation of openspace::properties::TemplateProperty with + * the type long double. + + * @} @} + */ + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(LongDoubleProperty, long double); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___LONGDOUBLEPROPERTY___H__ diff --git a/include/openspace/properties/scalar/longlongproperty.h b/include/openspace/properties/scalar/longlongproperty.h new file mode 100644 index 0000000000..65e176e09d --- /dev/null +++ b/include/openspace/properties/scalar/longlongproperty.h @@ -0,0 +1,53 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___LONGLONGPROPERTY___H__ +#define __OPENSPACE_CORE___LONGLONGPROPERTY___H__ + + /** + * \file longlongproperty.h + * + * \addtogroup openspace + * @{ + * \addtogroup properties + * @{ + + * \class LongLongProperty + * This class is a concrete implementation of openspace::properties::TemplateProperty with + * the type long long. + + * @} @} + */ + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(LongLongProperty, long long); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___LONGLONGPROPERTY___H__ diff --git a/include/openspace/properties/scalar/longproperty.h b/include/openspace/properties/scalar/longproperty.h new file mode 100644 index 0000000000..444fc6c15a --- /dev/null +++ b/include/openspace/properties/scalar/longproperty.h @@ -0,0 +1,53 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___LONGPROPERTY___H__ +#define __OPENSPACE_CORE___LONGPROPERTY___H__ + + /** + * \file longproperty.h + * + * \addtogroup openspace + * @{ + * \addtogroup properties + * @{ + + * \class LongProperty + * This class is a concrete implementation of openspace::properties::TemplateProperty with + * the type long. + + * @} @} + */ + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(LongProperty, long); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___LONGPROPERTY___H__ diff --git a/include/openspace/properties/scalar/shortproperty.h b/include/openspace/properties/scalar/shortproperty.h new file mode 100644 index 0000000000..da37c72a60 --- /dev/null +++ b/include/openspace/properties/scalar/shortproperty.h @@ -0,0 +1,53 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___SHORTPROPERTY___H__ +#define __OPENSPACE_CORE___SHORTPROPERTY___H__ + + /** + * \file shortproperty.h + * + * \addtogroup openspace + * @{ + * \addtogroup properties + * @{ + + * \class ShortProperty + * This class is a concrete implementation of openspace::properties::TemplateProperty with + * the type short. + + * @} @} + */ + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(ShortProperty, short); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___SHORTPROPERTY___H__ diff --git a/include/openspace/properties/scalar/signedcharproperty.h b/include/openspace/properties/scalar/signedcharproperty.h new file mode 100644 index 0000000000..2ff7ff0d03 --- /dev/null +++ b/include/openspace/properties/scalar/signedcharproperty.h @@ -0,0 +1,53 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___SIGNEDCHARPROPERTY___H__ +#define __OPENSPACE_CORE___SIGNEDCHARPROPERTY___H__ + + /** + * \file signedcharproperty.h + * + * \addtogroup openspace + * @{ + * \addtogroup properties + * @{ + + * \class SignedCharProperty + * This class is a concrete implementation of openspace::properties::TemplateProperty with + * the type signed char. + + * @} @} + */ + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(SignedCharProperty, signed char); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___SIGNEDCHARPROPERTY___H__ diff --git a/include/openspace/properties/scalar/ucharproperty.h b/include/openspace/properties/scalar/ucharproperty.h new file mode 100644 index 0000000000..c91b5051b5 --- /dev/null +++ b/include/openspace/properties/scalar/ucharproperty.h @@ -0,0 +1,53 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___UCHARPROPERTY___H__ +#define __OPENSPACE_CORE___UCHARPROPERTY___H__ + + /** + * \file ucharproperty.h + * + * \addtogroup openspace + * @{ + * \addtogroup properties + * @{ + + * \class UCharProperty + * This class is a concrete implementation of openspace::properties::TemplateProperty with + * the type unsigned char. + + * @} @} + */ + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(UCharProperty, unsigned char); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___UCHARPROPERTY___H__ diff --git a/include/openspace/properties/scalar/uintproperty.h b/include/openspace/properties/scalar/uintproperty.h new file mode 100644 index 0000000000..bf83adc31f --- /dev/null +++ b/include/openspace/properties/scalar/uintproperty.h @@ -0,0 +1,53 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___UINTPROPERTY___H__ +#define __OPENSPACE_CORE___UINTPROPERTY___H__ + + /** + * \file uintproperty.h + * + * \addtogroup openspace + * @{ + * \addtogroup properties + * @{ + + * \class UIntProperty + * This class is a concrete implementation of openspace::properties::TemplateProperty with + * the type unsigned int. + + * @} @} + */ + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(UIntProperty, unsigned int); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___UINTPROPERTY___H__ diff --git a/include/openspace/properties/scalar/ulonglongproperty.h b/include/openspace/properties/scalar/ulonglongproperty.h new file mode 100644 index 0000000000..045da7a9b9 --- /dev/null +++ b/include/openspace/properties/scalar/ulonglongproperty.h @@ -0,0 +1,53 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___ULONGLONGPROPERTY___H__ +#define __OPENSPACE_CORE___ULONGLONGPROPERTY___H__ + + /** + * \file ulonglongproperty.h + * + * \addtogroup openspace + * @{ + * \addtogroup properties + * @{ + + * \class ULongLongProperty + * This class is a concrete implementation of openspace::properties::TemplateProperty with + * the type unsigned long long. + + * @} @} + */ + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(ULongLongProperty, unsigned long long); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___ULONGLONGPROPERTY___H__ diff --git a/include/openspace/properties/scalar/ulongproperty.h b/include/openspace/properties/scalar/ulongproperty.h new file mode 100644 index 0000000000..4350c0ae46 --- /dev/null +++ b/include/openspace/properties/scalar/ulongproperty.h @@ -0,0 +1,53 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___ULONGPROPERTY___H__ +#define __OPENSPACE_CORE___ULONGPROPERTY___H__ + + /** + * \file ulongproperty.h + * + * \addtogroup openspace + * @{ + * \addtogroup properties + * @{ + + * \class ULongProperty + * This class is a concrete implementation of openspace::properties::TemplateProperty with + * the type unsigned long. + + * @} @} + */ + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(ULongProperty, unsigned long); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___ULONGPROPERTY___H__ diff --git a/include/openspace/properties/scalar/ushortproperty.h b/include/openspace/properties/scalar/ushortproperty.h new file mode 100644 index 0000000000..9c2d20320d --- /dev/null +++ b/include/openspace/properties/scalar/ushortproperty.h @@ -0,0 +1,53 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___USHORTPROPERTY___H__ +#define __OPENSPACE_CORE___USHORTPROPERTY___H__ + + /** + * \file ushortproperty.h + * + * \addtogroup openspace + * @{ + * \addtogroup properties + * @{ + + * \class UShortProperty + * This class is a concrete implementation of openspace::properties::TemplateProperty with + * the type unsigned short. + + * @} @} + */ + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(UShortProperty, unsigned short); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___USHORTPROPERTY___H__ diff --git a/include/openspace/properties/scalar/wcharproperty.h b/include/openspace/properties/scalar/wcharproperty.h new file mode 100644 index 0000000000..d19a460884 --- /dev/null +++ b/include/openspace/properties/scalar/wcharproperty.h @@ -0,0 +1,53 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___WCHARPROPERTY___H__ +#define __OPENSPACE_CORE___WCHARPROPERTY___H__ + + /** + * \file wcharproperty.h + * + * \addtogroup openspace + * @{ + * \addtogroup properties + * @{ + + * \class WCharProperty + * This class is a concrete implementation of openspace::properties::TemplateProperty with + * the type wchar_t. + + * @} @} + */ + +#include + +namespace openspace { +namespace properties { + +//REGISTER_NUMERICALPROPERTY_HEADER(WCharProperty, wchar_t); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___WCHARPROPERTY___H__ diff --git a/include/openspace/properties/scalarproperty.h b/include/openspace/properties/scalarproperty.h index 7576edd37d..16c620c3e9 100644 --- a/include/openspace/properties/scalarproperty.h +++ b/include/openspace/properties/scalarproperty.h @@ -22,103 +22,26 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SCALARPROPERTY_H__ -#define __SCALARPROPERTY_H__ +#ifndef __OPENSPACE_CORE___SCALARPROPERTY___H__ +#define __OPENSPACE_CORE___SCALARPROPERTY___H__ - /** - * \file scalarproperty.h - * - * \addtogroup openspace - * @{ - * \addtogroup properties - * @{ - - * \class BoolProperty - * This class is a concrete implementation of openspace::properties::TemplateProperty with - * the type bool. +#include - * \class CharProperty - * This class is a concrete implementation of openspace::properties::TemplateProperty with - * the type char. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include - * \class SignedCharProperty - * This class is a concrete implementation of openspace::properties::TemplateProperty with - * the type signed char. - - * \class UCharProperty - * This class is a concrete implementation of openspace::properties::TemplateProperty with - * the type unsigned char. - - * \class ShortProperty - * This class is a concrete implementation of openspace::properties::TemplateProperty with - * the type short. - - * \class UShortProperty - * This class is a concrete implementation of openspace::properties::TemplateProperty with - * the type unsigned short. - - * \class IntProperty - * This class is a concrete implementation of openspace::properties::TemplateProperty with - * the type int. - - * \class UIntProperty - * This class is a concrete implementation of openspace::properties::TemplateProperty with - * the type unsigned int. - - * \class LongProperty - * This class is a concrete implementation of openspace::properties::TemplateProperty with - * the type long. - - * \class ULongProperty - * This class is a concrete implementation of openspace::properties::TemplateProperty with - * the type unsigned long. - - * \class LongLongProperty - * This class is a concrete implementation of openspace::properties::TemplateProperty with - * the type long long. - - * \class ULongLongProperty - * This class is a concrete implementation of openspace::properties::TemplateProperty with - * the type unsigned long long. - - * \class FloatProperty - * This class is a concrete implementation of openspace::properties::TemplateProperty with - * the type float. - - * \class DoubleProperty - * This class is a concrete implementation of openspace::properties::TemplateProperty with - * the type double. - - * \class LongDoubleProperty - * This class is a concrete implementation of openspace::properties::TemplateProperty with - * the type long double. - - * @} @} - */ - -#include "openspace/properties/numericalproperty.h" - -namespace openspace { -namespace properties { - -REGISTER_TEMPLATEPROPERTY_HEADER(BoolProperty, bool); -REGISTER_NUMERICALPROPERTY_HEADER(CharProperty, char); -//REGISTER_NUMERICALPROPERTY_HEADER(WCharProperty, wchar_t); -REGISTER_NUMERICALPROPERTY_HEADER(SignedCharProperty, signed char); -REGISTER_NUMERICALPROPERTY_HEADER(UCharProperty, unsigned char); -REGISTER_NUMERICALPROPERTY_HEADER(ShortProperty, short); -REGISTER_NUMERICALPROPERTY_HEADER(UShortProperty, unsigned short); -REGISTER_NUMERICALPROPERTY_HEADER(IntProperty, int); -REGISTER_NUMERICALPROPERTY_HEADER(UIntProperty, unsigned int); -REGISTER_NUMERICALPROPERTY_HEADER(LongProperty, long); -REGISTER_NUMERICALPROPERTY_HEADER(ULongProperty, unsigned long); -REGISTER_NUMERICALPROPERTY_HEADER(LongLongProperty, long long); -REGISTER_NUMERICALPROPERTY_HEADER(ULongLongProperty, unsigned long long); -REGISTER_NUMERICALPROPERTY_HEADER(FloatProperty, float); -REGISTER_NUMERICALPROPERTY_HEADER(DoubleProperty, double); -REGISTER_NUMERICALPROPERTY_HEADER(LongDoubleProperty, long double); - -} // namespace properties -} // namespace openspace - -#endif // __SCALARPROPERTY_H__ +#endif // __OPENSPACE_CORE___SCALARPROPERTY___H__ diff --git a/include/openspace/properties/selectionproperty.h b/include/openspace/properties/selectionproperty.h index b86aea9870..39dc560508 100644 --- a/include/openspace/properties/selectionproperty.h +++ b/include/openspace/properties/selectionproperty.h @@ -22,10 +22,10 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SELECTIONPROPERTY_H__ -#define __SELECTIONPROPERTY_H__ +#ifndef __OPENSPACE_CORE___SELECTIONPROPERTY___H__ +#define __OPENSPACE_CORE___SELECTIONPROPERTY___H__ -#include +#include #include @@ -39,7 +39,8 @@ public: std::string description; }; - SelectionProperty(std::string identifier, std::string guiName); + SelectionProperty(std::string identifier, std::string guiName, + Property::Visibility visibility = Property::Visibility::User); void addOption(Option option); void removeOptions(); @@ -79,4 +80,4 @@ bool PropertyDelegate>>::toString(std::string& } // namespace properties } // namespace openspace -#endif // __SELECTIONPROPERTY_H__ +#endif // __OPENSPACE_CORE___SELECTIONPROPERTY___H__ diff --git a/include/openspace/properties/stringproperty.h b/include/openspace/properties/stringproperty.h index eb01a2dc07..d6840cd016 100644 --- a/include/openspace/properties/stringproperty.h +++ b/include/openspace/properties/stringproperty.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __STRINGPROPERTY_H__ -#define __STRINGPROPERTY_H__ +#ifndef __OPENSPACE_CORE___STRINGPROPERTY___H__ +#define __OPENSPACE_CORE___STRINGPROPERTY___H__ #include @@ -35,4 +35,4 @@ REGISTER_TEMPLATEPROPERTY_HEADER(StringProperty, std::string); } // namespace properties } // namespace openspace -#endif // __STRINGPROPERTY_H__ +#endif // __OPENSPACE_CORE___STRINGPROPERTY___H__ diff --git a/include/openspace/properties/templateproperty.h b/include/openspace/properties/templateproperty.h index c2d364540a..a562b59020 100644 --- a/include/openspace/properties/templateproperty.h +++ b/include/openspace/properties/templateproperty.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __TEMPLATEPROPERTY_H__ -#define __TEMPLATEPROPERTY_H__ +#ifndef __OPENSPACE_CORE___TEMPLATEPROPERTY___H__ +#define __OPENSPACE_CORE___TEMPLATEPROPERTY___H__ #include @@ -63,14 +63,16 @@ public: * \param identifier The identifier that is used for this TemplateProperty * \param guiName The human-readable GUI name for this TemplateProperty */ - TemplateProperty(std::string identifier, std::string guiName); + TemplateProperty(std::string identifier, std::string guiName, + Property::Visibility visibility = Visibility::User); /** * The constructor initializing the TemplateProperty with the provided * identifier, human-readable guiName and provided * value. */ - TemplateProperty(std::string identifier, std::string guiName, T value); + TemplateProperty(std::string identifier, std::string guiName, T value, + Property::Visibility visibility = Visibility::User); /** * Returns the class name for this TemplateProperty. The default implementation makes @@ -189,4 +191,4 @@ protected: #include "openspace/properties/templateproperty.inl" -#endif // __TEMPLATEPROPERTY_H__ +#endif // __OPENSPACE_CORE___TEMPLATEPROPERTY___H__ diff --git a/include/openspace/properties/templateproperty.inl b/include/openspace/properties/templateproperty.inl index ec8f8509a6..bacccfafe6 100644 --- a/include/openspace/properties/templateproperty.inl +++ b/include/openspace/properties/templateproperty.inl @@ -149,19 +149,21 @@ namespace properties { // a single constructor template -TemplateProperty::TemplateProperty(std::string identifier, std::string guiName) +TemplateProperty::TemplateProperty(std::string identifier, std::string guiName, + Property::Visibility visibility) : TemplateProperty( std::move(identifier), std::move(guiName), - PropertyDelegate>::template defaultValue()) + PropertyDelegate>::template defaultValue(), + visibility) { } template TemplateProperty::TemplateProperty(std::string identifier, std::string guiName, - T value) - : Property(std::move(identifier), std::move(guiName)) - , _value(std::move(value)) { -} + T value, Property::Visibility visibility) + : Property(std::move(identifier), std::move(guiName), visibility) + , _value(std::move(value)) +{} template std::string TemplateProperty::className() const { diff --git a/include/openspace/properties/triggerproperty.h b/include/openspace/properties/triggerproperty.h index dd43f58fc4..c6bcf6c9e9 100644 --- a/include/openspace/properties/triggerproperty.h +++ b/include/openspace/properties/triggerproperty.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __TRIGGERPROPERTY_H__ -#define __TRIGGERPROPERTY_H__ +#ifndef __OPENSPACE_CORE___TRIGGERPROPERTY___H__ +#define __OPENSPACE_CORE___TRIGGERPROPERTY___H__ #include @@ -42,7 +42,8 @@ public: * \param identifier The unique identifier used for this Property * \param guiName The human-readable name of this Property */ - TriggerProperty(std::string identifier, std::string guiName); + TriggerProperty(std::string identifier, std::string guiName, + Property::Visibility visibility = Property::Visibility::User); /** * Returns the class name TriggerProperty. @@ -69,4 +70,4 @@ public: } // namespace properties } // namespace openspace -#endif // __TRIGGERPROPERTY_H__ +#endif // __OPENSPACE_CORE___TRIGGERPROPERTY___H__ diff --git a/include/openspace/properties/ucharproperty.h b/include/openspace/properties/ucharproperty.h new file mode 100644 index 0000000000..f0d7de59ef --- /dev/null +++ b/include/openspace/properties/ucharproperty.h @@ -0,0 +1,53 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __UCHARPROPERTY_H__ +#define __UCHARPROPERTY_H__ + + /** + * \file ucharproperty.h + * + * \addtogroup openspace + * @{ + * \addtogroup properties + * @{ + + * \class UCharProperty + * This class is a concrete implementation of openspace::properties::TemplateProperty with + * the type unsigned char. + + * @} @} + */ + +#include "openspace/properties/numericalproperty.h" + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(UCharProperty, unsigned char); + +} // namespace properties +} // namespace openspace + +#endif // __UCHARPROPERTY_H__ diff --git a/modules/base/shaders/inScattering_sup_calc_gs.glsl b/include/openspace/properties/uintproperty.h similarity index 78% rename from modules/base/shaders/inScattering_sup_calc_gs.glsl rename to include/openspace/properties/uintproperty.h index 8ca6044fd1..2e4b50b103 100644 --- a/modules/base/shaders/inScattering_sup_calc_gs.glsl +++ b/include/openspace/properties/uintproperty.h @@ -21,21 +21,33 @@ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ + +#ifndef __UINTPROPERTY_H__ +#define __UINTPROPERTY_H__ + + /** + * \file uintproperty.h + * + * \addtogroup openspace + * @{ + * \addtogroup properties + * @{ -#version __CONTEXT__ + * \class UIntProperty + * This class is a concrete implementation of openspace::properties::TemplateProperty with + * the type unsigned int. -uniform int layer; + * @} @} + */ -layout (triangles) in; -layout (triangle_strip, max_vertices = 3) out; +#include "openspace/properties/numericalproperty.h" -void main() -{ - int n; - for (n = 0; n < gl_in.length(); ++n) { - gl_Position = gl_in[n].gl_Position; - gl_Layer = layer; - EmitVertex(); - } - EndPrimitive(); -} \ No newline at end of file +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(UIntProperty, unsigned int); + +} // namespace properties +} // namespace openspace + +#endif // __UINTPROPERTY_H__ diff --git a/include/openspace/properties/vector/bvec2property.h b/include/openspace/properties/vector/bvec2property.h new file mode 100644 index 0000000000..79d94c97e8 --- /dev/null +++ b/include/openspace/properties/vector/bvec2property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___BVEC2PROPERTY___H__ +#define __OPENSPACE_CORE___BVEC2PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_TEMPLATEPROPERTY_HEADER(BVec2Property, glm::bvec2); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___BVEC2PROPERTY___H__ diff --git a/include/openspace/properties/vector/bvec3property.h b/include/openspace/properties/vector/bvec3property.h new file mode 100644 index 0000000000..4dbfc678b0 --- /dev/null +++ b/include/openspace/properties/vector/bvec3property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___BVEC3PROPERTY___H__ +#define __OPENSPACE_CORE___BVEC3PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_TEMPLATEPROPERTY_HEADER(BVec3Property, glm::bvec3); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___BVEC3PROPERTY___H__ diff --git a/include/openspace/properties/vector/bvec4property.h b/include/openspace/properties/vector/bvec4property.h new file mode 100644 index 0000000000..9912c72506 --- /dev/null +++ b/include/openspace/properties/vector/bvec4property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___BVEC4PROPERTY___H__ +#define __OPENSPACE_CORE___BVEC4PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_TEMPLATEPROPERTY_HEADER(BVec4Property, glm::bvec4); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___BVEC4PROPERTY___H__ diff --git a/include/openspace/properties/vector/dvec2property.h b/include/openspace/properties/vector/dvec2property.h new file mode 100644 index 0000000000..2ad7df993f --- /dev/null +++ b/include/openspace/properties/vector/dvec2property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___DVEC2PROPERTY___H__ +#define __OPENSPACE_CORE___DVEC2PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(DVec2Property, glm::dvec2); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___DVEC2PROPERTY___H__ diff --git a/include/openspace/properties/vector/dvec3property.h b/include/openspace/properties/vector/dvec3property.h new file mode 100644 index 0000000000..57463d6c41 --- /dev/null +++ b/include/openspace/properties/vector/dvec3property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___DVEC3PROPERTY___H__ +#define __OPENSPACE_CORE___DVEC3PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(DVec3Property, glm::dvec3); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___DVEC3PROPERTY___H__ diff --git a/include/openspace/properties/vector/dvec4property.h b/include/openspace/properties/vector/dvec4property.h new file mode 100644 index 0000000000..eae10fe920 --- /dev/null +++ b/include/openspace/properties/vector/dvec4property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___DVEC4PROPERTY___H__ +#define __OPENSPACE_CORE___DVEC4PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(DVec4Property, glm::dvec4); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___DVEC4PROPERTY___H__ diff --git a/include/openspace/properties/vector/ivec2property.h b/include/openspace/properties/vector/ivec2property.h new file mode 100644 index 0000000000..3c70c7a915 --- /dev/null +++ b/include/openspace/properties/vector/ivec2property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___IVEC2PROPERTY___H__ +#define __OPENSPACE_CORE___IVEC2PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(IVec2Property, glm::ivec2); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___IVEC2PROPERTY___H__ diff --git a/include/openspace/properties/vector/ivec3property.h b/include/openspace/properties/vector/ivec3property.h new file mode 100644 index 0000000000..f1a61401c9 --- /dev/null +++ b/include/openspace/properties/vector/ivec3property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___IVEC3PROPERTY___H__ +#define __OPENSPACE_CORE___IVEC3PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(IVec3Property, glm::ivec3); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___IVEC3PROPERTY___H__ diff --git a/include/openspace/properties/vector/ivec4property.h b/include/openspace/properties/vector/ivec4property.h new file mode 100644 index 0000000000..c4baa75d08 --- /dev/null +++ b/include/openspace/properties/vector/ivec4property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___IVEC4PROPERTY___H__ +#define __OPENSPACE_CORE___IVEC4PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(IVec4Property, glm::ivec4); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___IVEC4PROPERTY___H__ diff --git a/include/openspace/properties/vector/uvec2property.h b/include/openspace/properties/vector/uvec2property.h new file mode 100644 index 0000000000..48a2629432 --- /dev/null +++ b/include/openspace/properties/vector/uvec2property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___UVEC2PROPERTY___H__ +#define __OPENSPACE_CORE___UVEC2PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(UVec2Property, glm::uvec2); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___UVEC2PROPERTY___H__ diff --git a/include/openspace/properties/vector/uvec3property.h b/include/openspace/properties/vector/uvec3property.h new file mode 100644 index 0000000000..defc195ec1 --- /dev/null +++ b/include/openspace/properties/vector/uvec3property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___UVEC3PROPERTY___H__ +#define __OPENSPACE_CORE___UVEC3PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(UVec3Property, glm::uvec3); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___UVEC3PROPERTY___H__ diff --git a/include/openspace/properties/vector/uvec4property.h b/include/openspace/properties/vector/uvec4property.h new file mode 100644 index 0000000000..e750f00e6a --- /dev/null +++ b/include/openspace/properties/vector/uvec4property.h @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___UVEC4PROPERTY___H__ +#define __OPENSPACE_CORE___UVEC4PROPERTY___H__ + +#include + +#include + +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(UVec4Property, glm::uvec4); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___UVEC4PROPERTY___H__ diff --git a/modules/base/shaders/inScattering_calc_gs.glsl b/include/openspace/properties/vector/vec2property.h similarity index 84% rename from modules/base/shaders/inScattering_calc_gs.glsl rename to include/openspace/properties/vector/vec2property.h index aed3744bd2..ad26b1e9c4 100644 --- a/modules/base/shaders/inScattering_calc_gs.glsl +++ b/include/openspace/properties/vector/vec2property.h @@ -22,20 +22,19 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#version __CONTEXT__ +#ifndef __OPENSPACE_CORE___VEC2PROPERTY___H__ +#define __OPENSPACE_CORE___VEC2PROPERTY___H__ -uniform int layer; +#include -layout (triangles) in; -layout (triangle_strip, max_vertices=3) out; +#include -void main() -{ - int n; - for (n = 0; n < gl_in.length(); ++n) { - gl_Position = gl_in[n].gl_Position; - gl_Layer = layer; - EmitVertex(); - } - EndPrimitive(); -} \ No newline at end of file +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(Vec2Property, glm::vec2); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___VEC2PROPERTY___H__ diff --git a/modules/base/shaders/deltaJ_calc_gs.glsl b/include/openspace/properties/vector/vec3property.h similarity index 84% rename from modules/base/shaders/deltaJ_calc_gs.glsl rename to include/openspace/properties/vector/vec3property.h index a4dd2d50b5..0daceaad4a 100644 --- a/modules/base/shaders/deltaJ_calc_gs.glsl +++ b/include/openspace/properties/vector/vec3property.h @@ -22,20 +22,19 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#version __CONTEXT__ +#ifndef __OPENSPACE_CORE___VEC3PROPERTY___H__ +#define __OPENSPACE_CORE___VEC3PROPERTY___H__ -uniform int layer; +#include -layout (triangles) in; -layout (triangle_strip, max_vertices = 3) out; +#include -void main() -{ - int n; - for (n = 0; n < gl_in.length(); ++n) { - gl_Position = gl_in[n].gl_Position; - gl_Layer = layer; - EmitVertex(); - } - EndPrimitive(); -} \ No newline at end of file +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(Vec3Property, glm::vec3); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___VEC3PROPERTY___H__ diff --git a/modules/base/shaders/deltaS_calc_gs.glsl b/include/openspace/properties/vector/vec4property.h similarity index 84% rename from modules/base/shaders/deltaS_calc_gs.glsl rename to include/openspace/properties/vector/vec4property.h index a4dd2d50b5..ae019c0e22 100644 --- a/modules/base/shaders/deltaS_calc_gs.glsl +++ b/include/openspace/properties/vector/vec4property.h @@ -22,20 +22,19 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#version __CONTEXT__ +#ifndef __OPENSPACE_CORE___VEC4PROPERTY___H__ +#define __OPENSPACE_CORE___VEC4PROPERTY___H__ -uniform int layer; +#include -layout (triangles) in; -layout (triangle_strip, max_vertices = 3) out; +#include -void main() -{ - int n; - for (n = 0; n < gl_in.length(); ++n) { - gl_Position = gl_in[n].gl_Position; - gl_Layer = layer; - EmitVertex(); - } - EndPrimitive(); -} \ No newline at end of file +namespace openspace { +namespace properties { + +REGISTER_NUMERICALPROPERTY_HEADER(Vec4Property, glm::vec4); + +} // namespace properties +} // namespace openspace + +#endif // __OPENSPACE_CORE___VEC4PROPERTY___H__ diff --git a/include/openspace/properties/vectorproperty.h b/include/openspace/properties/vectorproperty.h index a1307037ba..d7792f1915 100644 --- a/include/openspace/properties/vectorproperty.h +++ b/include/openspace/properties/vectorproperty.h @@ -22,34 +22,29 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __VECTORPROPERTY_H__ -#define __VECTORPROPERTY_H__ +#ifndef __OPENSPACE_CORE___VECTORPROPERTY___H__ +#define __OPENSPACE_CORE___VECTORPROPERTY___H__ -#include "openspace/properties/numericalproperty.h" +#include -#include +#include +#include +#include -namespace openspace { -namespace properties { +#include +#include +#include -REGISTER_TEMPLATEPROPERTY_HEADER(BVec2Property, glm::bvec2); -REGISTER_TEMPLATEPROPERTY_HEADER(BVec3Property, glm::bvec3); -REGISTER_TEMPLATEPROPERTY_HEADER(BVec4Property, glm::bvec4); +#include +#include +#include -REGISTER_NUMERICALPROPERTY_HEADER(Vec2Property, glm::vec2); -REGISTER_NUMERICALPROPERTY_HEADER(Vec3Property, glm::vec3); -REGISTER_NUMERICALPROPERTY_HEADER(Vec4Property, glm::vec4); -REGISTER_NUMERICALPROPERTY_HEADER(DVec2Property, glm::dvec2); -REGISTER_NUMERICALPROPERTY_HEADER(DVec3Property, glm::dvec3); -REGISTER_NUMERICALPROPERTY_HEADER(DVec4Property, glm::dvec4); -REGISTER_NUMERICALPROPERTY_HEADER(IVec2Property, glm::ivec2); -REGISTER_NUMERICALPROPERTY_HEADER(IVec3Property, glm::ivec3); -REGISTER_NUMERICALPROPERTY_HEADER(IVec4Property, glm::ivec4); -REGISTER_NUMERICALPROPERTY_HEADER(UVec2Property, glm::uvec2); -REGISTER_NUMERICALPROPERTY_HEADER(UVec3Property, glm::uvec3); -REGISTER_NUMERICALPROPERTY_HEADER(UVec4Property, glm::uvec4); +#include +#include +#include -} // namespace properties -} // namespace openspace +#include +#include +#include -#endif // __INTPROPERTY_H__ +#endif // __OPENSPACE_CORE___VECTORPROPERTY___H__ diff --git a/modules/base/shaders/deltaS_sup_calc_gs.glsl b/include/openspace/properties/wcharproperty.h similarity index 78% rename from modules/base/shaders/deltaS_sup_calc_gs.glsl rename to include/openspace/properties/wcharproperty.h index 8ca6044fd1..38d12030ce 100644 --- a/modules/base/shaders/deltaS_sup_calc_gs.glsl +++ b/include/openspace/properties/wcharproperty.h @@ -21,21 +21,33 @@ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ + +#ifndef __WCHARPROPERTY_H__ +#define __WCHARPROPERTY_H__ + + /** + * \file wcharproperty.h + * + * \addtogroup openspace + * @{ + * \addtogroup properties + * @{ -#version __CONTEXT__ + * \class WCharProperty + * This class is a concrete implementation of openspace::properties::TemplateProperty with + * the type wchar_t. -uniform int layer; + * @} @} + */ -layout (triangles) in; -layout (triangle_strip, max_vertices = 3) out; +#include "openspace/properties/numericalproperty.h" -void main() -{ - int n; - for (n = 0; n < gl_in.length(); ++n) { - gl_Position = gl_in[n].gl_Position; - gl_Layer = layer; - EmitVertex(); - } - EndPrimitive(); -} \ No newline at end of file +namespace openspace { +namespace properties { + +//REGISTER_NUMERICALPROPERTY_HEADER(WCharProperty, wchar_t); + +} // namespace properties +} // namespace openspace + +#endif // __WCHARPROPERTY_H__ diff --git a/include/openspace/query/query.h b/include/openspace/query/query.h index 98d2844f68..8941b8823e 100644 --- a/include/openspace/query/query.h +++ b/include/openspace/query/query.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __QUERY_H__ -#define __QUERY_H__ +#ifndef __OPENSPACE_CORE___QUERY___H__ +#define __OPENSPACE_CORE___QUERY___H__ #include #include @@ -46,6 +46,6 @@ Renderable* renderable(const std::string& name); properties::Property* property(const std::string& uri); std::vector allProperties(); -} // namespace +} // namespace openspace -#endif // __QUERY_H__ +#endif // __OPENSPACE_CORE___QUERY___H__ diff --git a/include/openspace/rendering/abufferrenderer.h b/include/openspace/rendering/abufferrenderer.h index 8a8dd5dba6..4d3972d38e 100644 --- a/include/openspace/rendering/abufferrenderer.h +++ b/include/openspace/rendering/abufferrenderer.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __ABUFFERRENDERER_H__ -#define __ABUFFERRENDERER_H__ +#ifndef __OPENSPACE_CORE___ABUFFERRENDERER___H__ +#define __OPENSPACE_CORE___ABUFFERRENDERER___H__ #include #include @@ -136,7 +136,8 @@ private: float _blackoutFactor; ghoul::Dictionary _rendererData; -}; // ABufferRenderer -} // openspace +}; -#endif // __RENDERER_H__ +} // namespace openspace + +#endif // __OPENSPACE_CORE___ABUFFERRENDERER___H__ diff --git a/include/openspace/rendering/framebufferrenderer.h b/include/openspace/rendering/framebufferrenderer.h index df996e695f..9ec20629d2 100644 --- a/include/openspace/rendering/framebufferrenderer.h +++ b/include/openspace/rendering/framebufferrenderer.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __FRAMEBUFFERRENDERER_H__ -#define __FRAMEBUFFERRENDERER_H__ +#ifndef __OPENSPACE_CORE___FRAMEBUFFERRENDERER___H__ +#define __OPENSPACE_CORE___FRAMEBUFFERRENDERER___H__ #include #include @@ -107,7 +107,8 @@ private: int _nAaSamples; ghoul::Dictionary _rendererData; -}; // FramebufferRenderer -} // openspace +}; -#endif // __FRAMEBUFFERRENDERER_H__ +} // namespace openspace + +#endif // __OPENSPACE_CORE___FRAMEBUFFERRENDERER___H__ diff --git a/include/openspace/rendering/raycasterlistener.h b/include/openspace/rendering/raycasterlistener.h index 97a88b2d33..9c5b2df027 100644 --- a/include/openspace/rendering/raycasterlistener.h +++ b/include/openspace/rendering/raycasterlistener.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RAYCASTERLISTENER_H__ -#define __RAYCASTERLISTENER_H__ +#ifndef __OPENSPACE_CORE___RAYCASTERLISTENER___H__ +#define __OPENSPACE_CORE___RAYCASTERLISTENER___H__ namespace openspace { @@ -36,4 +36,4 @@ public: } // openspace -#endif // __RAYCASTERLISTENER_H__ +#endif // __OPENSPACE_CORE___RAYCASTERLISTENER___H__ diff --git a/include/openspace/rendering/raycastermanager.h b/include/openspace/rendering/raycastermanager.h index 18e2e7f35f..8108ab756a 100644 --- a/include/openspace/rendering/raycastermanager.h +++ b/include/openspace/rendering/raycastermanager.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RAYCASTERMANAGER_H__ -#define __RAYCASTERMANAGER_H__ +#ifndef __OPENSPACE_CORE___RAYCASTERMANAGER___H__ +#define __OPENSPACE_CORE___RAYCASTERMANAGER___H__ #include @@ -46,8 +46,8 @@ public: private: std::vector _raycasters; std::vector _listeners; -}; // Volume +}; -} // openspace +} // namespace openspace -#endif // __RAYCASTERMANAGER_H__ +#endif // __OPENSPACE_CORE___RAYCASTERMANAGER___H__ diff --git a/include/openspace/rendering/renderable.h b/include/openspace/rendering/renderable.h index de1934821d..fc3b9c61d9 100644 --- a/include/openspace/rendering/renderable.h +++ b/include/openspace/rendering/renderable.h @@ -22,11 +22,12 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERABLE_H__ -#define __RENDERABLE_H__ +#ifndef __OPENSPACE_CORE___RENDERABLE___H__ +#define __OPENSPACE_CORE___RENDERABLE___H__ #include -#include + +#include #include #include @@ -77,7 +78,6 @@ public: virtual void render(const RenderData& data); virtual void render(const RenderData& data, RendererTasks& rendererTask); - virtual void postRender(const RenderData& data); virtual void update(const UpdateData& data); RenderBin renderBin() const; @@ -106,6 +106,6 @@ private: bool _hasTimeInterval; }; -} // namespace openspace +} // namespace openspace -#endif // __RENDERABLE_H__ +#endif // __OPENSPACE_CORE___RENDERABLE___H__ diff --git a/include/openspace/rendering/renderengine.h b/include/openspace/rendering/renderengine.h index 26fa01089c..725bfcbfa7 100644 --- a/include/openspace/rendering/renderengine.h +++ b/include/openspace/rendering/renderengine.h @@ -22,20 +22,17 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERENGINE_H__ -#define __RENDERENGINE_H__ +#ifndef __OPENSPACE_CORE___RENDERENGINE___H__ +#define __OPENSPACE_CORE___RENDERENGINE___H__ #include -#include -#include -#include +#include +#include +#include #include - -#include - namespace ghoul { namespace fontrendering { class Font; @@ -49,6 +46,10 @@ class SharedMemory; namespace openspace { +namespace performance { +class PerformanceManager; +} + // Forward declare to minimize dependencies class Camera; class SyncBuffer; @@ -59,7 +60,7 @@ class RaycasterManager; class ScreenLog; class ScreenSpaceRenderable; -class RenderEngine { +class RenderEngine : public properties::PropertyOwner { public: enum class RendererImplementation { Framebuffer = 0, @@ -67,11 +68,6 @@ public: Invalid }; - enum class RenderProgramType { - Default = 0, - Post - }; - enum class FrametimeType { DtTimeAvg = 0, FPS, @@ -112,10 +108,8 @@ public: void takeScreenshot(bool applyWarping = false); void toggleInfoText(bool b); - void toggleFrametimeType(int t); // Performance measurements - void setPerformanceMeasurements(bool performanceMeasurements); bool doesPerformanceMeasurements() const; performance::PerformanceManager* performanceManager(); @@ -136,16 +130,14 @@ public: std::string name, std::string vsPath, std::string fsPath, - const ghoul::Dictionary& dictionary = ghoul::Dictionary(), - RenderEngine::RenderProgramType type = RenderEngine::RenderProgramType::Default); + const ghoul::Dictionary& dictionary = ghoul::Dictionary()); std::unique_ptr buildRenderProgram( std::string name, std::string vsPath, std::string fsPath, std::string csPath, - const ghoul::Dictionary& dictionary = ghoul::Dictionary(), - RenderEngine::RenderProgramType type = RenderEngine::RenderProgramType::Default); + const ghoul::Dictionary& dictionary = ghoul::Dictionary()); std::string progressToStr(int size, double t); @@ -190,14 +182,8 @@ public: void sortScreenspaceRenderables(); - // This is temporary until a proper screenspace solution is found ---abock - struct OnScreenInformation{ - glm::vec2 _position; - unsigned int _size; - int _node; - }; - - SyncData _onScreenInformation; + glm::ivec2 renderingResolution() const; + glm::ivec2 fontResolution() const; std::vector getSyncables(); @@ -211,6 +197,7 @@ private: Scene* _sceneGraph; RaycasterManager* _raycasterManager; + properties::BoolProperty _performanceMeasurements; std::unique_ptr _performanceManager; std::unique_ptr _renderer; @@ -219,7 +206,9 @@ private: ghoul::Dictionary _resolveData; ScreenLog* _log; - FrametimeType _frametimeType; + properties::OptionProperty _frametimeType; + + //FrametimeType _frametimeType; bool _showInfo; bool _showLog; @@ -247,4 +236,4 @@ private: } // namespace openspace -#endif // __RENDERENGINE_H__ +#endif // __OPENSPACE_CORE___RENDERENGINE___H__ diff --git a/include/openspace/rendering/renderer.h b/include/openspace/rendering/renderer.h index 3258be73c0..a09a433497 100644 --- a/include/openspace/rendering/renderer.h +++ b/include/openspace/rendering/renderer.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERER_H__ -#define __RENDERER_H__ +#ifndef __OPENSPACE_CORE___RENDERER___H__ +#define __OPENSPACE_CORE___RENDERER___H__ #include #include @@ -79,7 +79,8 @@ public: */ virtual void updateRendererData() = 0; -}; // Renderer -} // openspace +}; -#endif // __RENDERER_H__ +} // openspace + +#endif // __OPENSPACE_CORE___RENDERER___H__ diff --git a/include/openspace/rendering/screenspacerenderable.h b/include/openspace/rendering/screenspacerenderable.h index 46cea14e32..aaebcb64b3 100644 --- a/include/openspace/rendering/screenspacerenderable.h +++ b/include/openspace/rendering/screenspacerenderable.h @@ -22,14 +22,15 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SCREENSPACERENDERABLE_H__ -#define __SCREENSPACERENDERABLE_H__ +#ifndef __OPENSPACE_CORE___SCREENSPACERENDERABLE___H__ +#define __OPENSPACE_CORE___SCREENSPACERENDERABLE___H__ #include -#include #include -#include +#include +#include +#include #include #include @@ -113,6 +114,6 @@ protected: float _radius; }; -} // namespace openspace +} // namespace openspace -#endif // __SCREENSPACERENDERABLE_H__ +#endif // __OPENSPACE_CORE___SCREENSPACERENDERABLE___H__ diff --git a/include/openspace/rendering/transferfunction.h b/include/openspace/rendering/transferfunction.h index 71023b00d5..1bccef366e 100644 --- a/include/openspace/rendering/transferfunction.h +++ b/include/openspace/rendering/transferfunction.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __TRANSFERFUNCTION_H__ -#define __TRANSFERFUNCTION_H__ +#ifndef __OPENSPACE_CORE___TRANSFERFUNCTION___H__ +#define __OPENSPACE_CORE___TRANSFERFUNCTION___H__ #include #include @@ -34,38 +34,38 @@ namespace openspace { - class TransferFunction { - public: - typedef std::function TfChangedCallback; +class TransferFunction { +public: + typedef std::function TfChangedCallback; - TransferFunction(const std::string& filepath, TfChangedCallback tfChangedCallback = TfChangedCallback()); - void setPath(const std::string& filepath); - ghoul::opengl::Texture& getTexture(); - void bind(); - void update(); - glm::vec4 sample(size_t t); - size_t width(); - void setCallback(TfChangedCallback callback); - private: - void setTextureFromTxt(); - void setTextureFromImage(); - void uploadTexture(); + TransferFunction(const std::string& filepath, TfChangedCallback tfChangedCallback = TfChangedCallback()); + void setPath(const std::string& filepath); + ghoul::opengl::Texture& getTexture(); + void bind(); + void update(); + glm::vec4 sample(size_t t); + size_t width(); + void setCallback(TfChangedCallback callback); +private: + void setTextureFromTxt(); + void setTextureFromImage(); + void uploadTexture(); - std::string _filepath; - std::unique_ptr _file = nullptr; - std::unique_ptr _texture = nullptr; - bool _needsUpdate = false; - TfChangedCallback _tfChangedCallback; - }; + std::string _filepath; + std::unique_ptr _file = nullptr; + std::unique_ptr _texture = nullptr; + bool _needsUpdate = false; + TfChangedCallback _tfChangedCallback; +}; + +struct MappingKey { + float position{0.0f}; + glm::vec4 color{0.0f,0.0f,0.0f,0.0f}; + MappingKey(float p, const glm::vec4& c): position(p), color(c) {}; + MappingKey(float p): position(p), color(glm::vec4(0.0f)) {}; + bool operator<(const MappingKey& rhs) {return position < rhs.position;}; +}; - struct MappingKey { - float position{0.0f}; - glm::vec4 color{0.0f,0.0f,0.0f,0.0f}; - MappingKey(float p, const glm::vec4& c): position(p), color(c) {}; - MappingKey(float p): position(p), color(glm::vec4(0.0f)) {}; - bool operator<(const MappingKey& rhs) {return position < rhs.position;}; - }; } // namespace openspace -#endif - +#endif // __OPENSPACE_CORE___TRANSFERFUNCTION___H__ diff --git a/include/openspace/rendering/volume.h b/include/openspace/rendering/volume.h index 4111705bea..0a01f23c34 100644 --- a/include/openspace/rendering/volume.h +++ b/include/openspace/rendering/volume.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __VOLUME_H__ -#define __VOLUME_H__ +#ifndef __OPENSPACE_CORE___VOLUME___H__ +#define __OPENSPACE_CORE___VOLUME___H__ #include #include @@ -125,8 +125,8 @@ public: */ //virtual std::string getHelperPath() = 0; -}; // Volume +}; -} // openspace +} // namespace openspace -#endif // __VOLUME_H__ +#endif // __OPENSPACE_CORE___VOLUME___H__ diff --git a/include/openspace/rendering/volumeraycaster.h b/include/openspace/rendering/volumeraycaster.h index dc4bbcee57..652d906e6e 100644 --- a/include/openspace/rendering/volumeraycaster.h +++ b/include/openspace/rendering/volumeraycaster.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __VOLUMERAYCASTER_H__ -#define __VOLUMERAYCASTER_H__ +#ifndef __OPENSPACE_CORE___VOLUMERAYCASTER___H__ +#define __OPENSPACE_CORE___VOLUMERAYCASTER___H__ #include #include @@ -122,9 +122,8 @@ public: * which should be a prefix to all symbols defined by the helper */ virtual std::string getHelperPath() const = 0; +}; -}; // Raycaster +} // namespace openspace -} // openspace - -#endif // __VOLUMERAYCASTER_H__ +#endif // __OPENSPACE_CORE___VOLUMERAYCASTER___H__ diff --git a/include/openspace/scene/rotation.h b/include/openspace/scene/rotation.h index 42e35bd3bd..d831046280 100644 --- a/include/openspace/scene/rotation.h +++ b/include/openspace/scene/rotation.h @@ -22,32 +22,36 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __ROTATION_H__ -#define __ROTATION_H__ +#ifndef __OPENSPACE_CORE___ROTATION___H__ +#define __OPENSPACE_CORE___ROTATION___H__ -#include -#include +#include #include +#include + +#include namespace openspace { -class Rotation { +class Rotation : public properties::PropertyOwner { public: static Rotation* createFromDictionary(const ghoul::Dictionary& dictionary); Rotation(const ghoul::Dictionary& dictionary); virtual ~Rotation(); virtual bool initialize(); - virtual const glm::dmat3& matrix() const = 0; + const glm::dmat3& matrix() const; virtual void update(const UpdateData& data); static openspace::Documentation Documentation(); protected: Rotation(); + + glm::dmat3 _matrix; }; } // namespace openspace -#endif // __ROTATION_H__ +#endif // __OPENSPACE_CORE___ROTATION___H__ diff --git a/include/openspace/scene/scale.h b/include/openspace/scene/scale.h index 40a694af4a..f3af6473fd 100644 --- a/include/openspace/scene/scale.h +++ b/include/openspace/scene/scale.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SCALE_H__ -#define __SCALE_H__ +#ifndef __OPENSPACE_CORE___SCALE___H__ +#define __OPENSPACE_CORE___SCALE___H__ #include @@ -48,4 +48,4 @@ public: } // namespace openspace -#endif // __SCALE_H__ +#endif // __OPENSPACE_CORE___SCALE___H__ diff --git a/include/openspace/scene/scene.h b/include/openspace/scene/scene.h index 0e748a2f65..31dec8b3dd 100644 --- a/include/openspace/scene/scene.h +++ b/include/openspace/scene/scene.h @@ -22,10 +22,9 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SCENE_H__ -#define __SCENE_H__ +#ifndef __OPENSPACE_CORE___SCENE___H__ +#define __OPENSPACE_CORE___SCENE___H__ -// std includes #include #include #include @@ -86,11 +85,6 @@ public: */ void render(const RenderData& data, RendererTasks& tasks); - /* - * Post-Render visible SceneGraphNodes using the provided camera - */ - void postRender(const RenderData& data); - /* * Returns the root SceneGraphNode */ @@ -124,7 +118,7 @@ public: private: bool loadSceneInternal(const std::string& sceneDescriptionFilePath); - void writePropertyDocumentation(const std::string& filename, const std::string& type); + void writePropertyDocumentation(const std::string& filename, const std::string& type, const std::string& sceneFilename); std::string _focus; @@ -158,4 +152,4 @@ private: } // namespace openspace -#endif // __SCENE_H__ +#endif // __OPENSPACE_CORE___SCENE___H__ diff --git a/include/openspace/scene/scenegraph.h b/include/openspace/scene/scenegraph.h index 125f1c58d4..effc22a3cc 100644 --- a/include/openspace/scene/scenegraph.h +++ b/include/openspace/scene/scenegraph.h @@ -22,11 +22,12 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SCENEGRAPH_H__ -#define __SCENEGRAPH_H__ +#ifndef __OPENSPACE_CORE___SCENEGRAPH___H__ +#define __OPENSPACE_CORE___SCENEGRAPH___H__ #include #include + namespace openspace { class SceneGraphNode; @@ -71,4 +72,4 @@ private: } // namespace openspace -#endif // __SCENEGRAPH_H__ +#endif // __OPENSPACE_CORE___SCENEGRAPH___H__ diff --git a/include/openspace/scene/scenegraphnode.h b/include/openspace/scene/scenegraphnode.h index a7a3c4cac7..b028462909 100644 --- a/include/openspace/scene/scenegraphnode.h +++ b/include/openspace/scene/scenegraphnode.h @@ -22,14 +22,14 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SCENEGRAPHNODE_H__ -#define __SCENEGRAPHNODE_H__ +#ifndef __OPENSPACE_CORE___SCENEGRAPHNODE___H__ +#define __OPENSPACE_CORE___SCENEGRAPHNODE___H__ // open space includes #include #include -#include +#include #include #include #include @@ -51,7 +51,9 @@ public: struct PerformanceRecord { long long renderTime; // time in ns long long updateTimeRenderable; // time in ns - long long updateTimeEphemeris; // time in ns + long long updateTimeTranslation; // time in ns + long long updateTimeRotation; // time in ns + long long updateTimeScaling; // time in ns }; static const std::string RootNodeName; @@ -70,7 +72,6 @@ public: void update(const UpdateData& data); void evaluate(const Camera* camera, const psc& parentPosition = psc()); void render(const RenderData& data, RendererTasks& tasks); - void postRender(const RenderData& data); void updateCamera(Camera* camera) const; //void addNode(SceneGraphNode* child); @@ -101,13 +102,6 @@ public: const Renderable* renderable() const; Renderable* renderable(); - // @TODO Remove once the scalegraph is in effect ---abock - - void setEphemeris(Ephemeris* eph) { - delete _ephemeris; - _ephemeris = eph; - } - static documentation::Documentation Documentation(); private: @@ -129,9 +123,11 @@ private: PowerScaledScalar _boundingSphere; // Transformation defined by ephemeris, rotation and scale - Ephemeris* _ephemeris; - Rotation* _rotation; - Scale* _scale; + struct { + std::unique_ptr translation; + std::unique_ptr rotation; + std::unique_ptr scale; + } _transform; // Cached transform data glm::dvec3 _worldPositionCached; @@ -141,4 +137,4 @@ private: } // namespace openspace -#endif // __SCENEGRAPHNODE_H__ +#endif // __OPENSPACE_CORE___SCENEGRAPHNODE___H__ diff --git a/include/openspace/scene/ephemeris.h b/include/openspace/scene/translation.h similarity index 78% rename from include/openspace/scene/ephemeris.h rename to include/openspace/scene/translation.h index ae56fe8569..b8b2e211bf 100644 --- a/include/openspace/scene/ephemeris.h +++ b/include/openspace/scene/translation.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __EPHEMERIS_H__ -#define __EPHEMERIS_H__ +#ifndef __OPENSPACE_CORE___TRANSLATION___H__ +#define __OPENSPACE_CORE___TRANSLATION___H__ #include @@ -34,18 +34,30 @@ namespace openspace { -class Ephemeris : public properties::PropertyOwner { +class Translation : public properties::PropertyOwner { public: - static Ephemeris* createFromDictionary(const ghoul::Dictionary& dictionary); + static Translation* createFromDictionary(const ghoul::Dictionary& dictionary); - virtual ~Ephemeris(); + virtual ~Translation(); virtual bool initialize(); + virtual glm::dvec3 position() const = 0; virtual void update(const UpdateData& data); + glm::dvec3 position(double time); + + // Registers a callback that gets called when a significant change has been made that + // invalidates potentially stored points, for example in trails + void onParameterChange(std::function callback); + static openspace::Documentation Documentation(); + +protected: + void notifyObservers(); + + std::function _onParameterChangeCallback; }; -} // namespace openspace +} // namespace openspace -#endif // __EPHEMERIS_H__ +#endif // __OPENSPACE_CORE___TRANSLATION___H__ diff --git a/include/openspace/scripting/lualibrary.h b/include/openspace/scripting/lualibrary.h index 6787575a84..7c9f25c3a9 100644 --- a/include/openspace/scripting/lualibrary.h +++ b/include/openspace/scripting/lualibrary.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __LUALIBRARY_H__ -#define __LUALIBRARY_H__ +#ifndef __OPENSPACE_CORE___LUALIBRARY___H__ +#define __OPENSPACE_CORE___LUALIBRARY___H__ #include @@ -37,9 +37,8 @@ namespace scripting { struct LuaLibrary { /** * This structure represents a Lua function with its #name, #function pointer - * #argumentText describing the arguments this function takes, the #helpText - * describing the function, and whether it should be shared in a parallel - * connection (#parallelShared) + * #argumentText describing the arguments this function takes, and the the #helpText + * describing the function. */ struct Function { /// The name of the function @@ -50,9 +49,6 @@ struct LuaLibrary { std::string argumentText; /// A help text describing what the function does/ std::string helpText; - /// If true, this function will be shared with other parallel - /// connections - bool parallelShared; }; /// The name of the library std::string name; @@ -66,4 +62,4 @@ struct LuaLibrary { } // namespace scripting } // namespace openspace -#endif // __LUALIBRARY_H__ +#endif // __OPENSPACE_CORE___LUALIBRARY___H__ diff --git a/include/openspace/scripting/scriptengine.h b/include/openspace/scripting/scriptengine.h index 89edffff5d..c87beddaa8 100644 --- a/include/openspace/scripting/scriptengine.h +++ b/include/openspace/scripting/scriptengine.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SCRIPTENGINE_H__ -#define __SCRIPTENGINE_H__ +#ifndef __OPENSPACE_CORE___SCRIPTENGINE___H__ +#define __OPENSPACE_CORE___SCRIPTENGINE___H__ #include #include @@ -50,6 +50,7 @@ namespace scripting { */ class ScriptEngine : public Syncable { public: + using RemoteScripting = ghoul::Boolean; /** * Initializes the internal Lua state and registers a common set of library functions * \throw LuaRuntimeException If the creation of the new Lua state fails @@ -79,7 +80,7 @@ public: virtual void decode(SyncBuffer* syncBuffer); virtual void postsync(bool isMaster); - void queueScript(const std::string &script); + void queueScript(const std::string &script, RemoteScripting remoteScripting); void setLogFile(const std::string& filename, const std::string& type); @@ -88,9 +89,9 @@ public: std::vector allLuaFunctions() const; //parallel functions - bool parseLibraryAndFunctionNames(std::string &library, std::string &function, const std::string &script); - bool shouldScriptBeSent(const std::string &library, const std::string &function); - void cacheScript(const std::string &library, const std::string &function, const std::string &script); + //bool parseLibraryAndFunctionNames(std::string &library, std::string &function, const std::string &script); + //bool shouldScriptBeSent(const std::string &library, const std::string &function); + //void cacheScript(const std::string &library, const std::string &function, const std::string &script); private: @@ -107,24 +108,22 @@ private: //sync variables std::mutex _mutex; - std::vector _queuedScripts; + std::vector> _queuedScripts; std::vector _receivedScripts; std::string _currentSyncedScript; //parallel variables - std::map> _cachedScripts; - std::mutex _cachedScriptsMutex; + //std::map> _cachedScripts; + //std::mutex _cachedScriptsMutex; //logging variables bool _logFileExists = false; bool _logScripts = true; std::string _logType; std::string _logFilename; - - }; } // namespace scripting } // namespace openspace -#endif // __SCRIPTENGINE_H__ +#endif // __OPENSPACE_CORE___SCRIPTENGINE___H__ diff --git a/include/openspace/scripting/scriptscheduler.h b/include/openspace/scripting/scriptscheduler.h index b8b5630c07..3f9f44916d 100644 --- a/include/openspace/scripting/scriptscheduler.h +++ b/include/openspace/scripting/scriptscheduler.h @@ -22,58 +22,46 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SCRIPTSCHEDULER_H__ -#define __SCRIPTSCHEDULER_H__ - -#include +#ifndef __OPENSPACE_CORE___SCRIPTSCHEDULER___H__ +#define __OPENSPACE_CORE___SCRIPTSCHEDULER___H__ +#include #include #include #include +namespace ghoul { +class Dictionary; +} // namespace ghoul + namespace openspace { - namespace scripting { - - -struct ReversibleLuaScript { - std::string forwardScript; - std::string backwardScript; -}; - -struct ScheduledScript { - ScheduledScript() : time(-DBL_MAX) { } - ScheduledScript(const ghoul::Dictionary& dict); - - double time; - ReversibleLuaScript script; - - static bool CompareByTime(const ScheduledScript& s1, const ScheduledScript& s2); -}; - - /** * Maintains an ordered list of ScheduledScripts and provides a simple * interface for retrieveing scheduled scripts */ class ScriptScheduler { public: + struct ScheduledScript { + ScheduledScript() = default; + ScheduledScript(const ghoul::Dictionary& dict); + + double time; + std::string forwardScript; + std::string backwardScript; + }; + /** - * Load a schedule from a Lua-file - * \param filename Lua file to load - * \param L an optional lua_State defining variables that may be used - * in the Lua-file. + * Load a schedule from a ghoul::Dictionary \p dictionary and adds the + * ScheduledScript%s to the list of stored scripts. + * \param dictionary Dictionary to read + * \throw SpecificationError If the dictionary does not adhere to the Documentation as + * specified in the openspace::Documentation function */ - void loadScripts(const std::string& filename, lua_State* L = nullptr); - - /** - * Load a schedule from a ghoul::Dictionary - * \param dict Dictionary to read - */ - void loadScripts(const ghoul::Dictionary& dict); + void loadScripts(const ghoul::Dictionary& dictionary); /** @@ -96,7 +84,7 @@ public: * * \returns the ordered queue of scripts . */ - std::queue progressTo(double newTime); +// std::queue progressTo(double newTime); /** * See progressTo(double newTime). @@ -104,10 +92,12 @@ public: * \param timeStr A string specifying the a new time stamp that the * scripts scheduler should progress to. */ - std::queue progressTo(const std::string& timeStr); - - +// std::queue progressTo(const std::string& timeStr); + std::pair< + std::vector::const_iterator, std::vector::const_iterator + > progressTo(double newTime); + /** * Returns the the j2000 time value that the script scheduler is currently at */ @@ -116,16 +106,19 @@ public: /** * \returns a vector of all scripts that has been loaded */ - const std::vector& allScripts() const; + std::vector allScripts() const; static LuaLibrary luaLibrary(); + + static openspace::Documentation Documentation(); private: - - std::vector _scheduledScripts; - - size_t _currentIndex = 0; + std::vector _timings; + std::vector _forwardScripts; + std::vector _backwardScripts; + + int _currentIndex = 0; double _currentTime; }; @@ -133,4 +126,4 @@ private: } // namespace scripting } // namespace openspace -#endif // __SCRIPTSCHEDULER_H__ +#endif // __OPENSPACE_CORE___SCRIPTSCHEDULER___H__ diff --git a/include/openspace/util/blockplaneintersectiongeometry.h b/include/openspace/util/blockplaneintersectiongeometry.h index 58292c967f..70117c36cd 100644 --- a/include/openspace/util/blockplaneintersectiongeometry.h +++ b/include/openspace/util/blockplaneintersectiongeometry.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __BLOCKPLANEINTERSECTIONGEOMETRY_H__ -#define __BLOCKPLANEINTERSECTIONGEOMETRY_H__ +#ifndef __OPENSPACE_CORE___BLOCKPLANEINTERSECTIONGEOMETRY___H__ +#define __OPENSPACE_CORE___BLOCKPLANEINTERSECTIONGEOMETRY___H__ #include #include @@ -55,6 +55,6 @@ private: float _planeDistance; }; -} +} // namespace openspace -#endif // __BLOCKPLANEINTERSECTIONGEOMETRY_H__ +#endif // __OPENSPACE_CORE___BLOCKPLANEINTERSECTIONGEOMETRY___H__ diff --git a/include/openspace/util/boxgeometry.h b/include/openspace/util/boxgeometry.h index ea16642a5a..8b87f29397 100644 --- a/include/openspace/util/boxgeometry.h +++ b/include/openspace/util/boxgeometry.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __BOXGEOMETRY_H__ -#define __BOXGEOMETRY_H__ +#ifndef __OPENSPACE_CORE___BOXGEOMETRY___H__ +#define __OPENSPACE_CORE___BOXGEOMETRY___H__ #include #include @@ -46,4 +46,4 @@ public: } // namespace openspace -#endif // __BOXGEOMETRY_H__ +#endif // __OPENSPACE_CORE___BOXGEOMETRY___H__ diff --git a/include/openspace/util/camera.h b/include/openspace/util/camera.h index e2de5a6099..87184d080d 100644 --- a/include/openspace/util/camera.h +++ b/include/openspace/util/camera.h @@ -22,182 +22,181 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __CAMERA_H__ -#define __CAMERA_H__ +#ifndef __OPENSPACE_CORE___CAMERA___H__ +#define __OPENSPACE_CORE___CAMERA___H__ #include -// open space includes #include #include #include -// glm includes #include #include #include #include namespace openspace { - class SyncBuffer; +class SyncBuffer; - /** - This class still needs some more love. Suggested improvements: - - Remove psc from the camera class interface. - - Accessors should return constant references to double precision class members. - - Remove the scaling variable (What is it used for?) - - Remove the maxFov and sinMaxfov variables. Redundant since the fov is embedded - within the perspective projection matrix. - - Remove focusposition, part of the integration with the scale graph. The - "focus position" should not be needed since we assume the camera is always - positioned relative to its origin. When orbiting another object (not in origin), - the focus position should probably be handled outside the camera class - (interaction handler) since it does not affect the state of the camera - (only how it interacts). - - The class might need some more reasonable accessors depending on use cases. - (up vector world space?) - - Make clear which function returns a combined view matrix (things that are - dependent on the separate sgct nodes). +/** + * This class still needs some more love. Suggested improvements: + * - Remove psc from the camera class interface. + * - Accessors should return constant references to double precision class members. + * - Remove the scaling variable (What is it used for?) + * - Remove the maxFov and sinMaxfov variables. Redundant since the fov is embedded + * within the perspective projection matrix. + * - Remove focusposition, part of the integration with the scale graph. The + * "focus position" should not be needed since we assume the camera is always + * positioned relative to its origin. When orbiting another object (not in origin), + * the focus position should probably be handled outside the camera class + * (interaction handler) since it does not affect the state of the camera + * (only how it interacts). + * - The class might need some more reasonable accessors depending on use cases. + * (up vector world space?) + * - Make clear which function returns a combined view matrix (things that are + * dependent on the separate sgct nodes). */ - class Camera { - /** - Used to explicitly show which variables within the Camera class that are used - for caching. +class Camera { + /** + * Used to explicitly show which variables within the Camera class that are used + * for caching. */ - template - struct Cached - { - Cached() { isDirty = true; } - T datum; - bool isDirty; - }; - - // now working with float precision. To be changed to double later. - // The reason double does not work yet is because of the setUniform function - // in ghoul::opengl - typedef glm::dquat Quat; - typedef glm::dmat4 Mat4; - typedef glm::dvec3 Vec3; - - // Static constants - static const Vec3 _VIEW_DIRECTION_CAMERA_SPACE; - static const Vec3 _LOOKUP_VECTOR_CAMERA_SPACE; - public: - Camera(); - Camera(const Camera& o); - ~Camera(); - - // Mutators - void setPositionVec3(Vec3 pos); - void setFocusPositionVec3(Vec3 pos); - void setRotation(Quat rotation); - void setScaling(glm::vec2 scaling); - void setMaxFov(float fov); - - // Relative mutators - void rotate(Quat rotation); - - // Accessors - // Remove Vec3 from the name when psc is gone - const Vec3& positionVec3() const; - const Vec3& unsynchedPositionVec3() const; - const Vec3& focusPositionVec3() const; - const Vec3& viewDirectionWorldSpace() const; - const Vec3& lookUpVectorCameraSpace() const; - const Vec3& lookUpVectorWorldSpace() const; - const glm::vec2& scaling() const; - const Mat4& viewRotationMatrix() const; - const Quat& rotationQuaternion() const; - float maxFov() const; - float sinMaxFov() const; - - // @TODO this should simply be called viewMatrix! - // Or it needs to be changed so that it actually is combined. Right now it is - // only the view matrix that is the same for all SGCT cameras. - // Right now this function returns the actual combined matrix which makes some - // of the old calls to the function wrong.. - const Mat4& combinedViewMatrix() const; - - void invalidateCache(); - - void serialize(std::ostream& os) const; - void deserialize(std::istream& is); - - /** - Handles SGCT's internal matrices. Also caches a calculated viewProjection - matrix. This is the data that is different for different cameras within - SGCT. - */ - class SgctInternal { - friend class Camera; - public: - void setViewMatrix(glm::mat4 viewMatrix); - void setProjectionMatrix(glm::mat4 projectionMatrix); - - const glm::mat4& viewMatrix() const; - const glm::mat4& projectionMatrix() const; - const glm::mat4& viewProjectionMatrix() const; - private: - SgctInternal(); - SgctInternal(const SgctInternal& o) - : _viewMatrix(o._viewMatrix) - , _projectionMatrix(o._projectionMatrix) - , _cachedViewProjectionMatrix(o._cachedViewProjectionMatrix) - {} - - // State - glm::mat4 _viewMatrix; - glm::mat4 _projectionMatrix; - - // Cache - mutable Cached _cachedViewProjectionMatrix; - mutable std::mutex _mutex; - } sgctInternal; - - // Deprecated - [[deprecated("Replaced by Camera::setPositionVec3()")]] - void setPosition(psc pos); - [[deprecated("Replaced by Camera::setFocusPositionVec3()")]] - void setFocusPosition(psc pos); - [[deprecated("Replaced by Camera::positionVec3()")]] - psc position() const; - [[deprecated("Replaced by Camera::unsynchedPositionVec3()")]] - psc unsynchedPosition() const; - [[deprecated("Replaced by Camera::focusPositionVec3()")]] - psc focusPosition() const; - // @TODO use Camera::SgctInternal interface instead - [[deprecated("Replaced by Camera::SgctInternal::viewMatrix()")]] - const glm::mat4& viewMatrix() const; - [[deprecated("Replaced by Camera::SgctInternal::projectionMatrix()")]] - const glm::mat4& projectionMatrix() const; - [[deprecated("Replaced by Camera::SgctInternal::viewProjectionMatrix()")]] - const glm::mat4& viewProjectionMatrix() const; - - - std::vector getSyncables(); - - - private: - - SyncData _position; - SyncData _rotation; - SyncData _scaling; - - - // _focusPosition to be removed - Vec3 _focusPosition; - float _maxFov; - - // Cached data - mutable Cached _cachedViewDirection; - mutable Cached _cachedLookupVector; - mutable Cached _cachedViewRotationMatrix; - mutable Cached _cachedCombinedViewMatrix; - mutable Cached _cachedSinMaxFov; - - mutable std::mutex _mutex; + template + struct Cached + { + Cached() { isDirty = true; } + T datum; + bool isDirty; }; + + // now working with float precision. To be changed to double later. + // The reason double does not work yet is because of the setUniform function + // in ghoul::opengl + typedef glm::dquat Quat; + typedef glm::dmat4 Mat4; + typedef glm::dvec3 Vec3; + + // Static constants + static const Vec3 _VIEW_DIRECTION_CAMERA_SPACE; + static const Vec3 _LOOKUP_VECTOR_CAMERA_SPACE; +public: + Camera(); + Camera(const Camera& o); + ~Camera(); + + // Mutators + void setPositionVec3(Vec3 pos); + void setFocusPositionVec3(Vec3 pos); + void setRotation(Quat rotation); + void setScaling(glm::vec2 scaling); + void setMaxFov(float fov); + + // Relative mutators + void rotate(Quat rotation); + + // Accessors + // Remove Vec3 from the name when psc is gone + const Vec3& positionVec3() const; + const Vec3& unsynchedPositionVec3() const; + const Vec3& focusPositionVec3() const; + const Vec3& viewDirectionWorldSpace() const; + const Vec3& lookUpVectorCameraSpace() const; + const Vec3& lookUpVectorWorldSpace() const; + const glm::vec2& scaling() const; + const Mat4& viewRotationMatrix() const; + const Quat& rotationQuaternion() const; + float maxFov() const; + float sinMaxFov() const; + + // @TODO this should simply be called viewMatrix! + // Or it needs to be changed so that it actually is combined. Right now it is + // only the view matrix that is the same for all SGCT cameras. + // Right now this function returns the actual combined matrix which makes some + // of the old calls to the function wrong.. + const Mat4& combinedViewMatrix() const; + + void invalidateCache(); + + void serialize(std::ostream& os) const; + void deserialize(std::istream& is); + + /** + Handles SGCT's internal matrices. Also caches a calculated viewProjection + matrix. This is the data that is different for different cameras within + SGCT. + */ + class SgctInternal { + friend class Camera; + public: + void setViewMatrix(glm::mat4 viewMatrix); + void setProjectionMatrix(glm::mat4 projectionMatrix); + + const glm::mat4& viewMatrix() const; + const glm::mat4& projectionMatrix() const; + const glm::mat4& viewProjectionMatrix() const; + private: + SgctInternal(); + SgctInternal(const SgctInternal& o) + : _viewMatrix(o._viewMatrix) + , _projectionMatrix(o._projectionMatrix) + , _cachedViewProjectionMatrix(o._cachedViewProjectionMatrix) + {} + + // State + glm::mat4 _viewMatrix; + glm::mat4 _projectionMatrix; + + // Cache + mutable Cached _cachedViewProjectionMatrix; + mutable std::mutex _mutex; + } sgctInternal; + + // Deprecated + [[deprecated("Replaced by Camera::setPositionVec3()")]] + void setPosition(psc pos); + [[deprecated("Replaced by Camera::setFocusPositionVec3()")]] + void setFocusPosition(psc pos); + [[deprecated("Replaced by Camera::positionVec3()")]] + psc position() const; + [[deprecated("Replaced by Camera::unsynchedPositionVec3()")]] + psc unsynchedPosition() const; + [[deprecated("Replaced by Camera::focusPositionVec3()")]] + psc focusPosition() const; + // @TODO use Camera::SgctInternal interface instead + [[deprecated("Replaced by Camera::SgctInternal::viewMatrix()")]] + const glm::mat4& viewMatrix() const; + [[deprecated("Replaced by Camera::SgctInternal::projectionMatrix()")]] + const glm::mat4& projectionMatrix() const; + [[deprecated("Replaced by Camera::SgctInternal::viewProjectionMatrix()")]] + const glm::mat4& viewProjectionMatrix() const; + + + std::vector getSyncables(); + + +private: + + SyncData _position; + SyncData _rotation; + SyncData _scaling; + + + // _focusPosition to be removed + Vec3 _focusPosition; + float _maxFov; + + // Cached data + mutable Cached _cachedViewDirection; + mutable Cached _cachedLookupVector; + mutable Cached _cachedViewRotationMatrix; + mutable Cached _cachedCombinedViewMatrix; + mutable Cached _cachedSinMaxFov; + + mutable std::mutex _mutex; +}; + } // namespace openspace -#endif // __CAMERA_H__ +#endif // __OPENSPACE_CORE___CAMERA___H__ diff --git a/include/openspace/util/factorymanager.h b/include/openspace/util/factorymanager.h index acee69b919..663376d7f1 100644 --- a/include/openspace/util/factorymanager.h +++ b/include/openspace/util/factorymanager.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __FACTORYMANAGER_H__ -#define __FACTORYMANAGER_H__ +#ifndef __OPENSPACE_CORE___FACTORYMANAGER___H__ +#define __OPENSPACE_CORE___FACTORYMANAGER___H__ #include #include @@ -129,4 +129,4 @@ private: #include -#endif // __FACTORYMANAGER_H__ +#endif // __OPENSPACE_CORE___FACTORYMANAGER___H__ diff --git a/include/openspace/interaction/mousecontroller.h b/include/openspace/util/gpudata.h similarity index 54% rename from include/openspace/interaction/mousecontroller.h rename to include/openspace/util/gpudata.h index 2a47ee73a2..aac40f5ba8 100644 --- a/include/openspace/interaction/mousecontroller.h +++ b/include/openspace/util/gpudata.h @@ -22,90 +22,87 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ +#ifndef __OPENSPACE_CORE___GPUDATA___H__ +#define __OPENSPACE_CORE___GPUDATA___H__ -//#define USE_OLD_INTERACTIONHANDLER -#ifdef USE_OLD_INTERACTIONHANDLER +#include +#include +#include -#ifndef __MOUSECONTROLLER_H__ -#define __MOUSECONTROLLER_H__ - -#include - -#include - -#include +#include +#include namespace openspace { -namespace interaction { -class MouseController : public Controller { +using namespace ghoul::opengl; + + +/** + * Very simple class maintaining a uniform location. + */ +class UniformLocation { public: - MouseController(); - virtual ~MouseController() {} - - virtual void button(MouseButton button, MouseAction action) = 0; - virtual void move(float x, float y) = 0; - virtual void scrollWheel(int pos) = 0; - virtual void update(const double& dt) = 0; + /** + * Updates the uniform location of the uniform variable named + * in the provided shader program. + */ + void bind(ProgramObject* program, const std::string& name); + protected: - glm::vec3 _lastTrackballPos; - bool _isMouseBeingPressedAndHeld; - - glm::vec3 mapToTrackball(glm::vec2 mousePos); - - glm::vec3 mapToCamera(glm::vec3 trackballPos); - - void trackballRotate(int x, int y); + GLint _uniformLocation = -1; }; -class TrackballMouseController : public MouseController { + +/** + * Manages a GPU representation of the templated data type T. + * This class provides a simple interface setting the value of + * the binded GLSL variable. + */ +template +class GPUData : public UniformLocation{ public: - TrackballMouseController(); + + /** + * Sets the value of T to its corresponding GPU value. + * OBS! Users must ensure bind has been called before using this method + */ + void setValue(ProgramObject* program, T val){ + program->setUniform(_uniformLocation, val); + } - void button(MouseButton button, MouseAction action) override; - - void move(float x, float y) override; - - void scrollWheel(int pos) override; - - void update(const double& dt) override; - -protected: - bool _leftMouseButtonDown; - glm::vec3 _previousTrackballPos; }; -class OrbitalMouseController : public MouseController { +/** + * Manages a Texture on the GPU. + * This class provides a simple interface binding texture to the + * named uniform. + */ +class GPUTexture : public UniformLocation{ public: - OrbitalMouseController(); - void button(MouseButton button, MouseAction action) override; + /** + * Sets and assignes a texture unit within the provided shader + * program. + * OBS! Users must ensure bind has been called before using this method. + */ + void setValue(ProgramObject* program, std::shared_ptr texture){ + _texUnit = std::make_unique(); + _texUnit->activate(); + texture->bind(); + program->setUniform(_uniformLocation, *_texUnit); + } - void move(float x, float y) override; - - void scrollWheel(int pos) override; - - void update(const double& dt) override; - -protected: - bool _leftMouseButtonDown; - bool _rightMouseButtonDown; - bool _middleMouseButtonDown; - glm::vec2 _previousCursorPos[3]; - glm::vec2 _currentCursorPos; - glm::vec2 _currentCursorDiff[3]; - float _rotationSpeed; - float _navigationSpeed; + void deactivate(){ + _texUnit = nullptr; + } private: - enum MouseButtons{ ButtonLeft = 0, ButtonRight, ButtonMiddle }; + + std::unique_ptr _texUnit; + }; -} // namespace interaction } // namespace openspace -#endif // __MOUSECONTROLLER_H__ - - -#endif // USE_OLD_INTERACTIONHANDLER +#endif // __OPENSPACE_CORE___GPUDATA___H__ diff --git a/include/openspace/util/histogram.h b/include/openspace/util/histogram.h index bc8affbaf5..1324b08096 100644 --- a/include/openspace/util/histogram.h +++ b/include/openspace/util/histogram.h @@ -22,15 +22,15 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __HISTOGRAM_H__ -#define __HISTOGRAM_H__ +#ifndef __OPENSPACE_CORE___HISTOGRAM___H__ +#define __OPENSPACE_CORE___HISTOGRAM___H__ #include #include namespace openspace { -class Histogram { +class Histogram { public: Histogram(); Histogram(float minValue, float maxValue, int numBins); @@ -86,7 +86,8 @@ private: std::vector _equalizer; int _numValues; -}; // class Histogram +}; + } // namespace openspace -#endif //__HISTOGRAM_H__ +#endif //__OPENSPACE_CORE___HISTOGRAM___H__ diff --git a/include/openspace/util/keys.h b/include/openspace/util/keys.h index 9c41fea2df..f65c13a261 100644 --- a/include/openspace/util/keys.h +++ b/include/openspace/util/keys.h @@ -51,8 +51,8 @@ * *************************************************************************/ -#ifndef __KEYS_H__ -#define __KEYS_H__ +#ifndef __OPENSPACE_CORE___KEYS___H__ +#define __OPENSPACE_CORE___KEYS___H__ // All values that are defined here are compatible with (and are based on) the // definitions GLFW v3.1 @@ -369,4 +369,4 @@ std::string to_string(openspace::KeyWithModifier key); } // namespace std -#endif // __KEYS_H__ +#endif // __OPENSPACE_CORE___KEYS___H__ diff --git a/include/openspace/util/mouse.h b/include/openspace/util/mouse.h index 32c399bbf8..c616ec73a4 100644 --- a/include/openspace/util/mouse.h +++ b/include/openspace/util/mouse.h @@ -54,8 +54,8 @@ // All values that are defined here are compatible with (and are based on) the // definitions GLFW v3.1 -#ifndef __MOUSE_H__ -#define __MOUSE_H__ +#ifndef __OPENSPACE_CORE___MOUSE___H__ +#define __OPENSPACE_CORE___MOUSE___H__ namespace openspace { @@ -92,4 +92,4 @@ enum class MouseButton { } // namespace openspace -#endif // __MOUSE_H__ +#endif // __OPENSPACE_CORE___MOUSE___H__ diff --git a/include/openspace/util/openspacemodule.h b/include/openspace/util/openspacemodule.h index 2cda76686a..266c07a0c9 100644 --- a/include/openspace/util/openspacemodule.h +++ b/include/openspace/util/openspacemodule.h @@ -22,13 +22,15 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __OPENSPACEMODULE_H__ -#define __OPENSPACEMODULE_H__ +#ifndef __OPENSPACE_CORE___OPENSPACEMODULE___H__ +#define __OPENSPACE_CORE___OPENSPACEMODULE___H__ #include #include +#include + #include #include @@ -66,8 +68,20 @@ public: */ void deinitialize(); + /** + * Returns a list of Documentation classes that are valid for this OpenSpaceModule. + * \return A list of Documentation classes that are valid for this OpenSapceModule + */ virtual std::vector documentations() const; + /** + * Returns the minimum required OpenGL version of this OpenSpaceModule. Unless + * overwritten, it returns an OpenGL version of 3.3. + * \return The minimum required OpenGL version of this OpenSpaceModule + */ + virtual ghoul::systemcapabilities::OpenGLCapabilitiesComponent::Version + requiredOpenGLVersion() const; + protected: /** * Customization point for each derived class. The internalInitialize method is called @@ -90,4 +104,4 @@ protected: } // namespace openspace -#endif // __OPENSPACEMODULE_H__ +#endif // __OPENSPACE_CORE___OPENSPACEMODULE___H__ diff --git a/include/openspace/util/powerscaledcoordinate.h b/include/openspace/util/powerscaledcoordinate.h index ec79a38931..75cfb94e85 100644 --- a/include/openspace/util/powerscaledcoordinate.h +++ b/include/openspace/util/powerscaledcoordinate.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __POWERSCALEDCOORDINATE_H__ -#define __POWERSCALEDCOORDINATE_H__ +#ifndef __OPENSPACE_CORE___POWERSCALEDCOORDINATE___H__ +#define __OPENSPACE_CORE___POWERSCALEDCOORDINATE___H__ // open space includes // glm includes @@ -119,4 +119,4 @@ typedef PowerScaledCoordinate psc; } // namespace openspace -#endif // __POWERSCALEDCOORDINATE_H__ +#endif // __OPENSPACE_CORE___POWERSCALEDCOORDINATE___H__ diff --git a/include/openspace/util/powerscaledscalar.h b/include/openspace/util/powerscaledscalar.h index 106070a8a1..2fe2aea57d 100644 --- a/include/openspace/util/powerscaledscalar.h +++ b/include/openspace/util/powerscaledscalar.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __POWERSCALEDSCALAR_H__ -#define __POWERSCALEDSCALAR_H__ +#ifndef __OPENSPACE_CORE___POWERSCALEDSCALAR___H__ +#define __OPENSPACE_CORE___POWERSCALEDSCALAR___H__ // glm includes #include @@ -92,4 +92,4 @@ typedef PowerScaledScalar pss; } // namespace openspace -#endif // __POWERSCALEDSCALAR_H__ +#endif // __OPENSPACE_CORE___POWERSCALEDSCALAR___H__ diff --git a/include/openspace/util/powerscaledsphere.h b/include/openspace/util/powerscaledsphere.h index 26d36eb2ce..da8e80ba90 100644 --- a/include/openspace/util/powerscaledsphere.h +++ b/include/openspace/util/powerscaledsphere.h @@ -22,14 +22,14 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __POWERSCALEDSPHERE_H__ -#define __POWERSCALEDSPHERE_H__ +#ifndef __OPENSPACE_CORE___POWERSCALEDSPHERE___H__ +#define __OPENSPACE_CORE___POWERSCALEDSPHERE___H__ // open space includes #include #include #include -#include +#include namespace openspace { @@ -69,4 +69,4 @@ public: } // namespace openspace -#endif // __POWERSCALEDSPHERE_H__ +#endif // __OPENSPACE_CORE___POWERSCALEDSPHERE___H__ diff --git a/include/openspace/util/progressbar.h b/include/openspace/util/progressbar.h index ee8567efcc..92f988958f 100644 --- a/include/openspace/util/progressbar.h +++ b/include/openspace/util/progressbar.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __PROGRESSBAR_H__ -#define __PROGRESSBAR_H__ +#ifndef __OPENSPACE_CORE___PROGRESSBAR___H__ +#define __OPENSPACE_CORE___PROGRESSBAR___H__ #include @@ -43,9 +43,8 @@ private: int _previous; int _end; std::ostream& _stream; - }; } // namespace openspace -#endif // __PROGRESSBAR_H__ +#endif // __OPENSPACE_CORE___PROGRESSBAR___H__ diff --git a/include/openspace/util/screenlog.h b/include/openspace/util/screenlog.h index afeaf2ecc2..f800991555 100644 --- a/include/openspace/util/screenlog.h +++ b/include/openspace/util/screenlog.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SCREENLOG_H__ -#define __SCREENLOG_H__ +#ifndef __OPENSPACE_CORE___SCREENLOG___H__ +#define __OPENSPACE_CORE___SCREENLOG___H__ #include @@ -42,14 +42,14 @@ namespace openspace { class ScreenLog : public ghoul::logging::Log { public: /// Just a shortcut for the LogLevel access - using LogLevel = ghoul::logging::LogManager::LogLevel; + using LogLevel = ghoul::logging::LogLevel; /** * This struct stores the incoming log entries with their #level, #timeString, * #category, #message, and the generated #timeStamp used for the expiry calculation. */ struct LogEntry { - /// The ghoul::logging::LogManager::LogLevel of the log message + /// The ghoul::logging::LogLevel of the log message LogLevel level; /// The timepoint when the log message arrived at the ScreenLog @@ -68,10 +68,10 @@ public: /** * Constructor that creates a ScreenLog with the provided \p timeToLive, and the * minimum \p logLevel that is stored. Log message with a lower - * ghoul::logging::LogManager::LogLevel are automatically discarded. + * ghoul::logging::LogLevel are automatically discarded. * \param timeToLive The time-to-live for the messages in this ScreenLog. Expired * messages are removed whenever the #removeExpiredEntries method is called - * \param logLevel The minimum ghoul::logging::LogManager::LogLevel that messages must + * \param logLevel The minimum ghoul::logging::LogLevel that messages must * have in order to be stored in the ScreenLog */ ScreenLog(std::chrono::seconds timeToLive, LogLevel logLevel = LogLevel::Info); @@ -79,11 +79,11 @@ public: /** * Overwritten ghoul::loggling::Log method that is called whenever a new log message * shall be stored. - * \param level The ghoul::logging::LogManager::LogLevel of the incoming log message + * \param level The ghoul::logging::LogLevel of the incoming log message * \param category The category of the log message * \param message The actual log message that was transmitted */ - void log(ghoul::logging::LogManager::LogLevel level, const std::string& category, + void log(ghoul::logging::LogLevel level, const std::string& category, const std::string& message) override; /** @@ -115,4 +115,4 @@ private: } // namespace openspace -#endif // __SCREENLOG_H__ +#endif // __OPENSPACE_CORE___SCREENLOG___H__ diff --git a/include/openspace/util/spicemanager.h b/include/openspace/util/spicemanager.h index b5597f9149..6350a26a43 100644 --- a/include/openspace/util/spicemanager.h +++ b/include/openspace/util/spicemanager.h @@ -22,34 +22,30 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SPICEMANAGER_H__ -#define __SPICEMANAGER_H__ +#ifndef __OPENSPACE_CORE___SPICEMANAGER___H__ +#define __OPENSPACE_CORE___SPICEMANAGER___H__ + +#include #include -#include #include -#include +#include #include -#include - #include -#include #include #include #include #include -#include "SpiceUsr.h" -#include "SpiceZpr.h" - namespace openspace { class SpiceManager : public ghoul::Singleton { friend class ghoul::Singleton; public: using TransformMatrix = std::array; + using UseException = ghoul::Boolean; using KernelHandle = unsigned int; struct SpiceException : public ghoul::RuntimeError { @@ -808,6 +804,21 @@ public: * \todo I think this function should die ---abock */ std::string frameFromBody(const std::string& body) const; + + /** + * Sets the SpiceManager's exception handling. If UseException::No is passed to this + * function, all subsequent calls will not throw an error, but fail silently instead. + * If set to UseException::Yes, a SpiceException is thrown whenever an error occurs. + * \param useException The new exeception handling method that the SpiceManager should + * use + */ + void setExceptionHandling(UseException useException); + + /** + * Returns the current SpiceManager's exception strategy. See setExceptionHandling + * \return The current exception handling strategy. + */ + UseException exceptionHandling() const; static scripting::LuaLibrary luaLibrary(); @@ -910,6 +921,9 @@ private: std::map> _spkCoverageTimes; // Vector of pairs: Body, Frame std::vector> _frameByBody; + + /// Stores whether the SpiceManager throws exceptions (Yes) or fails silently (No) + UseException _useExceptions; /// The last assigned kernel-id, used to determine the next free kernel id KernelHandle _lastAssignedKernel = KernelHandle(0); @@ -917,4 +931,4 @@ private: } // namespace openspace -#endif // __SPICEMANAGER_H__ \ No newline at end of file +#endif // __OPENSPACE_CORE___SPICEMANAGER___H__ diff --git a/include/openspace/util/syncbuffer.h b/include/openspace/util/syncbuffer.h index 6a63b41a9a..2e00eba951 100644 --- a/include/openspace/util/syncbuffer.h +++ b/include/openspace/util/syncbuffer.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef SYNCBUFFER_H -#define SYNCBUFFER_H +#ifndef __OPENSPACE_CORE___SYNCBUFFER___H__ +#define __OPENSPACE_CORE___SYNCBUFFER___H__ #include #include @@ -116,4 +116,4 @@ private: } // namespace openspace -#endif // SYNCBUFFER_H +#endif // __OPENSPACE_CORE___SYNCBUFFER___H__ diff --git a/include/openspace/util/syncdata.h b/include/openspace/util/syncdata.h index 7eb638dc6c..4c491b539c 100644 --- a/include/openspace/util/syncdata.h +++ b/include/openspace/util/syncdata.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SYNC_DATA_H__ -#define __SYNC_DATA_H__ +#ifndef __OPENSPACE_CORE___SYNCDATA___H__ +#define __OPENSPACE_CORE___SYNCDATA___H__ #include #include @@ -31,15 +31,13 @@ #include #include - namespace openspace { - /** -* Interface for synchronizable data -* -* Used by SyncEngine -*/ + * Interface for synchronizable data + * + * Used by SyncEngine + */ class Syncable { public: virtual ~Syncable() {}; @@ -55,17 +53,17 @@ protected: }; /** -* A double buffered implementation of the Syncable interface. -* Users are encouraged to used this class as a default way to synchronize different -* C++ data types using the SyncEngine -* -* This class aims to handle the synchronization parts and yet act like a regular -* instance of T. Implicit casts are supported, however, when accessing member functions or -* or variables, user may have to do explicit casts. -* -* ((T&) t).method(); -* -*/ + * A double buffered implementation of the Syncable interface. + * Users are encouraged to used this class as a default way to synchronize different + * C++ data types using the SyncEngine + * + * This class aims to handle the synchronization parts and yet act like a regular + * instance of T. Implicit casts are supported, however, when accessing member functions or + * or variables, user may have to do explicit casts. + * + * ((T&) t).method(); + * + */ template class SyncData : public Syncable { public: @@ -77,29 +75,28 @@ public: }; /** - * Allowing assignment of data as if - */ + * Allowing assignment of data as if + */ SyncData& operator=(const T& rhs) { data = rhs; return *this; } /** - * Allow implicit cast to referenced T - */ + * Allow implicit cast to referenced T + */ operator T&() { return data; } /** - * Allow implicit cast to const referenced T - */ + * Allow implicit cast to const referenced T + */ operator const T&() const { return data; } protected: - virtual void encode(SyncBuffer* syncBuffer) { _mutex.lock(); syncBuffer->encode(data); @@ -121,14 +118,12 @@ protected: } }; - T data; T doubleBufferedData; std::mutex _mutex; }; - } // namespace openspace -#endif //#ifndef __SYNC_DATA_H__ +#endif // __OPENSPACE_CORE___SYNCDATA___H__ diff --git a/include/openspace/util/time.h b/include/openspace/util/time.h index 2275c95eec..e8b525539b 100644 --- a/include/openspace/util/time.h +++ b/include/openspace/util/time.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __TIME_H__ -#define __TIME_H__ +#ifndef __OPENSPACE_CORE___TIME___H__ +#define __OPENSPACE_CORE___TIME___H__ #include #include @@ -59,10 +59,20 @@ class SyncBuffer; class Time { public: + /** + * Converts the \p timeString representing a date to a double precision + * value representing the ephemeris time; that is the number of TDB + * seconds past the J2000 epoch. + * \param timeString A string representing the time to be converted + * \return The converted time; the number of TDB seconds past the J2000 epoch, + * representing the passed \p timeString + * \pre \p timeString must not be empty + */ + static double convertTime(const std::string& time); + Time(double secondsJ2000 = -1); Time(const Time& other); - /** * Initializes the Time singleton. * \return true if the initialization succeeded, false @@ -214,4 +224,4 @@ private: } // namespace openspace -#endif // __TIME_H__ +#endif // __OPENSPACE_CORE___TIME___H__ diff --git a/modules/globebrowsing/tile/layeredtextures.h b/include/openspace/util/timemanager.h similarity index 74% rename from modules/globebrowsing/tile/layeredtextures.h rename to include/openspace/util/timemanager.h index ab6ca68241..fb9468bcc9 100644 --- a/modules/globebrowsing/tile/layeredtextures.h +++ b/include/openspace/util/timemanager.h @@ -22,33 +22,29 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __LAYERED_TEXTURES_H__ -#define __LAYERED_TEXTURES_H__ +#ifndef __OPENSPACE_CORE___TIMEMANAGER___H__ +#define __OPENSPACE_CORE___TIMEMANAGER___H__ -#include -#include -#include +#include +#include namespace openspace { - class LayeredTextures { - - public: - - static const size_t NUM_TEXTURE_CATEGORIES = 6; - static const size_t MAX_NUM_TEXTURES_PER_CATEGORY = 5; - - enum TextureCategory { - ColorTextures, - GrayScaleOverlays, - NightTextures, - WaterMasks, - Overlays, - HeightMaps, - }; - - static const std::string TEXTURE_CATEGORY_NAMES[NUM_TEXTURE_CATEGORIES]; - }; +class TimeManager { +public: + void preSynchronization(double dt); + void addKeyframe(const datamessagestructures::TimeKeyframe& kf); + void removeKeyframesBefore(double timestamp); + void clearKeyframes(); +private: + void consumeKeyframes(double dt); + std::deque _keyframes; + static bool compareKeyframeTimes( + const datamessagestructures::TimeKeyframe& a, + const datamessagestructures::TimeKeyframe& b); + double _latestConsumedTimestamp; +}; } // namespace openspace -#endif // __LAYERED_TEXTURES_H__ \ No newline at end of file + +#endif // __OPENSPACE_CORE___TIMEMANAGER___H__ diff --git a/include/openspace/util/timerange.h b/include/openspace/util/timerange.h index 4e82e0dacf..80a99c1fbf 100644 --- a/include/openspace/util/timerange.h +++ b/include/openspace/util/timerange.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __TIMERANGE_H__ -#define __TIMERANGE_H__ +#ifndef __OPENSPACE_CORE___TIMERANGE___H__ +#define __OPENSPACE_CORE___TIMERANGE___H__ #include @@ -78,4 +78,4 @@ struct TimeRange { } // namespace openspace -#endif //__TIMERANGE_H__ +#endif //__OPENSPACE_CORE___TIMERANGE___H__ diff --git a/include/openspace/util/transformationmanager.h b/include/openspace/util/transformationmanager.h index abc6cfb741..c2b655fd5b 100644 --- a/include/openspace/util/transformationmanager.h +++ b/include/openspace/util/transformationmanager.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __TRANSFORMATIONMANAGER__ -#define __TRANSFORMATIONMANAGER__ +#ifndef __OPENSPACE_CORE___TRANSFORMATIONMANAGER___H__ +#define __OPENSPACE_CORE___TRANSFORMATIONMANAGER___H__ #include #include @@ -59,6 +59,6 @@ private: std::set _dipoleFrames; }; -} +} // namespace openspace - #endif //__TRANSFORMATIONMANAGER__ \ No newline at end of file + #endif //__OPENSPACE_CORE___TRANSFORMATIONMANAGER___H__ diff --git a/include/openspace/util/updatestructures.h b/include/openspace/util/updatestructures.h index 22ed70bef7..6708532276 100644 --- a/include/openspace/util/updatestructures.h +++ b/include/openspace/util/updatestructures.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __UPDATESTRUCTURES_H__ -#define __UPDATESTRUCTURES_H__ +#ifndef __OPENSPACE_CORE___UPDATESTRUCTURES___H__ +#define __OPENSPACE_CORE___UPDATESTRUCTURES___H__ #include #include @@ -45,8 +45,9 @@ struct TransformData { struct UpdateData { TransformData modelTransform; double time; - bool isTimeJump; double delta; + bool timePaused; + bool isTimeJump; bool doPerformanceMeasurement; }; @@ -75,7 +76,6 @@ struct RaycastData { std::string namespaceName; }; +} // namespace openspace -} - -#endif // __UPDATESTRUCTURES_H__ +#endif // __OPENSPACE_CORE___UPDATESTRUCTURES___H__ diff --git a/modules/base/CMakeLists.txt b/modules/base/CMakeLists.txt index 163dc6e976..87bfff60d8 100644 --- a/modules/base/CMakeLists.txt +++ b/modules/base/CMakeLists.txt @@ -27,24 +27,17 @@ include(${OPENSPACE_CMAKE_EXT_DIR}/module_definition.cmake) set(HEADER_FILES ${CMAKE_CURRENT_SOURCE_DIR}/rendering/modelgeometry.h ${CMAKE_CURRENT_SOURCE_DIR}/rendering/multimodelgeometry.h - ${CMAKE_CURRENT_SOURCE_DIR}/rendering/planetgeometry.h - ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableconstellationbounds.h ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablemodel.h ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablepath.h ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableplane.h - ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableplanet.h - ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablerings.h ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablesphere.h ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablesphericalgrid.h - ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablestars.h ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderabletrail.h - ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderabletrailnew.h - ${CMAKE_CURRENT_SOURCE_DIR}/rendering/simplespheregeometry.h + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderabletrailorbit.h + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderabletrailtrajectory.h ${CMAKE_CURRENT_SOURCE_DIR}/rendering/screenspaceframebuffer.h ${CMAKE_CURRENT_SOURCE_DIR}/rendering/screenspaceimage.h - ${CMAKE_CURRENT_SOURCE_DIR}/ephemeris/spiceephemeris.h - ${CMAKE_CURRENT_SOURCE_DIR}/ephemeris/staticephemeris.h - ${CMAKE_CURRENT_SOURCE_DIR}/rotation/spicerotation.h + ${CMAKE_CURRENT_SOURCE_DIR}/translation/statictranslation.h ${CMAKE_CURRENT_SOURCE_DIR}/rotation/staticrotation.h ${CMAKE_CURRENT_SOURCE_DIR}/scale/staticscale.h ) @@ -53,42 +46,27 @@ source_group("Header Files" FILES ${HEADER_FILES}) set(SOURCE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/rendering/modelgeometry.cpp ${CMAKE_CURRENT_SOURCE_DIR}/rendering/multimodelgeometry.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/rendering/planetgeometry.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableconstellationbounds.cpp ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablemodel.cpp ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablepath.cpp ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableplane.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableplanet.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablerings.cpp ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablesphere.cpp ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablesphericalgrid.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablestars.cpp ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderabletrail.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderabletrailnew.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/rendering/simplespheregeometry.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderabletrailorbit.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderabletrailtrajectory.cpp ${CMAKE_CURRENT_SOURCE_DIR}/rendering/screenspaceframebuffer.cpp ${CMAKE_CURRENT_SOURCE_DIR}/rendering/screenspaceimage.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/ephemeris/spiceephemeris.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/ephemeris/staticephemeris.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/rotation/spicerotation.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/translation/statictranslation.cpp ${CMAKE_CURRENT_SOURCE_DIR}/rotation/staticrotation.cpp ${CMAKE_CURRENT_SOURCE_DIR}/scale/staticscale.cpp ) source_group("Source Files" FILES ${SOURCE_FILES}) set(SHADER_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/constellationbounds_fs.glsl - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/constellationbounds_vs.glsl - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/ephemeris_fs.glsl - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/ephemeris_vs.glsl - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/renderabletrailnew_fs.glsl - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/renderabletrailnew_vs.glsl ${CMAKE_CURRENT_SOURCE_DIR}/shaders/imageplane_fs.glsl ${CMAKE_CURRENT_SOURCE_DIR}/shaders/imageplane_vs.glsl ${CMAKE_CURRENT_SOURCE_DIR}/shaders/model_fs.glsl ${CMAKE_CURRENT_SOURCE_DIR}/shaders/model_vs.glsl - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/nighttexture_fs.glsl - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/nighttexture_vs.glsl ${CMAKE_CURRENT_SOURCE_DIR}/shaders/path_fs.glsl ${CMAKE_CURRENT_SOURCE_DIR}/shaders/path_gs.glsl ${CMAKE_CURRENT_SOURCE_DIR}/shaders/path_vs.glsl @@ -96,15 +74,12 @@ set(SHADER_FILES ${CMAKE_CURRENT_SOURCE_DIR}/shaders/plane_vs.glsl ${CMAKE_CURRENT_SOURCE_DIR}/shaders/pscstandard_fs.glsl ${CMAKE_CURRENT_SOURCE_DIR}/shaders/pscstandard_vs.glsl - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/rings_vs.glsl - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/rings_fs.glsl - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/sphere_fs.glsl - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/sphere_vs.glsl - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/star_fs.glsl - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/star_ge.glsl - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/star_vs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/renderabletrail_fs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/renderabletrail_vs.glsl ${CMAKE_CURRENT_SOURCE_DIR}/shaders/screenspace_fs.glsl ${CMAKE_CURRENT_SOURCE_DIR}/shaders/screenspace_vs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/sphere_fs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/sphere_vs.glsl ) source_group("Shader Files" FILES ${SHADER_FILES}) diff --git a/modules/base/basemodule.cpp b/modules/base/basemodule.cpp index e1725442fe..73c6a5779b 100644 --- a/modules/base/basemodule.cpp +++ b/modules/base/basemodule.cpp @@ -31,28 +31,20 @@ #include #include -#include -#include -#include -#include #include -#include #include #include -#include -#include +#include +#include #include -#include #include #include #include #include -#include -#include +#include #include -#include #include @@ -65,10 +57,6 @@ BaseModule::BaseModule() {} void BaseModule::internalInitialize() { - FactoryManager::ref().addFactory( - std::make_unique>(), - "PlanetGeometry" - ); FactoryManager::ref().addFactory( std::make_unique>(), "ModelGeometry" @@ -78,15 +66,6 @@ void BaseModule::internalInitialize() { "ScreenSpaceRenderable" ); - FactoryManager::ref().addFactory( - std::make_unique>(), - "Rotation" - ); - FactoryManager::ref().addFactory( - std::make_unique>(), - "Scale" - ); - auto fScreenSpaceRenderable = FactoryManager::ref().factory(); ghoul_assert(fScreenSpaceRenderable, "ScreenSpaceRenderable factory was not created"); @@ -96,39 +75,29 @@ void BaseModule::internalInitialize() { auto fRenderable = FactoryManager::ref().factory(); ghoul_assert(fRenderable, "Renderable factory was not created"); - fRenderable->registerClass("RenderableConstellationBounds"); fRenderable->registerClass("RenderableModel"); fRenderable->registerClass("RenderablePath"); fRenderable->registerClass("RenderablePlane"); - fRenderable->registerClass("RenderablePlanet"); - fRenderable->registerClass("RenderableRings"); fRenderable->registerClass("RenderableSphere"); fRenderable->registerClass("RenderableSphericalGrid"); - fRenderable->registerClass("RenderableStars"); - fRenderable->registerClass("RenderableTrail"); - fRenderable->registerClass("RenderableTrailNew"); + fRenderable->registerClass("RenderableTrailOrbit"); + fRenderable->registerClass("RenderableTrailTrajectory"); - auto fEphemeris = FactoryManager::ref().factory(); - ghoul_assert(fEphemeris, "Ephemeris factory was not created"); + auto fTranslation = FactoryManager::ref().factory(); + ghoul_assert(fTranslation, "Ephemeris factory was not created"); - fEphemeris->registerClass("StaticEphemeris"); - fEphemeris->registerClass("SpiceEphemeris"); + fTranslation->registerClass("StaticTranslation"); auto fRotation = FactoryManager::ref().factory(); ghoul_assert(fRotation, "Rotation factory was not created"); fRotation->registerClass("StaticRotation"); - fRotation->registerClass("SpiceRotation"); auto fScale = FactoryManager::ref().factory(); ghoul_assert(fScale, "Scale factory was not created"); fScale->registerClass ("StaticScale"); - auto fPlanetGeometry = FactoryManager::ref().factory(); - ghoul_assert(fPlanetGeometry, "Planet geometry factory was not created"); - fPlanetGeometry->registerClass("SimpleSphere"); - auto fModelGeometry = FactoryManager::ref().factory(); ghoul_assert(fModelGeometry, "Model geometry factory was not created"); fModelGeometry->registerClass("MultiModelGeometry"); @@ -137,8 +106,10 @@ void BaseModule::internalInitialize() { std::vector BaseModule::documentations() const { return { StaticScale::Documentation(), - StaticEphemeris::Documentation(), - SpiceEphemeris::Documentation() + StaticTranslation::Documentation(), + RenderableTrailOrbit::Documentation(), + RenderableTrailTrajectory::Documentation(), + modelgeometry::ModelGeometry::Documentation(), }; } diff --git a/modules/base/basemodule.h b/modules/base/basemodule.h index f9838dbe31..ab115abb1a 100644 --- a/modules/base/basemodule.h +++ b/modules/base/basemodule.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __BASEMODULE_H__ -#define __BASEMODULE_H__ +#ifndef __OPENSPACE_MODULE_BASE___BASEMODULE___H__ +#define __OPENSPACE_MODULE_BASE___BASEMODULE___H__ #include @@ -41,4 +41,4 @@ protected: } // namespace openspace -#endif // __BASEMODULE_H__ +#endif // __OPENSPACE_MODULE_BASE___BASEMODULE___H__ diff --git a/modules/base/rendering/modelgeometry.cpp b/modules/base/rendering/modelgeometry.cpp index 655c883a2e..28e90ed083 100644 --- a/modules/base/rendering/modelgeometry.cpp +++ b/modules/base/rendering/modelgeometry.cpp @@ -23,6 +23,8 @@ ****************************************************************************************/ #include + +#include #include #include #include @@ -33,61 +35,72 @@ namespace { const std::string _loggerCat = "ModelGeometry"; const std::string keyGeomModelFile = "GeometryFile"; const int8_t CurrentCacheVersion = 3; - const std::string keyType = "Type"; - const std::string keyName = "Name"; - const std::string keySize = "Magnification"; + const char* keyType = "Type"; + const char* keyName = "Name"; } namespace openspace { namespace modelgeometry { +Documentation ModelGeometry::Documentation() { + using namespace documentation; + return { + "Model Geometry", + "base_geometry_model", + { + { + keyType, + new StringVerifier, + "The type of the Model Geometry that should be generated", + Optional::No + }, + { + keyGeomModelFile, + new StringVerifier, + "The file that should be loaded in this ModelGeometry. The file can " + "contain filesystem tokens or can be specified relatively to the " + "location of the .mod file.", + Optional::No + } + } + }; +} + + ModelGeometry* ModelGeometry::createFromDictionary(const ghoul::Dictionary& dictionary) { - std::string geometryType; - const bool success = dictionary.getValue( - keyType, geometryType); - if (!success) { - LERROR("ModelGeometry did not contain a correct value of the key '" - << keyType << "'"); - return nullptr; + if (!dictionary.hasKeyAndValue(keyType)) { + throw ghoul::RuntimeError("Dictionary did not contain a key 'Type'"); } - ghoul::TemplateFactory* factory - = FactoryManager::ref().factory(); + + std::string geometryType = dictionary.value(keyType); + auto factory = FactoryManager::ref().factory(); ModelGeometry* result = factory->create(geometryType, dictionary); if (result == nullptr) { - LERROR("Failed to create a ModelGeometry object of type '" << geometryType - << "'"); - return nullptr; + throw ghoul::RuntimeError( + "Failed to create a ModelGeometry object of type '" + geometryType + "'" + ); } return result; } ModelGeometry::ModelGeometry(const ghoul::Dictionary& dictionary) : _parent(nullptr) - , _magnification("magnification", "Magnification", 1.f, 0.f, 10.f) , _mode(GL_TRIANGLES) { + documentation::testSpecificationAndThrow( + Documentation(), + dictionary, + "ModelGeometry" + ); + setName("ModelGeometry"); std::string name; bool success = dictionary.getValue(keyName, name); ghoul_assert(success, "Name tag was not present"); - if (dictionary.hasKeyAndValue(keySize)) - _magnification = static_cast(dictionary.value(keySize)); - - success = dictionary.getValue(keyGeomModelFile, _file); - if (!success) { - LERROR("Geometric Model file of '" << name << "' did not provide a key '" - << keyGeomModelFile << "'"); - } - _file = FileSys.absolutePath(_file); - - if (!FileSys.fileExists(_file, ghoul::filesystem::FileSystem::RawPath::Yes)) - LERROR("Could not load the geometric model file '" << _file << "': File not found"); - - - addProperty(_magnification); + _file = absPath(dictionary.value(keyGeomModelFile)); } double ModelGeometry::boundingRadius() const { @@ -273,7 +286,6 @@ bool ModelGeometry::getIndices(std::vector* indexList) { } void ModelGeometry::setUniforms(ghoul::opengl::ProgramObject& program) { - program.setUniform("_magnification", _magnification); } } // namespace modelgeometry diff --git a/modules/base/rendering/modelgeometry.h b/modules/base/rendering/modelgeometry.h index b85062b897..8cd5a9abba 100644 --- a/modules/base/rendering/modelgeometry.h +++ b/modules/base/rendering/modelgeometry.h @@ -22,12 +22,12 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __MODELGEOMETRY_H__ -#define __MODELGEOMETRY_H__ +#ifndef __OPENSPACE_MODULE_BASE___MODELGEOMETRY___H__ +#define __OPENSPACE_MODULE_BASE___MODELGEOMETRY___H__ #include -#include +#include #include #include @@ -59,13 +59,14 @@ public: virtual void setUniforms(ghoul::opengl::ProgramObject& program); + static openspace::Documentation Documentation(); + protected: Renderable* _parent; bool loadObj(const std::string& filename); bool loadCachedFile(const std::string& filename); bool saveCachedFile(const std::string& filename); - properties::FloatProperty _magnification; GLuint _vaoID; GLuint _vbo; @@ -80,4 +81,4 @@ protected: } // namespace modelgeometry } // namespace openspace -#endif // __MODELGEOMETRY_H__ +#endif // __OPENSPACE_MODULE_BASE___MODELGEOMETRY___H__ diff --git a/modules/base/rendering/multimodelgeometry.cpp b/modules/base/rendering/multimodelgeometry.cpp index fd05e38772..27bf69034b 100644 --- a/modules/base/rendering/multimodelgeometry.cpp +++ b/modules/base/rendering/multimodelgeometry.cpp @@ -1,26 +1,26 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ #include @@ -35,66 +35,53 @@ namespace { } namespace openspace { - namespace modelgeometry { +namespace modelgeometry { - MultiModelGeometry::MultiModelGeometry(const ghoul::Dictionary& dictionary) - : ModelGeometry(dictionary) - { - loadObj(_file); - } +MultiModelGeometry::MultiModelGeometry(const ghoul::Dictionary& dictionary) + : ModelGeometry(dictionary) +{ + loadObj(_file); +} - bool MultiModelGeometry::initialize(Renderable* parent) - { - bool success = ModelGeometry::initialize(parent); - return success; - } +bool MultiModelGeometry::initialize(Renderable* parent) { + bool success = ModelGeometry::initialize(parent); + return success; +} - void MultiModelGeometry::deinitialize() - { - ModelGeometry::deinitialize(); - } +void MultiModelGeometry::deinitialize() { + ModelGeometry::deinitialize(); +} - bool MultiModelGeometry::loadModel(const std::string& filename) - { - try { - ghoul::io::ModelReaderMultiFormat modelReader; +bool MultiModelGeometry::loadModel(const std::string& filename) { + ghoul::io::ModelReaderMultiFormat modelReader; - std::vector vertices; - std::vector indices; + std::vector vertices; + std::vector indices; - modelReader.loadModel(filename, vertices, indices); + modelReader.loadModel(filename, vertices, indices); - _vertices.reserve(vertices.size()); - for (const auto & v : vertices) - { - psc p = PowerScaledCoordinate::CreatePowerScaledCoordinate( - v.location[0], - v.location[1], - v.location[2] - ); + _vertices.reserve(vertices.size()); + for (const auto & v : vertices) { + psc p = PowerScaledCoordinate::CreatePowerScaledCoordinate( + v.location[0], + v.location[1], + v.location[2] + ); - Vertex vv; - memcpy(vv.location, v.location, sizeof(GLfloat) * 3); - vv.location[3] = 1.0; - //memcpy(vv.location, glm::value_ptr(p.vec4()), sizeof(GLfloat) * 4); - memcpy(vv.tex, v.tex, sizeof(GLfloat) * 2); - memcpy(vv.normal, v.normal, sizeof(GLfloat) * 3); - _vertices.push_back(vv); - } + Vertex vv; + memcpy(vv.location, v.location, sizeof(GLfloat) * 3); + vv.location[3] = 1.0; + //memcpy(vv.location, glm::value_ptr(p.vec4()), sizeof(GLfloat) * 4); + memcpy(vv.tex, v.tex, sizeof(GLfloat) * 2); + memcpy(vv.normal, v.normal, sizeof(GLfloat) * 3); + _vertices.push_back(vv); + } - _indices.resize(indices.size()); - std::copy(indices.begin(), indices.end(), _indices.begin()); - } - catch (ghoul::io::ModelReaderBase::ModelReaderException & e) - { - // Log error reading geometry file. - LERROR(e.message); - return false; - } + _indices.resize(indices.size()); + std::copy(indices.begin(), indices.end(), _indices.begin()); - return true; - } + return true; +} - - } // namespace modelgeometry +} // namespace modelgeometry } // namespace openspace diff --git a/modules/base/rendering/multimodelgeometry.h b/modules/base/rendering/multimodelgeometry.h index e343a30be9..ce4d8436e7 100644 --- a/modules/base/rendering/multimodelgeometry.h +++ b/modules/base/rendering/multimodelgeometry.h @@ -1,51 +1,51 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __MULTIMODELGEOMETRY_H__ -#define __MULTIMODELGEOMETRY_H__ +#ifndef __OPENSPACE_MODULE_BASE___MULTIMODELGEOMETRY___H__ +#define __OPENSPACE_MODULE_BASE___MULTIMODELGEOMETRY___H__ #include namespace openspace { - class RenderableModel; - class RenderableModelProjection; +class RenderableModel; +class RenderableModelProjection; - namespace modelgeometry { +namespace modelgeometry { - class MultiModelGeometry : public ModelGeometry { - public: - MultiModelGeometry(const ghoul::Dictionary& dictionary); +class MultiModelGeometry : public ModelGeometry { +public: + MultiModelGeometry(const ghoul::Dictionary& dictionary); - bool initialize(Renderable* parent) override; - void deinitialize() override; + bool initialize(Renderable* parent) override; + void deinitialize() override; - private: - bool loadModel(const std::string& filename); - }; +private: + bool loadModel(const std::string& filename); +}; - } // namespace modelgeometry +} // namespace modelgeometry } // namespace openspace -#endif // __MULTIMODELOBJECT_H__ +#endif // __OPENSPACE_MODULE_BASE___MULTIMODELGEOMETRY___H__ diff --git a/modules/base/rendering/renderablecrawlingline.cpp b/modules/base/rendering/renderablecrawlingline.cpp deleted file mode 100644 index 0500781d21..0000000000 --- a/modules/base/rendering/renderablecrawlingline.cpp +++ /dev/null @@ -1,182 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2015 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#include - -#include -#include -#include -#include -//#include - -namespace { - const std::string _loggerCat = "RenderableCrawlingLine"; - - const std::string KeySource = "Source"; - const std::string KeyTarget = "Target"; - const std::string KeyInstrument = "Instrument"; - const std::string KeyReferenceFrame = "Frame"; - const std::string keyColor = "RGB"; - - static const int SourcePosition = 0; - static const int TargetPosition = 1; -} - -namespace openspace { - -RenderableCrawlingLine::RenderableCrawlingLine(const ghoul::Dictionary& dictionary) - : Renderable(dictionary) - , _program(nullptr) - , _imageSequenceTime(-1.f) - , _vao(0) - , _vbo(0) -{ - dictionary.getValue(KeySource, _source); - dictionary.getValue(KeyTarget, _target); - dictionary.getValue(KeyInstrument, _instrumentName); - dictionary.getValue(KeyReferenceFrame, _referenceFrame); - - - if (dictionary.hasKeyAndValue(keyColor)) - dictionary.getValue(keyColor, _lineColor); - else - _lineColor = glm::vec3(1); -} - -bool RenderableCrawlingLine::isReady() const { - bool ready = true; - ready &= !_source.empty(); - ready &= !_target.empty(); - ready &= !_instrumentName.empty(); - ready &= (_program != nullptr); - return ready; -} - -bool RenderableCrawlingLine::initialize() { - _frameCounter = 0; - bool completeSuccess = true; - _program = ghoul::opengl::ProgramObject::Build("RenderableCrawlingLine", - "${SHADERS}/modules/crawlingline/crawlingline_vs.glsl", - "${SHADERS}/modules/crawlingline/crawlingline_fs.glsl" - ); - if (!_program) - return false; - - glGenVertexArrays(1, &_vao); - glGenBuffers(1, &_vbo); - - glBindVertexArray(_vao); - glBindBuffer(GL_ARRAY_BUFFER, _vbo); - glBufferData(GL_ARRAY_BUFFER, 2 * sizeof(psc), NULL, GL_DYNAMIC_DRAW); - - glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, (void*)0); - - glBindVertexArray(0); - - return completeSuccess; -} - -bool RenderableCrawlingLine::deinitialize(){ - glDeleteVertexArrays(1, &_vao); - _vao = 0; - glDeleteBuffers(1, &_vbo); - _vbo = 0; - return true; -} - -void RenderableCrawlingLine::render(const RenderData& data) { - if (_drawLine) { - _program->activate(); - _frameCounter++; - // fetch data - psc currentPosition = data.position; - psc campos = data.camera.position(); - glm::mat4 camrot = data.camera.viewRotationMatrix(); - - glm::mat4 transform = glm::mat4(1); - - // setup the data to the shader - _program->setUniform("ViewProjection", data.camera.viewProjectionMatrix()); - _program->setUniform("ModelTransform", transform); - - int frame = _frameCounter % 60; - float fadingFactor = static_cast(sin((frame * pi_c()) / 60)); - float alpha = 0.6f + fadingFactor*0.4f; - - glLineWidth(2.f); - - _program->setUniform("_alpha", alpha); - _program->setUniform("color", _lineColor); - setPscUniforms(_program, &data.camera, data.position); - - glBindVertexArray(_vao); - glBindBuffer(GL_ARRAY_BUFFER, _vbo); - glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(psc) * 2, _positions); - - glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0); - - glDrawArrays(GL_LINES, 0, 2); - glBindVertexArray(0); - - _program->deactivate(); - } -} - -void RenderableCrawlingLine::update(const UpdateData& data) { - if (_program->isDirty()) - _program->rebuildFromFile(); - glm::dmat3 transformMatrix = glm::dmat3(1); - openspace::SpiceManager::ref().getPositionTransformMatrix(_source, _referenceFrame, data.time, transformMatrix); - - glm::mat4 tmp = glm::mat4(1); - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 3; j++){ - tmp[i][j] = static_cast(transformMatrix[i][j]); - } - } - - _positions[SourcePosition] = PowerScaledCoordinate::CreatePowerScaledCoordinate(0, 0, 0); - - std::string shape, instrument; - std::vector bounds; - glm::dvec3 boresight; - - bool found = openspace::SpiceManager::ref().getFieldOfView(_source, shape, instrument, boresight, bounds); - if (!found) - LERROR("Could not find field of view for instrument"); - glm::vec4 target(boresight[0], boresight[1], boresight[2], 12); - target = tmp * target; - - _positions[TargetPosition] = target; - - if (ImageSequencer2::ref().isReady()) { - _imageSequenceTime = ImageSequencer2::ref().instrumentActiveTime(_instrumentName); - _drawLine = _imageSequenceTime != -1.f; - } -} - - -} \ No newline at end of file diff --git a/modules/base/rendering/renderablemodel.cpp b/modules/base/rendering/renderablemodel.cpp index c98e2480c5..aab085b9ae 100644 --- a/modules/base/rendering/renderablemodel.cpp +++ b/modules/base/rendering/renderablemodel.cpp @@ -22,12 +22,9 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -// temporary includes (will fix as soon as I figure out how class hierarchy should work, -// ie after I see model on screen) - -// open space includes -#include #include + +#include #include #include @@ -37,7 +34,6 @@ #include #include -#include #include @@ -46,13 +42,13 @@ namespace { const std::string _loggerCat = "RenderableModel"; - const std::string keyGeometry = "Geometry"; - const std::string keyBody = "Body"; - const std::string keyStart = "StartTime"; - const std::string keyEnd = "EndTime"; - const std::string keyFading = "Shading.Fadeable"; + const char* keyGeometry = "Geometry"; + const char* keyBody = "Body"; + const char* keyStart = "StartTime"; + const char* keyEnd = "EndTime"; + const char* keyFading = "Shading.Fadeable"; - const std::string keyModelTransform = "Rotation.ModelTransform"; + const char* keyModelTransform = "Rotation.ModelTransform"; //const std::string keyGhosting = "Shading.Ghosting"; } @@ -177,18 +173,6 @@ void RenderableModel::render(const RenderData& data) { double lt; - // Fade away if it does not have spice coverage - double time = openspace::Time::ref().j2000Seconds(); - bool targetPositionCoverage = openspace::SpiceManager::ref().hasSpkCoverage(_target, time); - if (!targetPositionCoverage) { - int frame = _frameCount % 180; - - float fadingFactor = static_cast(sin((frame * M_PI) / 180)); - _alpha = 0.5f + fadingFactor * 0.5f; - } - else - _alpha = 1.0f; - // Fading if (_performFade && _fading > 0.f) { _fading = _fading - 0.01f; @@ -261,7 +245,7 @@ void RenderableModel::update(const UpdateData& data) { //} double lt; - _sunPos = openspace::SpiceManager::ref().targetPosition("SUN", "SUN", "GALACTIC", {}, _time, lt); + _sunPos = OsEng.renderEngine().scene()->sceneGraphNode("Sun")->worldPosition(); } void RenderableModel::loadTexture() { diff --git a/modules/base/rendering/renderablemodel.h b/modules/base/rendering/renderablemodel.h index 19724e482d..2921b47ee4 100644 --- a/modules/base/rendering/renderablemodel.h +++ b/modules/base/rendering/renderablemodel.h @@ -22,12 +22,15 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERABLEMODEL_H__ -#define __RENDERABLEMODEL_H__ +#ifndef __OPENSPACE_MODULE_BASE___RENDERABLEMODEL___H__ +#define __OPENSPACE_MODULE_BASE___RENDERABLEMODEL___H__ #include #include +#include +#include +#include #include #include @@ -84,4 +87,4 @@ private: } // namespace openspace -#endif // __RENDERABLEMODEL_H__ +#endif // __OPENSPACE_MODULE_BASE___RENDERABLEMODEL___H__ diff --git a/modules/base/rendering/renderablepath.cpp b/modules/base/rendering/renderablepath.cpp index be5547aefd..f0e3623950 100644 --- a/modules/base/rendering/renderablepath.cpp +++ b/modules/base/rendering/renderablepath.cpp @@ -42,17 +42,16 @@ namespace { const std::string _loggerCat = "RenderableTrail"; //constants - const std::string keyName = "Name"; - const std::string keyBody = "Body"; - const std::string keyObserver = "Observer"; - const std::string keyFrame = "Frame"; - const std::string keyPathModule = "ModulePath"; - const std::string keyColor = "RGB"; - const std::string keyTimeSteps = "TimeSteps"; - const std::string keyPointSteps = "PointSteps"; - const std::string keyDrawLine = "DrawLine"; - const std::string keRenderDistanceInterval = "RenderDistanceInterval"; - + const char* keyName = "Name"; + const char* keyBody = "Body"; + const char* keyObserver = "Observer"; + const char* keyFrame = "Frame"; + const char* keyPathModule = "ModulePath"; + const char* keyColor = "RGB"; + const char* keyTimeSteps = "TimeSteps"; + const char* keyPointSteps = "PointSteps"; + const char* keyDrawLine = "DrawLine"; + const char* keRenderDistanceInterval = "RenderDistanceInterval"; } namespace openspace { diff --git a/modules/base/rendering/renderablepath.h b/modules/base/rendering/renderablepath.h index 4e8cdeefb7..e83fc305da 100644 --- a/modules/base/rendering/renderablepath.h +++ b/modules/base/rendering/renderablepath.h @@ -22,12 +22,12 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERABLEPATH_H__ -#define __RENDERABLEPATH_H__ +#ifndef __OPENSPACE_MODULE_BASE___RENDERABLEPATH___H__ +#define __OPENSPACE_MODULE_BASE___RENDERABLEPATH___H__ #include -#include -#include +#include +#include #include @@ -91,4 +91,4 @@ private: } // namespace openspace -#endif // __RENDERABLEPATH_H__ +#endif // __OPENSPACE_MODULE_BASE___RENDERABLEPATH___H__ diff --git a/modules/base/rendering/renderableplane.cpp b/modules/base/rendering/renderableplane.cpp index 3d43ee6c66..3c88efce3a 100644 --- a/modules/base/rendering/renderableplane.cpp +++ b/modules/base/rendering/renderableplane.cpp @@ -38,14 +38,14 @@ #include namespace { - const std::string _loggerCat = "RenderablePlane"; + static const std::string _loggerCat = "RenderablePlane"; - const std::string keyFieldlines = "Fieldlines"; - const std::string keyFilename = "File"; - const std::string keyHints = "Hints"; - const std::string keyShaders = "Shaders"; - const std::string keyVertexShader = "VertexShader"; - const std::string keyFragmentShader = "FragmentShader"; + const char* keyFieldlines = "Fieldlines"; + const char* keyFilename = "File"; + const char* keyHints = "Hints"; + const char* keyShaders = "Shaders"; + const char* keyVertexShader = "VertexShader"; + const char* keyFragmentShader = "FragmentShader"; } namespace openspace { diff --git a/modules/base/rendering/renderableplane.h b/modules/base/rendering/renderableplane.h index fc4e8f795c..3b8ce519dd 100644 --- a/modules/base/rendering/renderableplane.h +++ b/modules/base/rendering/renderableplane.h @@ -22,13 +22,14 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef RENDERABLEPLANE_H_ -#define RENDERABLEPLANE_H_ +#ifndef __OPENSPACE_MODULE_BASE___RENDERABLEPLANE___H__ +#define __OPENSPACE_MODULE_BASE___RENDERABLEPLANE___H__ #include #include -#include +#include +#include #include namespace ghoul { @@ -91,4 +92,5 @@ private: }; } // namespace openspace -#endif // RENDERABLEFIELDLINES_H_ + +#endif // __OPENSPACE_MODULE_BASE___RENDERABLEPLANE___H__ diff --git a/modules/base/rendering/renderableplanet.cpp b/modules/base/rendering/renderableplanet.cpp deleted file mode 100644 index eac80732c3..0000000000 --- a/modules/base/rendering/renderableplanet.cpp +++ /dev/null @@ -1,2039 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -// open space includes -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include -#include - -#define _USE_MATH_DEFINES -#include - - -namespace { - const std::string _loggerCat = "RenderablePlanet"; - - const std::string keyFrame = "Frame"; - const std::string keyGeometry = "Geometry"; - const std::string keyRadius = "Radius"; - const std::string keyShading = "PerformShading"; - const std::string keyShadowGroup = "Shadow_Group"; - const std::string keyShadowSource = "Source"; - const std::string keyShadowCaster = "Caster"; - const std::string keyAtmosphere = "Atmosphere"; - const std::string keyAtmosphereRadius = "AtmoshereRadius"; - const std::string keyPlanetRadius = "PlanetRadius"; - const std::string keyAverageGroundReflectance = "PlanetAverageGroundReflectance"; - const std::string keyRayleigh = "Rayleigh"; - const std::string keyRayleighHeightScale = "H_R"; - const std::string keyMie = "Mie"; - const std::string keyMieHeightScale = "H_M"; - const std::string keyMiePhaseConstant = "G"; - const std::string keyBody = "Body"; -} - -namespace openspace { - -RenderablePlanet::RenderablePlanet(const ghoul::Dictionary& dictionary) - : Renderable(dictionary) - , _colorTexturePath("colorTexture", "Color Texture") - , _nightTexturePath("nightTexture", "Night Texture") - , _heightMapTexturePath("heightMap", "Heightmap Texture") - , _cloudsTexturePath("clouds", "Clouds Texture") - , _reflectanceTexturePath("reflectance", "Reflectance Texture") - , _heightExaggeration("heightExaggeration", "Height Exaggeration", 1.f, 0.f, 10.f) - , _programObject(nullptr) - , _transmittanceProgramObject(nullptr) - , _irradianceProgramObject(nullptr) - , _irradianceSupTermsProgramObject(nullptr) - , _inScatteringProgramObject(nullptr) - , _inScatteringSupTermsProgramObject(nullptr) - , _deltaEProgramObject(nullptr) - , _deltaSProgramObject(nullptr) - , _deltaSSupTermsProgramObject(nullptr) - , _deltaJProgramObject(nullptr) - , _atmosphereProgramObject(nullptr) - , _texture(nullptr) - , _nightTexture(nullptr) - , _reflectanceTexture(nullptr) - , _heightMapTexture(nullptr) - , _cloudsTexture(nullptr) - , _geometry(nullptr) - , _performShading("performShading", "Perform Shading", true) - , _rotation("rotation", "Rotation", 0, 0, 360) - , _alpha(1.f) - , _planetRadius(0.f) - , _transmittanceTableTexture(0) - , _irradianceTableTexture(0) - , _inScatteringTableTexture(0) - , _deltaETableTexture(0) - , _deltaSRayleighTableTexture(0) - , _deltaSMieTableTexture(0) - , _deltaJTableTexture(0) - , _dummyTexture(0) - , _dummy3DTexture(0) - , _atmosphereTexture(0) - , _atmosphereFBO(0) - , _atmosphereRenderVAO(0) - , _atmosphereRenderVBO(0) - , _atmosphereCalculated(false) - , _atmosphereEnabled(false) - , _atmosphereRadius(0.f) - , _atmospherePlanetRadius(0.f) - , _planetAverageGroundReflectance(0.f) - , _rayleighHeightScale(0.f) - , _mieHeightScale(0.f) - , _miePhaseConstant(0.f) - , _mieExtinctionCoeff(glm::vec3(0.f)) - , _rayleighScatteringCoeff(glm::vec3(0.f)) - , _mieScatteringCoeff(glm::vec3(0.f)) - , _hasNightTexture(false) - , _hasHeightTexture(false) - , _hasReflectanceTexture(false) - , _hasCloudsTexture(false) - , _shadowEnabled(false) -{ - std::string name; - bool success = dictionary.getValue(SceneGraphNode::KeyName, name); - ghoul_assert(success, - "RenderablePlanet need the '" << SceneGraphNode::KeyName<<"' be specified"); - - //std::string path; - //success = dictionary.getValue(constants::scenegraph::keyPathModule, path); - //ghoul_assert(success, - // "RenderablePlanet need the '"<(keyShading)) { - bool shading; - dictionary.getValue(keyShading, shading); - _performShading = shading; - } - - addProperty(_performShading); - // Mainly for debugging purposes @AA - addProperty(_rotation); - - - // Shadow data: - ghoul::Dictionary shadowDictionary; - success = dictionary.getValue(keyShadowGroup, shadowDictionary); - bool disableShadows = false; - if (success) { - std::vector< std::pair > sourceArray; - unsigned int sourceCounter = 1; - while (success) { - std::string sourceName; - std::stringstream ss; - ss << keyShadowSource << sourceCounter << ".Name"; - success = shadowDictionary.getValue(ss.str(), sourceName); - if (success) { - glm::vec2 sourceRadius; - ss.str(std::string()); - ss << keyShadowSource << sourceCounter << ".Radius"; - success = shadowDictionary.getValue(ss.str(), sourceRadius); - if (success) { - sourceArray.push_back(std::pair< std::string, float>( - sourceName, sourceRadius[0] * pow(10.f, sourceRadius[1]))); - } - else { - LWARNING("No Radius value expecified for Shadow Source Name " - << sourceName << " from " << name - << " planet.\nDisabling shadows for this planet."); - disableShadows = true; - break; - } - } - sourceCounter++; - } - - if (!disableShadows && !sourceArray.empty()) { - success = true; - std::vector< std::pair > casterArray; - unsigned int casterCounter = 1; - while (success) { - std::string casterName; - std::stringstream ss; - ss << keyShadowCaster << casterCounter << ".Name"; - success = shadowDictionary.getValue(ss.str(), casterName); - if (success) { - glm::vec2 casterRadius; - ss.str(std::string()); - ss << keyShadowCaster << casterCounter << ".Radius"; - success = shadowDictionary.getValue(ss.str(), casterRadius); - if (success) { - casterArray.push_back(std::pair< std::string, float>( - casterName, casterRadius[0] * pow(10.f, casterRadius[1]))); - } - else { - LWARNING("No Radius value expecified for Shadow Caster Name " - << casterName << " from " << name - << " planet.\nDisabling shadows for this planet."); - disableShadows = true; - break; - } - } - - casterCounter++; - } - - if (!disableShadows && (!sourceArray.empty() && !casterArray.empty())) { - for (const auto & source : sourceArray) - for (const auto & caster : casterArray) { - ShadowConf sc; - sc.source = source; - sc.caster = caster; - _shadowConfArray.push_back(sc); - } - _shadowEnabled = true; - } - } - } - - // Atmosphere data: - bool errorReadingAtmosphereData = false; - ghoul::Dictionary atmosphereDictionary; - success = dictionary.getValue(keyAtmosphere, atmosphereDictionary); - if (success) { - if (!atmosphereDictionary.getValue(keyAtmosphereRadius, _atmosphereRadius)) { - errorReadingAtmosphereData = true; - LWARNING("No Atmosphere Radius value expecified for Atmosphere Effects of " - << name << " planet.\nDisabling atmosphere effects for this planet."); - } - - if (!atmosphereDictionary.getValue(keyPlanetRadius, _atmospherePlanetRadius)) { - errorReadingAtmosphereData = true; - LWARNING("No Planet Radius value expecified for Atmosphere Effects of " - << name << " planet.\nDisabling atmosphere effects for this planet."); - } - - if (!atmosphereDictionary.getValue(keyAverageGroundReflectance, _planetAverageGroundReflectance)) { - errorReadingAtmosphereData = true; - LWARNING("No Average Atmosphere Ground Reflectance value expecified for Atmosphere Effects of " - << name << " planet.\nDisabling atmosphere effects for this planet."); - } - - ghoul::Dictionary rayleighDictionary; - success = atmosphereDictionary.getValue(keyRayleigh, rayleighDictionary); - - if (success) { - // Not using right now. - glm::vec3 rayleighWavelengths; - success = rayleighDictionary.getValue("Coefficients.Wavelengths", rayleighWavelengths); - - if (!rayleighDictionary.getValue("Coefficients.Scattering", _rayleighScatteringCoeff)) { - errorReadingAtmosphereData = true; - LWARNING("No Rayleigh Scattering parameters expecified for Atmosphere Effects of " - << name << " planet.\nDisabling atmosphere effects for this planet."); - } - - if (!rayleighDictionary.getValue(keyRayleighHeightScale, _rayleighHeightScale)) { - errorReadingAtmosphereData = true; - LWARNING("No Rayleigh Height Scale value expecified for Atmosphere Effects of " - << name << " planet.\nDisabling atmosphere effects for this planet."); - } - } - else { - errorReadingAtmosphereData = true; - LWARNING("No Rayleigh parameters expecified for Atmosphere Effects of " - << name << " planet.\nDisabling atmosphere effects for this planet."); - } - - ghoul::Dictionary mieDictionary; - success = atmosphereDictionary.getValue(keyMie, mieDictionary); - if (success) { - if (!mieDictionary.getValue(keyMieHeightScale, _mieHeightScale)) { - errorReadingAtmosphereData = true; - LWARNING("No Mie Height Scale value expecified for Atmosphere Effects of " - << name << " planet.\nDisabling atmosphere effects for this planet."); - } - - if (!mieDictionary.getValue("Coefficients.Scattering", _mieScatteringCoeff)) { - errorReadingAtmosphereData = true; - LWARNING("No Mie Scattering parameters expecified for Atmosphere Effects of " - << name << " planet.\nDisabling atmosphere effects for this planet."); - } - - if (!mieDictionary.getValue("Coefficients.Extinction", _mieExtinctionCoeff)) { - errorReadingAtmosphereData = true; - LWARNING("No Mie Extinction parameters expecified for Atmosphere Effects of " - << name << " planet.\nDisabling atmosphere effects for this planet."); - } - - if (!mieDictionary.getValue(keyMiePhaseConstant, _miePhaseConstant)) { - errorReadingAtmosphereData = true; - LWARNING("No Mie Phase Constant value expecified for Atmosphere Effects of " - << name << " planet.\nDisabling atmosphere effects for this planet."); - } - } - else { - errorReadingAtmosphereData = true; - LWARNING("No Mie parameters expecified for Atmosphere Effects of " - << name << " planet.\nDisabling atmosphere effects for this planet."); - } - - if (!errorReadingAtmosphereData) { - _atmosphereEnabled = true; - - //// DEBUG: - //std::stringstream ss; - //ss << "\n\nAtmosphere Values:\n" - // << "Radius: " << _atmosphereRadius << std::endl - // << "Planet Radius: " << _atmospherePlanetRadius << std::endl - // << "Average Reflection: " << _planetAverageGroundReflectance << std::endl - // << "Rayleigh HR: " << _rayleighHeightScale << std::endl - // << "Mie HR: " << _mieHeightScale << std::endl - // << "Mie G phase constant: " << _miePhaseConstant << std::endl - // << "Mie Extinction coeff: " << _mieExtinctionCoeff << std::endl - // << "Rayleigh Scattering coeff: " << _rayleighScatteringCoeff << std::endl - // << "Mie Scattering coeff: " << _mieScatteringCoeff << std::endl; - //std::cout << ss.str() << std::endl; - } - } -} - -RenderablePlanet::~RenderablePlanet() { -} - -bool RenderablePlanet::initialize() { - RenderEngine& renderEngine = OsEng.renderEngine(); - - GLenum err; - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Checking System State. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - if (_programObject == nullptr && _atmosphereEnabled && _shadowEnabled && _hasNightTexture) { - // shadow program - _programObject = renderEngine.buildRenderProgram( - "atmosphereAndShadowProgram", - "${MODULE_BASE}/shaders/atmosphere_vs.glsl", - "${MODULE_BASE}/shaders/atmosphere_fs.glsl"); - if (!_programObject) - return false; - } else if (_programObject == nullptr && _shadowEnabled && _hasNightTexture) { - // shadow program - _programObject = renderEngine.buildRenderProgram( - "shadowNightProgram", - "${MODULE_BASE}/shaders/shadow_nighttexture_vs.glsl", - "${MODULE_BASE}/shaders/shadow_nighttexture_fs.glsl"); - if (!_programObject) - return false; - } - else if (_programObject == nullptr && _shadowEnabled) { - // shadow program - _programObject = renderEngine.buildRenderProgram( - "shadowProgram", - "${MODULE_BASE}/shaders/shadow_vs.glsl", - "${MODULE_BASE}/shaders/shadow_fs.glsl"); - if (!_programObject) - return false; - } - else if (_programObject == nullptr && _hasNightTexture) { - // Night texture program - _programObject = renderEngine.buildRenderProgram( - "nightTextureProgram", - "${MODULE_BASE}/shaders/nighttexture_vs.glsl", - "${MODULE_BASE}/shaders/nighttexture_fs.glsl"); - if (!_programObject) - return false; - } - else if (_programObject == nullptr) { - // pscstandard - _programObject = renderEngine.buildRenderProgram( - "pscstandard", - "${MODULE_BASE}/shaders/pscstandard_vs.glsl", - "${MODULE_BASE}/shaders/pscstandard_fs.glsl"); - if (!_programObject) - return false; - } - using IgnoreError = ghoul::opengl::ProgramObject::IgnoreError; - _programObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); - _programObject->setIgnoreUniformLocationError(IgnoreError::Yes); - - /*_atmosphereProgramObject = renderEngine.buildRenderProgram( - "atmosphereDeferredProgram", - "${MODULE_BASE}/shaders/atmosphere_deferred_vs.glsl", - "${MODULE_BASE}/shaders/atmosphere_deferred_fs.glsl"); - if (!_atmosphereProgramObject) - return false;*/ - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error after load shading programs. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - loadTexture(); - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error loading textures. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - _geometry->initialize(this); - - _programObject->deactivate(); - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Shader Programs Creation. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - //Atmosphere precomputation and tables - if (_atmosphereEnabled && !_atmosphereCalculated) { - _atmosphereCalculated = true; - - preCalculateAtmosphereParam(); - - //createAtmosphereFBO(); - - createRenderQuad(&_atmosphereRenderVAO, &_atmosphereRenderVBO, 6); - } - - count = 0; - - return isReady(); -} - -bool RenderablePlanet::deinitialize() { - if(_geometry) { - _geometry->deinitialize(); - delete _geometry; - } - - RenderEngine& renderEngine = OsEng.renderEngine(); - if (_programObject) { - renderEngine.removeRenderProgram(_programObject); - _programObject = nullptr; - } - - if (_transmittanceProgramObject) { - renderEngine.removeRenderProgram(_transmittanceProgramObject); - _transmittanceProgramObject = nullptr; - } - - if (_irradianceProgramObject) { - renderEngine.removeRenderProgram(_irradianceProgramObject); - _irradianceProgramObject = nullptr; - } - - if (_irradianceSupTermsProgramObject) { - renderEngine.removeRenderProgram(_irradianceSupTermsProgramObject); - _irradianceSupTermsProgramObject = nullptr; - } - - if (_inScatteringProgramObject) { - renderEngine.removeRenderProgram(_inScatteringProgramObject); - _inScatteringProgramObject = nullptr; - } - - if (_inScatteringSupTermsProgramObject) { - renderEngine.removeRenderProgram(_inScatteringSupTermsProgramObject); - _inScatteringSupTermsProgramObject = nullptr; - } - - if (_deltaEProgramObject) { - renderEngine.removeRenderProgram(_deltaEProgramObject); - _deltaEProgramObject = nullptr; - } - - if (_deltaSProgramObject) { - renderEngine.removeRenderProgram(_deltaSProgramObject); - _deltaSProgramObject = nullptr; - } - - if (_deltaSSupTermsProgramObject) { - renderEngine.removeRenderProgram(_deltaSSupTermsProgramObject); - _deltaSSupTermsProgramObject = nullptr; - } - - if (_deltaJProgramObject) { - renderEngine.removeRenderProgram(_deltaJProgramObject); - _deltaJProgramObject = nullptr; - } - - _geometry = nullptr; - _texture = nullptr; - _nightTexture = nullptr; - _reflectanceTexture = nullptr; - _cloudsTexture = nullptr; - - glDeleteTextures(1, &_transmittanceTableTexture); - glDeleteTextures(1, &_irradianceTableTexture); - glDeleteTextures(1, &_inScatteringTableTexture); - glDeleteTextures(1, &_deltaETableTexture); - glDeleteTextures(1, &_deltaSRayleighTableTexture); - glDeleteTextures(1, &_deltaSMieTableTexture); - glDeleteTextures(1, &_deltaJTableTexture); - glDeleteTextures(1, &_atmosphereTexture); - - glDeleteFramebuffers(1, &_atmosphereFBO); - - return true; -} - -bool RenderablePlanet::isReady() const { - bool ready = true; - ready &= (_programObject != nullptr); - ready &= (_texture != nullptr); - ready &= (_geometry != nullptr); - return ready; -} - -void RenderablePlanet::render(const RenderData& data) { - // activate shader - _programObject->activate(); - - // scale the planet to appropriate size since the planet is a unit sphere - glm::mat4 transform = glm::mat4(1); - - //earth needs to be rotated for that to work. - glm::mat4 rot = glm::rotate(transform, static_cast(M_PI_2), glm::vec3(1, 0, 0)); - glm::mat4 roty = glm::rotate(transform, static_cast(M_PI_2), glm::vec3(0, -1, 0)); - glm::mat4 rotProp = glm::rotate(transform, glm::radians(static_cast(_rotation)), glm::vec3(0, 1, 0)); - - for (int i = 0; i < 3; i++){ - for (int j = 0; j < 3; j++){ - transform[i][j] = static_cast(_stateMatrix[i][j]); - } - } - transform = transform * rot * roty * rotProp; - - _programObject->setUniform("transparency", _alpha); - _programObject->setUniform("ViewProjection", data.camera.viewProjectionMatrix()); - _programObject->setUniform("ModelTransform", transform); - - // Normal Transformation - glm::mat4 translateObjTrans = glm::translate(glm::mat4(1.0), data.position.vec3()); - glm::mat4 translateCamTrans = glm::translate(glm::mat4(1.0), -data.camera.position().vec3()); - float scaleFactor = data.camera.scaling().x * powf(10.0, data.camera.scaling().y); - glm::mat4 scaleCamTrans = glm::scale(glm::mat4(1.0), glm::vec3(scaleFactor)); - - - glm::mat4 ModelViewTrans = data.camera.viewMatrix() * scaleCamTrans * - translateCamTrans * translateObjTrans * transform; - if (_atmosphereEnabled) - _programObject->setUniform("NormalTransform", - glm::transpose(glm::inverse(ModelViewTrans))); - - setPscUniforms(*_programObject.get(), data.camera, data.position); - - _programObject->setUniform("_performShading", _performShading); - - _programObject->setUniform("_hasHeightMap", _hasHeightTexture); - _programObject->setUniform("_heightExaggeration", _heightExaggeration); - - // Bind texture - ghoul::opengl::TextureUnit dayUnit; - ghoul::opengl::TextureUnit nightUnit; - ghoul::opengl::TextureUnit heightUnit; - - - dayUnit.activate(); - _texture->bind(); - _programObject->setUniform("texture1", dayUnit); - - // Bind possible night texture - if (_hasNightTexture) { - nightUnit.activate(); - _nightTexture->bind(); - _programObject->setUniform("nightTex", nightUnit); - } - - if (_hasHeightTexture) { - heightUnit.activate(); - _heightMapTexture->bind(); - _programObject->setUniform("heightTex", heightUnit); - } - - glEnable(GL_CULL_FACE); - glCullFace(GL_BACK); - - // TODO: Move Calculations to VIEW SPACE (precision problems avoidance...) - - double lt; - // Shadow calculations.. - if (!_shadowConfArray.empty()) { - std::vector shadowDataArray; - shadowDataArray.reserve(_shadowConfArray.size()); - - for (const auto & shadowConf : _shadowConfArray) { - // TO REMEMBER: all distances and lengths in world coordinates are in meters!!! We need to move this to view space... - // Getting source and caster: - glm::dvec3 sourcePos = SpiceManager::ref().targetPosition(shadowConf.source.first, "SUN", "GALACTIC", {}, _time, lt); - sourcePos *= 1000.0; // converting to meters - glm::dvec3 casterPos = SpiceManager::ref().targetPosition(shadowConf.caster.first, "SUN", "GALACTIC", {}, _time, lt); - casterPos *= 1000.0; // converting to meters - psc caster_pos = PowerScaledCoordinate::CreatePowerScaledCoordinate(casterPos.x, casterPos.y, casterPos.z); - - - // First we determine if the caster is shadowing the current planet (all calculations in World Coordinates): - glm::vec3 planetCasterVec = (caster_pos - data.position).vec3(); - glm::vec3 sourceCasterVec = glm::vec3(casterPos - sourcePos); - float sc_length = glm::length(sourceCasterVec); - glm::vec3 planetCaster_proj = (glm::dot(planetCasterVec, sourceCasterVec) / (sc_length*sc_length)) * sourceCasterVec; - float d_test = glm::length(planetCasterVec - planetCaster_proj); - float xp_test = shadowConf.caster.second * sc_length / (shadowConf.source.second + shadowConf.caster.second); - float rp_test = shadowConf.caster.second * (glm::length(planetCaster_proj) + xp_test) / xp_test; - - float casterDistSun = glm::length(casterPos); - float planetDistSun = glm::length(data.position.vec3()); - - ShadowRenderingStruct shadowData; - shadowData.isShadowing = false; - - if (((d_test - rp_test) < _planetRadius) && - (casterDistSun < planetDistSun) ) { - // The current caster is shadowing the current planet - shadowData.isShadowing = true; - shadowData.rs = shadowConf.source.second; - shadowData.rc = shadowConf.caster.second; - shadowData.sourceCasterVec = sourceCasterVec; - shadowData.xp = xp_test; - shadowData.xu = shadowData.rc * sc_length / (shadowData.rs - shadowData.rc); - shadowData.casterPositionVec = glm::vec3(casterPos); - } - shadowDataArray.push_back(shadowData); - } - - const std::string uniformVarName("shadowDataArray["); - unsigned int counter = 0; - for (const auto & sd : shadowDataArray) { - std::stringstream ss; - ss << uniformVarName << counter << "].isShadowing"; - _programObject->setUniform(ss.str(), sd.isShadowing); - if (sd.isShadowing) { - ss.str(std::string()); - ss << uniformVarName << counter << "].xp"; - _programObject->setUniform(ss.str(), sd.xp); - ss.str(std::string()); - ss << uniformVarName << counter << "].xu"; - _programObject->setUniform(ss.str(), sd.xu); - /*ss.str(std::string()); - ss << uniformVarName << counter << "].rs"; - _programObject->setUniform(ss.str(), sd.rs);*/ - ss.str(std::string()); - ss << uniformVarName << counter << "].rc"; - _programObject->setUniform(ss.str(), sd.rc); - ss.str(std::string()); - ss << uniformVarName << counter << "].sourceCasterVec"; - _programObject->setUniform(ss.str(), sd.sourceCasterVec); - ss.str(std::string()); - ss << uniformVarName << counter << "].casterPositionVec"; - _programObject->setUniform(ss.str(), sd.casterPositionVec); - } - counter++; - } - } - - // Atmosphere Data - if (_atmosphereEnabled) { - -// GLenum err; -// while ((err = glGetError()) != GL_NO_ERROR) { -// const GLubyte * errorString = gluErrorString(err); -// std::stringstream ss; -// ss << "Error setting up atmosphere framebuffer. OpenGL error: " -// << err << " - " << errorString << std::endl; -// LERROR(ss.str()); -// } - - // Object Space (in Km) - glm::mat4 obj2World = glm::translate(glm::mat4(1.0), data.position.vec3() / 1000.0f); - /*glm::mat4 M = data.camera.viewMatrix() * scaleCamTrans * glm::mat4(data.camera.viewRotationMatrix()) * - translateCamTrans * obj2World * transform; - */ - glm::mat4 M = glm::mat4(data.camera.combinedViewMatrix()) * scaleCamTrans * obj2World * transform; - - glm::mat4 completeInverse = glm::inverse(M); - - _programObject->setUniform("completeInverse", completeInverse); - _programObject->setUniform("projInverse", glm::inverse(data.camera.projectionMatrix())); - - // This is camera position and planet position vector in object coordinates, in Km. - glm::mat4 world2Obj = glm::inverse(obj2World * transform); - glm::vec4 cameraPosObj = world2Obj * glm::vec4(data.camera.position().vec3() / 1000.0f, 1.0); - glm::vec4 planetPositionObj = world2Obj * glm::vec4(data.position.vec3() / 1000.0f, 1.0); - _programObject->setUniform("cameraPosObj", cameraPosObj); - _programObject->setUniform("planetPositionObj", planetPositionObj); - - // I know it is (0,0,0). It is here just for sake of sanity. :-p - glm::dvec3 sunPosWorld = - SpiceManager::ref().targetPosition("SUN", "SUN", "GALACTIC", {}, _time, lt); - glm::vec4 sunPosObj = world2Obj * glm::vec4(sunPosWorld.x, sunPosWorld.y, sunPosWorld.z, 1.0); - _programObject->setUniform("sunPositionObj", glm::vec3(sunPosObj)); - - _transmittanceTableTextureUnit.activate(); - _programObject->setUniform("transmittanceTexture", _transmittanceTableTextureUnit); - - _irradianceTableTextureUnit.activate(); - _programObject->setUniform("irradianceTexture", _irradianceTableTextureUnit); - - _inScatteringTableTextureUnit.activate(); - _programObject->setUniform("inscatterTexture", _inScatteringTableTextureUnit); - - GLint m_viewport[4]; - glGetIntegerv(GL_VIEWPORT, m_viewport); - _programObject->setUniform("screenX", (float)m_viewport[0]); - _programObject->setUniform("screenY", (float)m_viewport[1]); - _programObject->setUniform("screenWIDTH", (float)m_viewport[2]); - _programObject->setUniform("screenHEIGHT", (float)m_viewport[3]); - - - _programObject->setUniform("Rg", _atmospherePlanetRadius); - _programObject->setUniform("Rt", _atmosphereRadius); - _programObject->setUniform("AVERAGE_GROUND_REFLECTANCE", _planetAverageGroundReflectance); - _programObject->setUniform("HR", _rayleighHeightScale); - _programObject->setUniform("betaR", _rayleighScatteringCoeff); - _programObject->setUniform("HM", _mieHeightScale); - _programObject->setUniform("betaMSca", _mieScatteringCoeff); - _programObject->setUniform("betaMEx", _mieExtinctionCoeff); - _programObject->setUniform("mieG", _miePhaseConstant); - - - ghoul::opengl::TextureUnit reflectanceUnit; - if (_hasReflectanceTexture) { - reflectanceUnit.activate(); - _reflectanceTexture->bind(); - _programObject->setUniform("reflectanceTexture", reflectanceUnit); - } - - ghoul::opengl::TextureUnit cloudsUnit; - if (_hasCloudsTexture) { - cloudsUnit.activate(); - _cloudsTexture->bind(); - _programObject->setUniform("cloudsTexture", cloudsUnit); - } - - // HDR - _programObject->setUniform("exposure", 0.4f); - - } - - - // render - _geometry->render(); - - // disable shader - _programObject->deactivate(); - -} - -void RenderablePlanet::update(const UpdateData& data) { - // set spice-orientation in accordance to timestamp - _stateMatrix = SpiceManager::ref().positionTransformMatrix(_frame, "GALACTIC", data.time); - _time = data.time; -} - -void RenderablePlanet::loadTexture() { - _texture = nullptr; - if (_colorTexturePath.value() != "") { - _texture = std::move(ghoul::io::TextureReader::ref().loadTexture(absPath(_colorTexturePath))); - if (_texture) { - LDEBUG("Loaded texture from '" << _colorTexturePath << "'"); - _texture->uploadTexture(); - - // Textures of planets looks much smoother with AnisotropicMipMap rather than linear - // TODO: AnisotropicMipMap crashes on ATI cards ---abock - //_texture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); - _texture->setFilter(ghoul::opengl::Texture::FilterMode::Linear); - } - } - - GLenum err; - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error after reading memory 1. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - if (_hasNightTexture) { - _nightTexture = nullptr; - if (_nightTexturePath.value() != "") { - _nightTexture = std::move(ghoul::io::TextureReader::ref().loadTexture(absPath(_nightTexturePath))); - if (_nightTexture) { - LDEBUG("Loaded texture from '" << _nightTexturePath << "'"); - _nightTexture->uploadTexture(); - _nightTexture->setFilter(ghoul::opengl::Texture::FilterMode::Linear); - //_nightTexture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); - } - } - } - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error after reading memory 2. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - if (_hasReflectanceTexture) { - _reflectanceTexture = nullptr; - if (_reflectanceTexturePath.value() != "") { - _reflectanceTexture = std::move(ghoul::io::TextureReader::ref().loadTexture(absPath(_reflectanceTexturePath))); - if (_reflectanceTexture) { - LDEBUG("Loaded texture from '" << _reflectanceTexturePath << "'"); - _reflectanceTexture->uploadTexture(); - _reflectanceTexture->setFilter(ghoul::opengl::Texture::FilterMode::Linear); - //_reflectanceTexture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); - } - } - } - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error after reading memory 3. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - if (_hasHeightTexture) { - _heightMapTexture = nullptr; - if (_heightMapTexturePath.value() != "") { - _heightMapTexture = std::move(ghoul::io::TextureReader::ref().loadTexture(absPath(_heightMapTexturePath))); - if (_heightMapTexture) { - LDEBUG("Loaded texture from '" << _heightMapTexturePath << "'"); - _heightMapTexture->uploadTexture(); - _heightMapTexture->setFilter(ghoul::opengl::Texture::FilterMode::Linear); - //_nightTexture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); - } - } - } - -// while ((err = glGetError()) != GL_NO_ERROR) { -// const GLubyte * errString = gluErrorString(err); -// std::stringstream ss; -// ss << "Error after reading memory 4. OpenGL error: " << errString << std::endl; -// LERROR(ss.str()); -// } - - if (_hasCloudsTexture) { - _cloudsTexture = nullptr; - if (_cloudsTexturePath.value() != "") { - _cloudsTexture = std::move(ghoul::io::TextureReader::ref().loadTexture(absPath(_cloudsTexturePath))); - if (_cloudsTexture) { - LDEBUG("Loaded texture from '" << _cloudsTexturePath << "'"); - _cloudsTexture->uploadTexture(); - _cloudsTexture->setFilter(ghoul::opengl::Texture::FilterMode::Linear); - //_cloudsTexture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); - } - } - } - -// while ((err = glGetError()) != GL_NO_ERROR) { -// const GLubyte * errString = gluErrorString(err); -// std::stringstream ss; -// ss << "Error after reading memory 5. OpenGL error: " << errString << std::endl; -// LERROR(ss.str()); -// } -} - -void RenderablePlanet::loadComputationPrograms() { - - RenderEngine& renderEngine = OsEng.renderEngine(); - - //============== Transmittance ================= - if (_transmittanceProgramObject == nullptr) { - _transmittanceProgramObject = renderEngine.buildRenderProgram( - "transmittanceCalcProgram", - "${MODULE_BASE}/shaders/transmittance_calc_vs.glsl", - "${MODULE_BASE}/shaders/transmittance_calc_fs.glsl"); - if (!_transmittanceProgramObject) { - return; - } - } - using IgnoreError = ghoul::opengl::ProgramObject::IgnoreError; - _transmittanceProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); - _transmittanceProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - - //============== Irradiance ================= - if (_irradianceProgramObject == nullptr) { - _irradianceProgramObject = renderEngine.buildRenderProgram( - "irradianceCalcProgram", - "${MODULE_BASE}/shaders/irradiance_calc_vs.glsl", - "${MODULE_BASE}/shaders/irradiance_calc_fs.glsl"); - if (!_irradianceProgramObject) { - if (_transmittanceProgramObject) { - renderEngine.removeRenderProgram(_transmittanceProgramObject); - _transmittanceProgramObject = nullptr; - } - - return; - } - } - _irradianceProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); - _irradianceProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - - if (_irradianceSupTermsProgramObject == nullptr) { - _irradianceSupTermsProgramObject = renderEngine.buildRenderProgram( - "irradianceSupTermsCalcProgram", - "${MODULE_BASE}/shaders/irradiance_sup_calc_vs.glsl", - "${MODULE_BASE}/shaders/irradiance_sup_calc_fs.glsl"); - if (!_irradianceSupTermsProgramObject) { - if (_transmittanceProgramObject) { - renderEngine.removeRenderProgram(_transmittanceProgramObject); - _transmittanceProgramObject = nullptr; - } - - if (_irradianceProgramObject) { - renderEngine.removeRenderProgram(_irradianceProgramObject); - _irradianceProgramObject = nullptr; - } - - return; - } - } - _irradianceSupTermsProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); - _irradianceSupTermsProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - - //============== InScattering ================= - if (_inScatteringProgramObject == nullptr) { - _inScatteringProgramObject = renderEngine.buildRenderProgram( - "inScatteringCalcProgram", - "${MODULE_BASE}/shaders/inScattering_calc_vs.glsl", - "${MODULE_BASE}/shaders/inScattering_calc_fs.glsl", - "${MODULE_BASE}/shaders/inScattering_calc_gs.glsl"); - if (!_inScatteringProgramObject) { - if (_transmittanceProgramObject) { - renderEngine.removeRenderProgram(_transmittanceProgramObject); - _transmittanceProgramObject = nullptr; - } - - if (_irradianceProgramObject) { - renderEngine.removeRenderProgram(_irradianceProgramObject); - _irradianceProgramObject = nullptr; - } - - if (_irradianceSupTermsProgramObject) { - renderEngine.removeRenderProgram(_irradianceSupTermsProgramObject); - _irradianceSupTermsProgramObject = nullptr; - } - - return; - } - } - _inScatteringProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); - _inScatteringProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - - if (_inScatteringSupTermsProgramObject == nullptr) { - _inScatteringSupTermsProgramObject = renderEngine.buildRenderProgram( - "inScatteringSupTermsCalcProgram", - "${MODULE_BASE}/shaders/inScattering_sup_calc_vs.glsl", - "${MODULE_BASE}/shaders/inScattering_sup_calc_fs.glsl", - "${MODULE_BASE}/shaders/inScattering_sup_calc_gs.glsl"); - if (!_inScatteringSupTermsProgramObject) { - if (_transmittanceProgramObject) { - renderEngine.removeRenderProgram(_transmittanceProgramObject); - _transmittanceProgramObject = nullptr; - } - - if (_irradianceProgramObject) { - renderEngine.removeRenderProgram(_irradianceProgramObject); - _irradianceProgramObject = nullptr; - } - - if (_irradianceSupTermsProgramObject) { - renderEngine.removeRenderProgram(_irradianceSupTermsProgramObject); - _irradianceSupTermsProgramObject = nullptr; - } - - if (_inScatteringProgramObject) { - renderEngine.removeRenderProgram(_inScatteringProgramObject); - _inScatteringProgramObject = nullptr; - } - - return; - } - } - _inScatteringSupTermsProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); - _inScatteringSupTermsProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - - //============== Delta E ================= - if (_deltaEProgramObject == nullptr) { - _deltaEProgramObject = renderEngine.buildRenderProgram( - "deltaECalcProgram", - "${MODULE_BASE}/shaders/deltaE_calc_vs.glsl", - "${MODULE_BASE}/shaders/deltaE_calc_fs.glsl"); - if (!_deltaEProgramObject) { - if (_transmittanceProgramObject) { - renderEngine.removeRenderProgram(_transmittanceProgramObject); - _transmittanceProgramObject = nullptr; - } - - if (_irradianceProgramObject) { - renderEngine.removeRenderProgram(_irradianceProgramObject); - _irradianceProgramObject = nullptr; - } - - if (_irradianceSupTermsProgramObject) { - renderEngine.removeRenderProgram(_irradianceSupTermsProgramObject); - _irradianceSupTermsProgramObject = nullptr; - } - - if (_inScatteringProgramObject) { - renderEngine.removeRenderProgram(_inScatteringProgramObject); - _inScatteringProgramObject = nullptr; - } - - if (_inScatteringSupTermsProgramObject) { - renderEngine.removeRenderProgram(_inScatteringSupTermsProgramObject); - _inScatteringSupTermsProgramObject = nullptr; - } - - return; - } - } - _deltaEProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); - _deltaEProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - - //============== Delta S ================= - if (_deltaSProgramObject == nullptr) { - _deltaSProgramObject = renderEngine.buildRenderProgram( - "deltaSCalcProgram", - "${MODULE_BASE}/shaders/deltaS_calc_vs.glsl", - "${MODULE_BASE}/shaders/deltaS_calc_fs.glsl", - "${MODULE_BASE}/shaders/deltaS_calc_gs.glsl"); - if (!_deltaSProgramObject) { - if (_transmittanceProgramObject) { - renderEngine.removeRenderProgram(_transmittanceProgramObject); - _transmittanceProgramObject = nullptr; - } - - if (_irradianceProgramObject) { - renderEngine.removeRenderProgram(_irradianceProgramObject); - _irradianceProgramObject = nullptr; - } - - if (_irradianceSupTermsProgramObject) { - renderEngine.removeRenderProgram(_irradianceSupTermsProgramObject); - _irradianceSupTermsProgramObject = nullptr; - } - - if (_inScatteringProgramObject) { - renderEngine.removeRenderProgram(_inScatteringProgramObject); - _inScatteringProgramObject = nullptr; - } - - if (_inScatteringSupTermsProgramObject) { - renderEngine.removeRenderProgram(_inScatteringSupTermsProgramObject); - _inScatteringSupTermsProgramObject = nullptr; - } - - if (_deltaEProgramObject) { - renderEngine.removeRenderProgram(_deltaEProgramObject); - _deltaEProgramObject = nullptr; - } - - return; - } - } - _deltaSProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); - _deltaSProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - - if (_deltaSSupTermsProgramObject == nullptr) { - _deltaSSupTermsProgramObject = renderEngine.buildRenderProgram( - "deltaSSUPTermsCalcProgram", - "${MODULE_BASE}/shaders/deltaS_sup_calc_vs.glsl", - "${MODULE_BASE}/shaders/deltaS_sup_calc_fs.glsl", - "${MODULE_BASE}/shaders/deltaS_sup_calc_gs.glsl"); - if (!_deltaSSupTermsProgramObject) { - if (_transmittanceProgramObject) { - renderEngine.removeRenderProgram(_transmittanceProgramObject); - _transmittanceProgramObject = nullptr; - } - - if (_irradianceProgramObject) { - renderEngine.removeRenderProgram(_irradianceProgramObject); - _irradianceProgramObject = nullptr; - } - - if (_irradianceSupTermsProgramObject) { - renderEngine.removeRenderProgram(_irradianceSupTermsProgramObject); - _irradianceSupTermsProgramObject = nullptr; - } - - if (_inScatteringProgramObject) { - renderEngine.removeRenderProgram(_inScatteringProgramObject); - _inScatteringProgramObject = nullptr; - } - - if (_inScatteringSupTermsProgramObject) { - renderEngine.removeRenderProgram(_inScatteringSupTermsProgramObject); - _inScatteringSupTermsProgramObject = nullptr; - } - - if (_deltaEProgramObject) { - renderEngine.removeRenderProgram(_deltaEProgramObject); - _deltaEProgramObject = nullptr; - } - - if (_deltaSProgramObject) { - renderEngine.removeRenderProgram(_deltaSProgramObject); - _deltaSProgramObject = nullptr; - } - - return; - } - } - _deltaSSupTermsProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); - _deltaSSupTermsProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - - //============== Delta J (Radiance Scattered) ================= - if (_deltaJProgramObject == nullptr) { - // shadow program - _deltaJProgramObject = renderEngine.buildRenderProgram( - "deltaJCalcProgram", - "${MODULE_BASE}/shaders/deltaJ_calc_vs.glsl", - "${MODULE_BASE}/shaders/deltaJ_calc_fs.glsl", - "${MODULE_BASE}/shaders/deltaJ_calc_gs.glsl"); - if (!_deltaJProgramObject) { - if (_transmittanceProgramObject) { - renderEngine.removeRenderProgram(_transmittanceProgramObject); - _transmittanceProgramObject = nullptr; - } - - if (_irradianceProgramObject) { - renderEngine.removeRenderProgram(_irradianceProgramObject); - _irradianceProgramObject = nullptr; - } - - if (_irradianceSupTermsProgramObject) { - renderEngine.removeRenderProgram(_irradianceSupTermsProgramObject); - _irradianceSupTermsProgramObject = nullptr; - } - - if (_inScatteringProgramObject) { - renderEngine.removeRenderProgram(_inScatteringProgramObject); - _inScatteringProgramObject = nullptr; - } - - if (_inScatteringSupTermsProgramObject) { - renderEngine.removeRenderProgram(_inScatteringSupTermsProgramObject); - _inScatteringSupTermsProgramObject = nullptr; - } - - if (_deltaEProgramObject) { - renderEngine.removeRenderProgram(_deltaEProgramObject); - _deltaEProgramObject = nullptr; - } - - if (_deltaSProgramObject) { - renderEngine.removeRenderProgram(_deltaSProgramObject); - _deltaSProgramObject = nullptr; - } - - if (_deltaSSupTermsProgramObject) { - renderEngine.removeRenderProgram(_deltaSSupTermsProgramObject); - _deltaSSupTermsProgramObject = nullptr; - } - - return; - } - - } - _deltaJProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); - _deltaJProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); -} - -void RenderablePlanet::unloadComputationPrograms() { - - RenderEngine& renderEngine = OsEng.renderEngine(); - - if (_transmittanceProgramObject) { - renderEngine.removeRenderProgram(_transmittanceProgramObject); - _transmittanceProgramObject = nullptr; - } - - if (_irradianceProgramObject) { - renderEngine.removeRenderProgram(_irradianceProgramObject); - _irradianceProgramObject = nullptr; - } - - if (_irradianceSupTermsProgramObject) { - renderEngine.removeRenderProgram(_irradianceSupTermsProgramObject); - _irradianceSupTermsProgramObject = nullptr; - } - - if (_inScatteringProgramObject) { - renderEngine.removeRenderProgram(_inScatteringProgramObject); - _inScatteringProgramObject = nullptr; - } - - if (_inScatteringSupTermsProgramObject) { - renderEngine.removeRenderProgram(_inScatteringSupTermsProgramObject); - _inScatteringSupTermsProgramObject = nullptr; - } - - if (_deltaEProgramObject) { - renderEngine.removeRenderProgram(_deltaEProgramObject); - _deltaEProgramObject = nullptr; - } - - if (_deltaSProgramObject) { - renderEngine.removeRenderProgram(_deltaSProgramObject); - _deltaSProgramObject = nullptr; - } - - if (_deltaSSupTermsProgramObject) { - renderEngine.removeRenderProgram(_deltaSSupTermsProgramObject); - _deltaSSupTermsProgramObject = nullptr; - } - - if (_deltaJProgramObject) { - renderEngine.removeRenderProgram(_deltaJProgramObject); - _deltaJProgramObject = nullptr; - } -} - -void RenderablePlanet::createComputationTextures() { - // TODO: Change precision of textures: GL_RGB16F to GL_RGB32F - //========== Create Tables (textures) ============== - - GLenum err; - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error before creating OpenGL textures for Atmosphere computation. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - _dummyTextureUnit.activate(); - glGenTextures(1, &_dummyTexture); - glBindTexture(GL_TEXTURE_2D, _dummyTexture); - glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, TRANSMITTANCE_TABLE_WIDTH, - TRANSMITTANCE_TABLE_HEIGHT, 0, GL_RGB, GL_FLOAT, nullptr); - - //GLenum err; - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error 1 creating OpenGL textures for Atmosphere computation. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - ghoul::opengl::TextureUnit _dummy3DTextureUnit; - _dummy3DTextureUnit.activate(); - glGenTextures(1, &_dummy3DTexture); - glBindTexture(GL_TEXTURE_3D, _dummy3DTexture); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); - glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB16F, MU_S_SAMPLES * NU_SAMPLES, - MU_SAMPLES, R_SAMPLES, 0, GL_RGB, GL_FLOAT, nullptr); - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error 2 creating OpenGL textures for Atmosphere computation. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - //============== Transmittance ================= - _transmittanceTableTextureUnit.activate(); - glGenTextures(1, &_transmittanceTableTexture); - glBindTexture(GL_TEXTURE_2D, _transmittanceTableTexture); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, TRANSMITTANCE_TABLE_WIDTH, - TRANSMITTANCE_TABLE_HEIGHT, 0, GL_RGB, GL_FLOAT, nullptr); - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error 3 creating OpenGL textures for Atmosphere computation. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - //============== Irradiance ================= - _irradianceTableTextureUnit.activate(); - glGenTextures(1, &_irradianceTableTexture); - glBindTexture(GL_TEXTURE_2D, _irradianceTableTexture); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, IRRADIANCE_TABLE_WIDTH, - IRRADIANCE_TABLE_HEIGHT, 0, GL_RGB, GL_FLOAT, nullptr); - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error 4 creating OpenGL textures for Atmosphere computation. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - //============== InScattering ================= - _inScatteringTableTextureUnit.activate(); - glGenTextures(1, &_inScatteringTableTexture); - glBindTexture(GL_TEXTURE_3D, _inScatteringTableTexture); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); - glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA16F_ARB, MU_S_SAMPLES * NU_SAMPLES, - MU_SAMPLES, R_SAMPLES, 0, GL_RGB, GL_FLOAT, nullptr); - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error 5 creating OpenGL textures for Atmosphere computation. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - //============== Delta E ================= - _deltaETableTextureUnit.activate(); - glGenTextures(1, &_deltaETableTexture); - glBindTexture(GL_TEXTURE_2D, _deltaETableTexture); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, DELTA_E_TABLE_WIDTH, - DELTA_E_TABLE_HEIGHT, 0, GL_RGB, GL_FLOAT, nullptr); - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error 6 creating OpenGL textures for Atmosphere computation. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - //============== Delta S ================= - _deltaSRayleighTableTextureUnit.activate(); - glGenTextures(1, &_deltaSRayleighTableTexture); - glBindTexture(GL_TEXTURE_3D, _deltaSRayleighTableTexture); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); - glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB16F, MU_S_SAMPLES * NU_SAMPLES, - MU_SAMPLES, R_SAMPLES, 0, GL_RGB, GL_FLOAT, nullptr); - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error 7 creating OpenGL textures for Atmosphere computation. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - _deltaSMieTableTextureUnit.activate(); - glGenTextures(1, &_deltaSMieTableTexture); - glBindTexture(GL_TEXTURE_3D, _deltaSMieTableTexture); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); - glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB16F, MU_S_SAMPLES * NU_SAMPLES, - MU_SAMPLES, R_SAMPLES, 0, GL_RGB, GL_FLOAT, nullptr); - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error 8 creating OpenGL textures for Atmosphere computation. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - //============== Delta J (Radiance Scattered) ================= - _deltaJTableTextureUnit.activate(); - glGenTextures(1, &_deltaJTableTexture); - glBindTexture(GL_TEXTURE_3D, _deltaJTableTexture); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); - glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB16F, MU_S_SAMPLES * NU_SAMPLES, - MU_SAMPLES, R_SAMPLES, 0, GL_RGB, GL_FLOAT, nullptr); - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error 9 creating OpenGL textures for Atmosphere computation. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } -} - -void RenderablePlanet::deleteComputationTextures() { - // Cleaning up - glDeleteTextures(1, &_dummyTexture); - glDeleteTextures(1, &_dummy3DTexture); - glDeleteTextures(1, &_transmittanceTableTexture); - glDeleteTextures(1, &_irradianceTableTexture); - glDeleteTextures(1, &_inScatteringTableTexture); - glDeleteTextures(1, &_deltaETableTexture); - glDeleteTextures(1, &_deltaSRayleighTableTexture); - glDeleteTextures(1, &_deltaSMieTableTexture); - glDeleteTextures(1, &_deltaJTableTexture); -} - -void RenderablePlanet::deleteUnusedComputationTextures() { - glDeleteTextures(1, &_dummyTexture); - glDeleteTextures(1, &_dummy3DTexture); - glDeleteTextures(1, &_deltaETableTexture); - glDeleteTextures(1, &_deltaSRayleighTableTexture); - glDeleteTextures(1, &_deltaSMieTableTexture); - glDeleteTextures(1, &_deltaJTableTexture); -} - -void RenderablePlanet::loadAtmosphereDataIntoShaderProgram(std::unique_ptr & shaderProg) { - shaderProg->setUniform("Rg", _atmospherePlanetRadius); - shaderProg->setUniform("Rt", _atmosphereRadius); - shaderProg->setUniform("AVERAGE_GROUND_REFLECTANCE", _planetAverageGroundReflectance); - shaderProg->setUniform("HR", _rayleighHeightScale); - shaderProg->setUniform("betaR", _rayleighScatteringCoeff); - shaderProg->setUniform("HM", _mieHeightScale); - shaderProg->setUniform("betaMSca", _mieScatteringCoeff); - shaderProg->setUniform("betaMEx", _mieExtinctionCoeff); - shaderProg->setUniform("mieG", _miePhaseConstant); -} - - -void RenderablePlanet::executeCalculations(const GLuint vao, const GLenum drawBuffers[2], const GLsizei vertexSize) { - // =========================================================== - // See Precomputed Atmosphere Scattering from Bruneton et al. paper, algorithm 4.1: - // =========================================================== - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _dummyTexture, 0); - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, _transmittanceTableTexture, 0); - if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) - LERROR("Computation Framework not built."); - glViewport(0, 0, TRANSMITTANCE_TABLE_WIDTH, TRANSMITTANCE_TABLE_HEIGHT); - _transmittanceProgramObject->activate(); - loadAtmosphereDataIntoShaderProgram(_transmittanceProgramObject); - renderQuadForCalc(vao, vertexSize); - /*saveTextureToPPMFile(GL_COLOR_ATTACHMENT1, std::string("transmittance_texture.ppm"), - TRANSMITTANCE_TABLE_WIDTH, TRANSMITTANCE_TABLE_HEIGHT);*/ - - GLenum err; - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error executing computation 1. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - // line 2 in algorithm 4.1 - glBindTexture(GL_TEXTURE_2D, _dummyTexture); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, - DELTA_E_TABLE_WIDTH, DELTA_E_TABLE_HEIGHT, 0, - GL_RGB, GL_FLOAT, nullptr); - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _dummyTexture, 0); - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, _deltaETableTexture, 0); - if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) - LERROR("Computation Framework not built."); - glViewport(0, 0, DELTA_E_TABLE_WIDTH, DELTA_E_TABLE_HEIGHT); - _irradianceProgramObject->activate(); - _irradianceProgramObject->setUniform("transmittanceTexture", _transmittanceTableTextureUnit); - loadAtmosphereDataIntoShaderProgram(_irradianceProgramObject); - renderQuadForCalc(vao, vertexSize); - /*saveTextureToPPMFile(GL_COLOR_ATTACHMENT1, std::string("deltaE_table_texture.ppm"), - DELTA_E_TABLE_WIDTH, DELTA_E_TABLE_HEIGHT);*/ - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error executing computation 2. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - // line 3 in algorithm 4.1 - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _dummy3DTexture, 0); - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, _deltaSRayleighTableTexture, 0); - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, _deltaSMieTableTexture, 0); - GLenum colorBuffers[3] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 }; - glDrawBuffers(3, colorBuffers); - if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) - LERROR("Computation Framework not built."); - glViewport(0, 0, MU_S_SAMPLES * NU_SAMPLES, MU_SAMPLES); - _inScatteringProgramObject->activate(); - _inScatteringProgramObject->setUniform("transmittanceTexture", _transmittanceTableTextureUnit); - loadAtmosphereDataIntoShaderProgram(_inScatteringProgramObject); - for (int layer = 0; layer < R_SAMPLES; ++layer) { - step3DTexture(_inScatteringProgramObject, layer); - renderQuadForCalc(vao, vertexSize); - } - /*saveTextureToPPMFile(GL_COLOR_ATTACHMENT1, std::string("deltaS_rayleigh_texture.ppm"), - MU_S_SAMPLES * NU_SAMPLES, MU_SAMPLES); - saveTextureToPPMFile(GL_COLOR_ATTACHMENT2, std::string("deltaS_mie_texture.ppm"), - MU_S_SAMPLES * NU_SAMPLES, MU_SAMPLES);*/ - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, 0, 0); - glDrawBuffers(2, drawBuffers); - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error executing computation 3. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - // line 4 in algorithm 4.1 - glBindTexture(GL_TEXTURE_2D, _dummyTexture); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, - DELTA_E_TABLE_WIDTH, DELTA_E_TABLE_HEIGHT, 0, - GL_RGB, GL_FLOAT, nullptr); - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _dummyTexture, 0); - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, _irradianceTableTexture, 0); - glDrawBuffers(2, drawBuffers); - if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) - LERROR("Computation Framework not built."); - glViewport(0, 0, DELTA_E_TABLE_WIDTH, DELTA_E_TABLE_HEIGHT); - _deltaEProgramObject->activate(); - _deltaEProgramObject->setUniform("line", 4); - _deltaEProgramObject->setUniform("deltaETexture", _deltaETableTextureUnit); - loadAtmosphereDataIntoShaderProgram(_deltaEProgramObject); - renderQuadForCalc(vao, vertexSize); - /*saveTextureToPPMFile(GL_COLOR_ATTACHMENT1, std::string("irradiance_texture.ppm"), - DELTA_E_TABLE_WIDTH, DELTA_E_TABLE_HEIGHT);*/ - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error executing computation 4. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - // line 5 in algorithm 4.1 - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _dummy3DTexture, 0); - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, _inScatteringTableTexture, 0); - glViewport(0, 0, MU_S_SAMPLES * NU_SAMPLES, MU_SAMPLES); - _deltaSProgramObject->activate(); - _deltaSProgramObject->setUniform("deltaSRTexture", _deltaSRayleighTableTextureUnit); - _deltaSProgramObject->setUniform("deltaSMTexture", _deltaSMieTableTextureUnit); - loadAtmosphereDataIntoShaderProgram(_deltaSProgramObject); - for (int layer = 0; layer < R_SAMPLES; ++layer) { - step3DTexture(_deltaSProgramObject, layer, false); - renderQuadForCalc(vao, vertexSize); - } - /*saveTextureToPPMFile(GL_COLOR_ATTACHMENT1, std::string("S_texture.ppm"), - MU_S_SAMPLES * NU_SAMPLES, MU_SAMPLES);*/ - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error executing computation 5. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - // loop in line 6 in algorithm 4.1 - for (int scatteringOrder = 2; scatteringOrder <= 4; ++scatteringOrder) { - - // line 7 in algorithm 4.1 - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _dummy3DTexture, 0); - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, _deltaJTableTexture, 0); - if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) - LERROR("Computation Framework not built."); - glViewport(0, 0, MU_S_SAMPLES * NU_SAMPLES, MU_SAMPLES); - _deltaJProgramObject->activate(); - if (scatteringOrder == 2) - _deltaJProgramObject->setUniform("first", 1.0f); - else - _deltaJProgramObject->setUniform("first", 0.0f); - _deltaJProgramObject->setUniform("transmittanceTexture", _transmittanceTableTextureUnit); - _deltaJProgramObject->setUniform("deltaETexture", _deltaETableTextureUnit); - _deltaJProgramObject->setUniform("deltaSRTexture", _deltaSRayleighTableTextureUnit); - _deltaJProgramObject->setUniform("deltaSMTexture", _deltaSMieTableTextureUnit); - loadAtmosphereDataIntoShaderProgram(_deltaJProgramObject); - for (int layer = 0; layer < R_SAMPLES; ++layer) { - step3DTexture(_deltaJProgramObject, layer); - renderQuadForCalc(vao, vertexSize); - } - /*std::stringstream sst; - sst << "deltaJ_texture-scattering_order-" << scatteringOrder << ".ppm"; - saveTextureToPPMFile(GL_COLOR_ATTACHMENT1, sst.str(), - MU_S_SAMPLES * NU_SAMPLES, MU_SAMPLES);*/ - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error executing computation 6. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - // line 8 in algorithm 4.1 - glBindTexture(GL_TEXTURE_2D, _dummyTexture); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, - DELTA_E_TABLE_WIDTH, DELTA_E_TABLE_HEIGHT, 0, - GL_RGB, GL_FLOAT, nullptr); - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _dummyTexture, 0); - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, _deltaETableTexture, 0); - if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) - LERROR("Computation Framework not built."); - glViewport(0, 0, DELTA_E_TABLE_WIDTH, DELTA_E_TABLE_HEIGHT); - _irradianceSupTermsProgramObject->activate(); - if (scatteringOrder == 2) - _irradianceSupTermsProgramObject->setUniform("first", 1.0f); - else - _irradianceSupTermsProgramObject->setUniform("first", 0.0f); - _irradianceSupTermsProgramObject->setUniform("transmittanceTexture", _transmittanceTableTextureUnit); - _irradianceSupTermsProgramObject->setUniform("deltaSRTexture", _deltaSRayleighTableTextureUnit); - _irradianceSupTermsProgramObject->setUniform("deltaSMTexture", _deltaSMieTableTextureUnit); - loadAtmosphereDataIntoShaderProgram(_irradianceSupTermsProgramObject); - renderQuadForCalc(vao, vertexSize); - /*sst.str(std::string()); - sst << "deltaE_texture-scattering_order-" << scatteringOrder << ".ppm"; - saveTextureToPPMFile(GL_COLOR_ATTACHMENT1, sst.str(), - DELTA_E_TABLE_WIDTH, DELTA_E_TABLE_HEIGHT);*/ - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error executing computation 7. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - // line 9 in algorithm 4.1 - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _dummy3DTexture, 0); - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, _deltaSRayleighTableTexture, 0); - if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) - LERROR("Computation Framework not built."); - glViewport(0, 0, MU_S_SAMPLES * NU_SAMPLES, MU_SAMPLES); - _inScatteringSupTermsProgramObject->activate(); - if (scatteringOrder == 2) - _inScatteringSupTermsProgramObject->setUniform("first", 1.0f); - else - _inScatteringSupTermsProgramObject->setUniform("first", 0.0f); - _inScatteringSupTermsProgramObject->setUniform("transmittanceTexture", _transmittanceTableTextureUnit); - _inScatteringSupTermsProgramObject->setUniform("deltaJTexture", _deltaJTableTextureUnit); - loadAtmosphereDataIntoShaderProgram(_inScatteringSupTermsProgramObject); - for (int layer = 0; layer < R_SAMPLES; ++layer) { - step3DTexture(_inScatteringSupTermsProgramObject, layer); - renderQuadForCalc(vao, vertexSize); - } - /*sst.str(std::string()); - sst << "deltaS_texture-scattering_order-" << scatteringOrder << ".ppm"; - saveTextureToPPMFile(GL_COLOR_ATTACHMENT1, sst.str(), - MU_S_SAMPLES * NU_SAMPLES, MU_SAMPLES);*/ - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error executing computation 8. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - glEnable(GL_BLEND); - glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD); - glBlendFuncSeparate(GL_ONE, GL_ONE, GL_ONE, GL_ONE); - - // line 10 in algorithm 4.1 - glBindTexture(GL_TEXTURE_2D, _dummyTexture); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, - DELTA_E_TABLE_WIDTH, DELTA_E_TABLE_HEIGHT, 0, - GL_RGB, GL_FLOAT, nullptr); - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _dummyTexture, 0); - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, _irradianceTableTexture, 0); - if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) - LERROR("Computation Framework not built."); - glViewport(0, 0, DELTA_E_TABLE_WIDTH, DELTA_E_TABLE_HEIGHT); - _deltaEProgramObject->activate(); - _deltaEProgramObject->setUniform("line", 10); - _deltaEProgramObject->setUniform("deltaETexture", _deltaETableTextureUnit); - loadAtmosphereDataIntoShaderProgram(_deltaEProgramObject); - renderQuadForCalc(vao, vertexSize); - /*sst.str(std::string()); - sst << "irradianceTable_order-" << scatteringOrder << ".ppm"; - saveTextureToPPMFile(GL_COLOR_ATTACHMENT1, sst.str(), - DELTA_E_TABLE_WIDTH, DELTA_E_TABLE_HEIGHT);*/ - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error executing computation 9. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - // line 11 in algorithm 4.1 - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _dummy3DTexture, 0); - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, _inScatteringTableTexture, 0); - if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) - LERROR("Computation Framework not built."); - glViewport(0, 0, MU_S_SAMPLES * NU_SAMPLES, MU_SAMPLES); - _deltaSSupTermsProgramObject->activate(); - _deltaSSupTermsProgramObject->setUniform("deltaSTexture", _deltaSRayleighTableTextureUnit); - loadAtmosphereDataIntoShaderProgram(_deltaSSupTermsProgramObject); - for (int layer = 0; layer < R_SAMPLES; ++layer) { - step3DTexture(_deltaSSupTermsProgramObject, layer, false); - renderQuadForCalc(vao, vertexSize); - } - /*sst.str(std::string()); - sst << "inscatteringTable_order-" << scatteringOrder << ".ppm"; - saveTextureToPPMFile(GL_COLOR_ATTACHMENT1, sst.str(), - MU_S_SAMPLES * NU_SAMPLES, MU_SAMPLES);*/ - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error executing computation 10. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - glDisable(GL_BLEND); - } - -} - -void RenderablePlanet::preCalculateAtmosphereParam() { - - //========================================================== - //========= Load Shader Programs for Calculations ========== - //========================================================== - loadComputationPrograms(); - - GLenum err; - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error loading shader programs for Atmosphere computation. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - //========================================================== - //============ Create Textures for Calculations ============ - //========================================================== - createComputationTextures(); - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error creating textures for Atmosphere computation. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - // Preparing FBO... - GLint defaultFBO; - glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); - - GLuint calcFBO; - glGenFramebuffers(1, &calcFBO); - glBindFramebuffer(GL_FRAMEBUFFER, calcFBO); - glReadBuffer(GL_COLOR_ATTACHMENT1); - //glDrawBuffer(GL_COLOR_ATTACHMENT1); - GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; - glDrawBuffers(2, drawBuffers); - - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errString = gluErrorString(err); - std::stringstream ss; - ss << "Error creating FrameBuffer Object for Atmosphere computation. OpenGL error: " << errString << std::endl; - LERROR(ss.str()); - } - - // Prepare for rendering/calculations - GLuint calcVAO; - GLuint calcVBO; - createRenderQuad(&calcVAO, &calcVBO, 1.0f); - - GLint m_viewport[4]; - glGetIntegerv(GL_VIEWPORT, m_viewport); - - // Execute Calculations... - LDEBUG("Starting precalculations for scattering effects..."); - - //========================================================== - //=================== Execute Calculations ================= - //========================================================== - executeCalculations(calcVAO, drawBuffers, 6); - - deleteUnusedComputationTextures(); - - glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO); - glViewport(m_viewport[0], m_viewport[1], - m_viewport[2], m_viewport[3]); - glDeleteBuffers(1, &calcVBO); - glDeleteVertexArrays(1, &calcVAO); - glDeleteFramebuffers(1, &calcFBO); - - LDEBUG("Ended precalculations for scattering effects..."); -} - -void RenderablePlanet::createAtmosphereFBO() { - - GLint m_viewport[4]; - glGetIntegerv(GL_VIEWPORT, m_viewport); - - /*GLint defaultFBO; - glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); */ - - _atmosphereTextureUnit.activate(); - glGenTextures(1, &_atmosphereTexture); - glBindTexture(GL_TEXTURE_2D, _atmosphereTexture); - //glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, _atmosphereTexture); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_viewport[2], - m_viewport[2], 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr); - /*glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, 8, GL_RGBA, - m_viewport[2], m_viewport[3], true);*/ - glGenFramebuffers(1, &_atmosphereFBO); - /*glBindFramebuffer(GL_FRAMEBUFFER, _atmosphereFBO); - glReadBuffer(GL_COLOR_ATTACHMENT1); - GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; - glDrawBuffers(2, drawBuffers); - - GLenum err; - while ((err = glGetError()) != GL_NO_ERROR) { - std::stringstream ss; - ss << "Error creating atmosphere framebuffer. OpenGL error: " << err << std::endl; - LERROR(ss.str()); - } - - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _dummyTexture, 0); - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, _atmosphereTexture, 0); - if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) - LERROR("Atmosphere Framework not built."); - - glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO); - glViewport(m_viewport[0], m_viewport[1], - m_viewport[2], m_viewport[3]);*/ - -} - -void RenderablePlanet::createRenderQuad(GLuint * vao, GLuint * vbo, const GLfloat size) { - - glGenVertexArrays(1, vao); - glGenBuffers(1, vbo); - glBindVertexArray(*vao); - glBindBuffer(GL_ARRAY_BUFFER, *vbo); - - const GLfloat vertex_data[] = { - // x y z w - -size, -size, 0.0f, 1.0f, - size, size, 0.0f, 1.0f, - -size, size, 0.0f, 1.0f, - -size, -size, 0.0f, 1.0f, - size, -size, 0.0f, 1.0f, - size, size, 0.0f, 1.0f - }; - - glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW); - glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 4, reinterpret_cast(0)); - glEnableVertexAttribArray(0); - - GLenum err; - while ((err = glGetError()) != GL_NO_ERROR) { - std::stringstream ss; - ss << "Error creating vertexbuffer for computation. OpenGL error: " << err << std::endl; - LERROR(ss.str()); - } -} - -void RenderablePlanet::renderQuadForCalc(const GLuint vao, const GLsizei size) -{ - glBindVertexArray(vao); - glDrawArrays(GL_TRIANGLES, 0, size); - glBindVertexArray(0); -} - -void RenderablePlanet::step3DTexture(std::unique_ptr & shaderProg, - const int layer, const bool doCalc) -{ - // See OpenGL redbook 8th Edition page 556 for Layered Rendering - //if (doCalc) - { - - float earth2 = _atmospherePlanetRadius * _atmospherePlanetRadius; - float atm2 = _atmosphereRadius * _atmosphereRadius; - float diff = atm2 - earth2; - float r = static_cast(layer) / static_cast(R_SAMPLES - 1); - float r2 = r * r; - float c = 0.0; - if (layer == 0) - c = 0.01f; - else if (layer == (R_SAMPLES - 1)) - c = -0.001f; - else - c = 0.0; - r = sqrtf(earth2 + r2 * diff) + c; - float dmin = _atmosphereRadius - r; - float dmax = sqrtf(r * r - earth2) + sqrtf(diff); - float dminp = r - _atmospherePlanetRadius; - float dmaxp = sqrtf(r * r - earth2); - - shaderProg->setUniform("r", r); - shaderProg->setUniform("dhdH", dmin, dmax, dminp, dmaxp); - } - - shaderProg->setUniform("layer", static_cast(layer)); -} - -void RenderablePlanet::saveTextureToPPMFile(const GLenum color_buffer_attachment, const std::string & fileName, - const int width, const int height) const { - std::fstream ppmFile; - - ppmFile.open(fileName.c_str(), std::fstream::out); - if (ppmFile.is_open()) { - unsigned char * pixels = new unsigned char[width*height * 3]; - for (int t = 0; t < width*height * 3; ++t) - pixels[t] = 255; - - - // check OpenGL error - GLenum err; - while ((err = glGetError()) != GL_NO_ERROR) { - const GLubyte * errorString = gluErrorString(err); - - std::cout << "\n\nBefore Reading Texture from card. OpenGL error: " - << err << " - " << errorString << std::endl; - } - - glReadBuffer(color_buffer_attachment); - glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels); - - ppmFile << "P3" << std::endl; - ppmFile << width << " " << height << std::endl; - ppmFile << "255" << std::endl; - - std::cout << "\n\nFILE\n\n"; - int k = 0; - for (int i = 0; i < width; i++) { - for (int j = 0; j < height; j++) { - ppmFile << (unsigned int)pixels[k] << " " << (unsigned int)pixels[k + 1] << " " << (unsigned int)pixels[k + 2] << " "; - k += 3; - } - ppmFile << std::endl; - } - delete[] pixels; - - ppmFile.close(); - } -} - -} // namespace openspace diff --git a/modules/base/rendering/renderableplanet.h b/modules/base/rendering/renderableplanet.h deleted file mode 100644 index 11df2513df..0000000000 --- a/modules/base/rendering/renderableplanet.h +++ /dev/null @@ -1,221 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#ifndef __RENDERABLEPLANET_H__ -#define __RENDERABLEPLANET_H__ - -// open space includes -#include - -#include -#include - -#include - -#include -#include - -// ghoul includes -namespace ghoul { - namespace opengl { - class ProgramObject; - class Texture; - } -} - -namespace openspace { - -namespace planetgeometry { -class PlanetGeometry; -} - -class RenderablePlanet : public Renderable { -public: - // Shadow structure - typedef struct { - std::pair source; - std::pair caster; - } ShadowConf; - - struct ShadowRenderingStruct { - float xu, xp; - float rs, rc; - glm::vec3 sourceCasterVec; - glm::vec3 casterPositionVec; - bool isShadowing; - }; - - // See: Precomputed Atmospheric Scattering from Bruneton et al. - // for explanation of the following parameters. - - const unsigned int TRANSMITTANCE_TABLE_WIDTH = 256; - const unsigned int TRANSMITTANCE_TABLE_HEIGHT = 64; - - const unsigned int IRRADIANCE_TABLE_WIDTH = 64; - const unsigned int IRRADIANCE_TABLE_HEIGHT = 16; - - const unsigned int DELTA_E_TABLE_WIDTH = 64; - const unsigned int DELTA_E_TABLE_HEIGHT = 16; - - - /*const unsigned int TRANSMITTANCE_TABLE_WIDTH = 512; - const unsigned int TRANSMITTANCE_TABLE_HEIGHT = 128; - - const unsigned int IRRADIANCE_TABLE_WIDTH = 128; - const unsigned int IRRADIANCE_TABLE_HEIGHT = 32; - - const unsigned int DELTA_E_TABLE_WIDTH = 128; - const unsigned int DELTA_E_TABLE_HEIGHT = 32;*/ - - const unsigned int R_SAMPLES = 32; - const unsigned int MU_SAMPLES = 128; - const unsigned int MU_S_SAMPLES = 32; - const unsigned int NU_SAMPLES = 8; - - /*const unsigned int R_SAMPLES = 64; - const unsigned int MU_SAMPLES = 256; - const unsigned int MU_S_SAMPLES = 64; - const unsigned int NU_SAMPLES = 16;*/ - -public: - explicit RenderablePlanet(const ghoul::Dictionary& dictionary); - ~RenderablePlanet(); - - bool initialize() override; - bool deinitialize() override; - bool isReady() const override; - - void render(const RenderData& data) override; - void update(const UpdateData& data) override; - -protected: - void loadTexture(); - -private: - void loadComputationPrograms(); - void unloadComputationPrograms(); - void createComputationTextures(); - void deleteComputationTextures(); - void deleteUnusedComputationTextures(); - void loadAtmosphereDataIntoShaderProgram(std::unique_ptr & shaderProg); - void executeCalculations(const GLuint vao, const GLenum drawBuffers[2], const GLsizei vertexSize); - void preCalculateAtmosphereParam(); - void createAtmosphereFBO(); - void createRenderQuad(GLuint * vao, GLuint * vbo, const GLfloat size); - void renderQuadForCalc(const GLuint vao, const GLsizei size); - void step3DTexture(std::unique_ptr & shaderProg, - const int layer, const bool doCalc = true); - void saveTextureToPPMFile(const GLenum color_buffer_attachment, const std::string & fileName, - const int width, const int height) const; - -private: - properties::StringProperty _colorTexturePath; - properties::StringProperty _nightTexturePath; - properties::StringProperty _heightMapTexturePath; - properties::StringProperty _cloudsTexturePath; - properties::StringProperty _reflectanceTexturePath; - - std::unique_ptr _programObject; - std::unique_ptr _transmittanceProgramObject; - std::unique_ptr _irradianceProgramObject; - std::unique_ptr _irradianceSupTermsProgramObject; - std::unique_ptr _inScatteringProgramObject; - std::unique_ptr _inScatteringSupTermsProgramObject; - std::unique_ptr _deltaEProgramObject; - std::unique_ptr _deltaSProgramObject; - std::unique_ptr _deltaSSupTermsProgramObject; - std::unique_ptr _deltaJProgramObject; - std::unique_ptr _atmosphereProgramObject; - ghoul::opengl::TextureUnit _dummyTextureUnit; - ghoul::opengl::TextureUnit _dummy3DTextureUnit; - ghoul::opengl::TextureUnit _transmittanceTableTextureUnit; - ghoul::opengl::TextureUnit _irradianceTableTextureUnit; - ghoul::opengl::TextureUnit _inScatteringTableTextureUnit; - ghoul::opengl::TextureUnit _deltaETableTextureUnit; - ghoul::opengl::TextureUnit _deltaSRayleighTableTextureUnit; - ghoul::opengl::TextureUnit _deltaSMieTableTextureUnit; - ghoul::opengl::TextureUnit _deltaJTableTextureUnit; - ghoul::opengl::TextureUnit _atmosphereTextureUnit; - std::unique_ptr _texture; - std::unique_ptr _nightTexture; - std::unique_ptr _reflectanceTexture; - std::unique_ptr _heightMapTexture; - std::unique_ptr _cloudsTexture; - GLuint _transmittanceTableTexture; - GLuint _irradianceTableTexture; - GLuint _inScatteringTableTexture; - GLuint _deltaETableTexture; - GLuint _deltaSRayleighTableTexture; - GLuint _deltaSMieTableTexture; - GLuint _deltaJTableTexture; - GLuint _dummyTexture; - GLuint _dummy3DTexture; - GLuint _atmosphereTexture; - GLuint _atmosphereFBO; - GLuint _atmosphereRenderVAO; - GLuint _atmosphereRenderVBO; - - properties::FloatProperty _heightExaggeration; - - planetgeometry::PlanetGeometry* _geometry; - properties::BoolProperty _performShading; - properties::IntProperty _rotation; - float _alpha; - std::vector< ShadowConf > _shadowConfArray; - float _planetRadius; - - glm::dmat3 _stateMatrix; - std::string _frame; - std::string _target; - bool _hasNightTexture; - bool _hasReflectanceTexture; - bool _hasHeightTexture; - bool _hasCloudsTexture; - bool _shadowEnabled; - double _time; - - // Atmosphere Data - bool _atmosphereCalculated; - bool _atmosphereEnabled; - float _atmosphereRadius; - float _atmospherePlanetRadius; - float _planetAverageGroundReflectance; - float _rayleighHeightScale; - float _mieHeightScale; - float _miePhaseConstant; - glm::vec3 _mieExtinctionCoeff; - glm::vec3 _rayleighScatteringCoeff; - glm::vec3 _mieScatteringCoeff; - - - bool tempPic; - - unsigned int count; - - -}; - -} // namespace openspace - -#endif // __RENDERABLEPLANET_H__ diff --git a/modules/base/rendering/renderablesphere.cpp b/modules/base/rendering/renderablesphere.cpp index 557831bd43..ce5049df5a 100644 --- a/modules/base/rendering/renderablesphere.cpp +++ b/modules/base/rendering/renderablesphere.cpp @@ -22,7 +22,6 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ - #include #include @@ -37,12 +36,12 @@ #include namespace { - const std::string _loggerCat = "RenderableSphere"; + static const std::string _loggerCat = "RenderableSphere"; - const std::string keySize = "Size"; - const std::string keySegments = "Segments"; - const std::string keyTexture = "Texture"; - const std::string keyOrientation = "Orientation"; + const char* keySize = "Size"; + const char* keySegments = "Segments"; + const char* keyTexture = "Texture"; + const char* keyOrientation = "Orientation"; enum Orientation { Outside = 1, @@ -122,7 +121,7 @@ bool RenderableSphere::initialize() { RenderEngine& renderEngine = OsEng.renderEngine(); _shader = renderEngine.buildRenderProgram("Sphere", "${MODULE_BASE}/shaders/sphere_vs.glsl", - "${MODULES}/base/shaders/sphere_fs.glsl"); + "${MODULE_BASE}/shaders/sphere_fs.glsl"); if (!_shader) return false; diff --git a/modules/base/rendering/renderablesphere.h b/modules/base/rendering/renderablesphere.h index 2a2d49c1b0..b423a864a7 100644 --- a/modules/base/rendering/renderablesphere.h +++ b/modules/base/rendering/renderablesphere.h @@ -22,15 +22,17 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERABLESPHERE_H__ -#define __RENDERABLESPHERE_H__ +#ifndef __OPENSPACE_MODULE_BASE___RENDERABLESPHERE___H__ +#define __OPENSPACE_MODULE_BASE___RENDERABLESPHERE___H__ #include #include #include #include -#include +#include +#include +#include #include #include @@ -70,4 +72,5 @@ private: }; } // namespace openspace -#endif // __RENDERABLESPHERE_H__ + +#endif // __OPENSPACE_MODULE_BASE___RENDERABLESPHERE___H__ diff --git a/modules/base/rendering/renderablesphericalgrid.cpp b/modules/base/rendering/renderablesphericalgrid.cpp index b1f62cdb87..6fc2743814 100644 --- a/modules/base/rendering/renderablesphericalgrid.cpp +++ b/modules/base/rendering/renderablesphericalgrid.cpp @@ -32,13 +32,13 @@ #include namespace { - const std::string _loggerCat = "RenderableSphericalGrid"; - const std::string KeyGridType = "GridType"; - const std::string KeyGridColor = "GridColor"; - const std::string KeyGridMatrix = "GridMatrix"; - const std::string KeyGridSegments = "GridSegments"; - const std::string KeyGridRadius = "GridRadius"; - const std::string KeyGridParentsRotation = "ParentsRotation"; + static const std::string _loggerCat = "RenderableSphericalGrid"; + const char* KeyGridType = "GridType"; + const char* KeyGridColor = "GridColor"; + const char* KeyGridMatrix = "GridMatrix"; + const char* KeyGridSegments = "GridSegments"; + const char* KeyGridRadius = "GridRadius"; + const char* KeyGridParentsRotation = "ParentsRotation"; } namespace openspace { diff --git a/modules/base/rendering/renderablesphericalgrid.h b/modules/base/rendering/renderablesphericalgrid.h index 6c7cf37da2..47bfabc849 100644 --- a/modules/base/rendering/renderablesphericalgrid.h +++ b/modules/base/rendering/renderablesphericalgrid.h @@ -22,16 +22,12 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERABLESPHERICALGRID_H__ -#define __RENDERABLESPHERICALGRID_H__ +#ifndef __OPENSPACE_MODULE_BASE___RENDERABLESPHERICALGRID___H__ +#define __OPENSPACE_MODULE_BASE___RENDERABLESPHERICALGRID___H__ -// more or less a brutal adaptation of powerscaledsphere class - -// open space includes #include #include -// ghoul includes #include #include @@ -48,7 +44,7 @@ public: void render(const RenderData& data) override; void update(const UpdateData& data) override; -private: + protected: typedef struct { GLfloat location[4]; @@ -57,7 +53,6 @@ protected: GLubyte padding[28]; // Pads the struct out to 64 bytes for performance increase } Vertex; - ghoul::opengl::ProgramObject* _gridProgram; std::string _gridType; glm::vec4 _gridColor; @@ -79,5 +74,7 @@ protected: Vertex* _varray; int* _iarray; }; + }// namespace openspace -#endif \ No newline at end of file + +#endif // __OPENSPACE_MODULE_BASE___RENDERABLESPHERICALGRID___H__ diff --git a/modules/base/rendering/renderabletrail.cpp b/modules/base/rendering/renderabletrail.cpp index a95cb3054d..0313f59687 100644 --- a/modules/base/rendering/renderabletrail.cpp +++ b/modules/base/rendering/renderabletrail.cpp @@ -23,199 +23,352 @@ ****************************************************************************************/ #include -#include -#include -#include -#include +#include #include #include -#include - -#include -#include - - -/* TODO for this class: -* In order to add geometry shader (for pretty-draw), -* need to pack each consecutive point pair into a vec2 -* in order to draw quad between them. -*/ +#include namespace { - const std::string _loggerCat = "RenderableTrail"; - //constants - const std::string keyName = "Name"; - const std::string keyBody = "Body"; - const std::string keyObserver = "Observer"; - const std::string keyFrame = "Frame"; - const std::string keyPathModule = "ModulePath"; - const std::string keyColor = "RGB"; - const std::string keyTropicalOrbitPeriod = "TropicalOrbitPeriod"; - const std::string keyEarthOrbitRatio = "EarthOrbitRatio"; - const std::string keyDayLength = "DayLength"; - const std::string keyStamps = "TimeStamps"; + const char* KeyTranslation = "Translation"; + const char* KeyColor = "Color"; + const char* KeyEnableFade = "EnableFade"; + const char* KeyFade = "Fade"; + const char* KeyLineWidth = "LineWidth"; + const char* KeyPointSize = "PointSize"; + const char* KeyRendering = "Rendering"; + + // The possible values for the _renderingModes property + enum RenderingMode { + RenderingModeLines = 0, + RenderingModePoints, + RenderingModeLinesPoints + }; + + // Fragile! Keep in sync with documentation + static const std::map RenderingModeConversion = { + { "Lines", RenderingModeLines }, + { "Points", RenderingModePoints }, + { "Lines+Points", RenderingModeLinesPoints }, + { "Points+Lines", RenderingModeLinesPoints } + }; } namespace openspace { +Documentation RenderableTrail::Documentation() { +using namespace documentation; + return { + "RenderableTrail", + "base_renderable_renderabletrail", + { + { + KeyTranslation, + new ReferencingVerifier("core_transform_translation"), + "This object is used to compute locations along the path. Any " + "Translation object can be used here.", + Optional::No + }, + { + KeyColor, + new DoubleVector3Verifier, + "The main color the for lines and points on this trail. The value is " + "interpreted as an RGB value.", + Optional::No + }, + { + KeyEnableFade, + new BoolVerifier, + "Toggles whether the trail should fade older points out. If this value " + "is 'true', the 'Fade' parameter determines the speed of fading. If this " + "value is 'false', the entire trail is rendered at full opacity and " + "color. The default value is 'true'.", + Optional::Yes + }, + { + KeyFade, + new DoubleVerifier, + "The fading factor that is applied to the trail if the 'EnableFade' " + "value is 'true'. If it is 'false', this setting has no effect. The " + "higher the number, the less fading is applied. This value defaults to " + "1.0.", + Optional::Yes + }, + { + KeyLineWidth, + new DoubleVerifier, + "This value specifies the line width of the trail if this rendering " + "method is selected. It defaults to 2.0.", + Optional::Yes + }, + { + KeyPointSize, + new DoubleVerifier, + "This value specifies the base size of the points along the line if this " + "rendering method is selected. If a subsampling of the values is " + "performed, the subsampled values are half this size. The default value " + "is 1.0.", + Optional::Yes + }, + { + KeyRendering, + new StringInListVerifier( + // Taken from the RenderingModeConversion map above + { "Lines", "Points", "Lines+Points", "Points + Lines" } + ), + "Determines how the trail should be rendered to the screen. If 'Lines' " + "is selected, only the line part is visible, if 'Points' is selected, " + "only the corresponding points (and subpoints) are shown. " + "Lines+Points' shows both parts. On default, only the lines are rendered", + Optional::Yes + } + }, + Exhaustive::No + }; +} + RenderableTrail::RenderableTrail(const ghoul::Dictionary& dictionary) : Renderable(dictionary) - , _lineColor("lineColor", "Line Color") - , _lineFade("lineFade", "Line Fade", 0.75f, 0.f, 5.f) + , _lineColor("lineColor", "Color", glm::vec3(1.f), glm::vec3(0.f), glm::vec3(1.f)) + , _useLineFade("useLineFade", "Use Line Fade", true) + , _lineFade("lineFade", "Line Fade", 1.f, 0.f, 20.f) , _lineWidth("lineWidth", "Line Width", 2.f, 1.f, 20.f) - , _showTimestamps("timestamps", "Show Timestamps", false) - , _programObject(nullptr) - , _successfullDictionaryFetch(true) - , _vaoID(0) - , _vBufferID(0) - , _needsSweep(true) - , _oldTime(std::numeric_limits::max()) - , _tropic(0.f) - , _ratio(0.f) - , _day(0.f) - , _increment(0.f) + , _pointSize("pointSize", "Point Size", 1, 1, 64) + , _renderingModes( + "renderingMode", + "Rendering Mode", + properties::OptionProperty::DisplayType::Dropdown + ) { - _successfullDictionaryFetch &= dictionary.getValue(keyBody, _target); - _successfullDictionaryFetch &= dictionary.getValue(keyObserver, _observer); - _successfullDictionaryFetch &= dictionary.getValue(keyFrame, _frame); - _successfullDictionaryFetch &= dictionary.getValue(keyTropicalOrbitPeriod, _tropic); - _successfullDictionaryFetch &= dictionary.getValue(keyEarthOrbitRatio, _ratio); - _successfullDictionaryFetch &= dictionary.getValue(keyDayLength, _day); - // values in modfiles set from here - // http://nssdc.gsfc.nasa.gov/planetary/factsheet/marsfact.html + _translation = std::unique_ptr(Translation::createFromDictionary( + dictionary.value(KeyTranslation) + )); + addPropertySubOwner(_translation.get()); - glm::vec3 color(0.f); - if (dictionary.hasKeyAndValue(keyColor)) - dictionary.getValue(keyColor, color); - _lineColor = color; - - bool timeStamps = false; - if (dictionary.hasKeyAndValue(keyStamps)) - dictionary.getValue(keyStamps, timeStamps); - _showTimestamps = timeStamps; - addProperty(_showTimestamps); - - _lineColor.setViewOption(properties::Property::ViewOptions::Color); + _lineColor = dictionary.value(KeyColor); addProperty(_lineColor); + if (dictionary.hasKeyAndValue(KeyEnableFade)) { + _useLineFade = dictionary.value(KeyEnableFade); + } + addProperty(_useLineFade); + + if (dictionary.hasKeyAndValue(KeyFade)) { + _lineFade = dictionary.value(KeyFade); + } addProperty(_lineFade); + if (dictionary.hasKeyAndValue(KeyLineWidth)) { + _lineWidth = dictionary.value(KeyLineWidth); + } addProperty(_lineWidth); - _distanceFade = 1.0; + + if (dictionary.hasKeyAndValue(KeyPointSize)) { + _pointSize = dictionary.value(KeyPointSize); + } + addProperty(_pointSize); + + _renderingModes.addOptions({ + { RenderingModeLines, "Lines" }, + { RenderingModePoints, "Points" }, + { RenderingModeLinesPoints, "Lines+Points" } + }); + + // This map is not accessed out of order as long as the Documentation is adapted + // whenever the map changes. The documentation will check for valid values + if (dictionary.hasKeyAndValue(KeyRendering)) { + _renderingModes = RenderingModeConversion.at( + dictionary.value(KeyRendering) + ); + } + else { + _renderingModes = RenderingModeLines; + } + addProperty(_renderingModes); } bool RenderableTrail::initialize() { - if (!_successfullDictionaryFetch) { - LERROR("The following keys need to be set in the Dictionary. Cannot initialize!"); - LERROR(keyBody << ": " << _target); - LERROR(keyObserver << ": " << _observer); - LERROR(keyFrame << ": " << _frame); - LERROR(keyTropicalOrbitPeriod << ": " << _tropic); - LERROR(keyEarthOrbitRatio << ": " << _ratio); - LERROR(keyDayLength << ": " << _day); - return false; - } - - bool completeSuccess = true; - RenderEngine& renderEngine = OsEng.renderEngine(); - _programObject = renderEngine.buildRenderProgram("EphemerisProgram", - "${MODULE_BASE}/shaders/ephemeris_vs.glsl", - "${MODULE_BASE}/shaders/ephemeris_fs.glsl"); + _programObject = renderEngine.buildRenderProgram( + "EphemerisProgram", + "${MODULE_BASE}/shaders/renderabletrail_vs.glsl", + "${MODULE_BASE}/shaders/renderabletrail_fs.glsl" + ); setRenderBin(Renderable::RenderBin::Overlay); - if (!_programObject) - return false; - - return completeSuccess; + return true; } bool RenderableTrail::deinitialize() { - glDeleteVertexArrays(1, &_vaoID); - glDeleteBuffers(1, &_vBufferID); - RenderEngine& renderEngine = OsEng.renderEngine(); if (_programObject) { renderEngine.removeRenderProgram(_programObject); _programObject = nullptr; } - return true; } bool RenderableTrail::isReady() const { - return (_programObject != nullptr) && _successfullDictionaryFetch; + return _programObject != nullptr; } -void RenderableTrail::render(const RenderData& data) { +void RenderableTrail::render(const RenderData & data) { _programObject->activate(); - //psc currentPosition = data.position; - //psc campos = data.camera.position(); - //glm::mat4 camrot = glm::mat4(data.camera.viewRotationMatrix()); - //glm::mat4 transform = glm::mat4(1); - - // setup the data to the shader - //_programObject->setUniform("ViewProjection", data.camera.viewProjectionMatrix()); - //_programObject->setUniform("ModelTransform", transform); - //setPscUniforms(*_programObject.get(), data.camera, data.position); - - // Calculate variables to be used as uniform variables in shader - glm::dvec3 bodyPosition = data.modelTransform.translation; - - // Model transform and view transform needs to be in double precision glm::dmat4 modelTransform = - glm::translate(glm::dmat4(1.0), bodyPosition) * - glm::dmat4(data.modelTransform.rotation) * // Spice rotation + glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * + glm::dmat4(data.modelTransform.rotation) * glm::dmat4(glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale))); - glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() * modelTransform; - _programObject->setUniform("modelViewTransform", glm::mat4(modelViewTransform)); _programObject->setUniform("projectionTransform", data.camera.projectionMatrix()); _programObject->setUniform("color", _lineColor); - _programObject->setUniform("nVertices", static_cast(_vertexArray.size())); - _programObject->setUniform("lineFade", _lineFade); - _programObject->setUniform("forceFade", _distanceFade); + _programObject->setUniform("useLineFade", _useLineFade); + if (_useLineFade) { + _programObject->setUniform("lineFade", _lineFade); + } - //const psc& position = data.camera.position(); - //const psc& origin = openspace::OpenSpaceEngine::ref().interactionHandler()->focusNode()->worldPosition(); - //const PowerScaledScalar& pssl = (position - origin).length(); - // - //if (pssl[0] < 0.000001){ - // if (_distanceFade > 0.0f) _distanceFade -= 0.05f; - // _programObject->setUniform("forceFade", _distanceFade); - //} - //else{ - // if (_distanceFade < 1.0f) _distanceFade += 0.05f; - // _programObject->setUniform("forceFade", _distanceFade); - //} + static std::map SortingMapping = { + // Fragile! Keep in sync with shader + { RenderInformation::VertexSorting::NewestFirst, 0 }, + { RenderInformation::VertexSorting::OldestFirst, 1 }, + { RenderInformation::VertexSorting::NoSorting, 2} + }; bool usingFramebufferRenderer = - OsEng.renderEngine().rendererImplementation() == RenderEngine::RendererImplementation::Framebuffer; - + OsEng.renderEngine().rendererImplementation() == + RenderEngine::RendererImplementation::Framebuffer; + if (usingFramebufferRenderer) { glDepthMask(false); glBlendFunc(GL_SRC_ALPHA, GL_ONE); } - glLineWidth(_lineWidth); + bool renderLines = + _renderingModes == RenderingModeLines | + _renderingModes == RenderingModeLinesPoints; - glBindVertexArray(_vaoID); - glDrawArrays(GL_LINE_STRIP, 0, static_cast(_vertexArray.size())); - glBindVertexArray(0); + bool renderPoints = + _renderingModes == RenderingModePoints | + _renderingModes == RenderingModeLinesPoints; - glLineWidth(1.f); - - if (_showTimestamps){ - glPointSize(5.f); - glBindVertexArray(_vaoID); - glDrawArrays(GL_POINTS, 0, static_cast(_vertexArray.size())); - glBindVertexArray(0); + if (renderLines) { + glLineWidth(_lineWidth); + } + if (renderPoints) { + glEnable(GL_PROGRAM_POINT_SIZE); } + auto render = [renderLines, renderPoints, p = _programObject.get(), &data, + &modelTransform, pointSize = _pointSize.value()] + (RenderInformation& info, int nVertices, int offset) + { + // We pass in the model view transformation matrix as double in order to maintain + // high precision for vertices; especially for the trails, a high vertex precision + // is necessary as they are usually far away from their reference + p->setUniform( + "modelViewTransform", + data.camera.combinedViewMatrix() * modelTransform * info._localTransform + ); + + // The vertex sorting method is used to tweak the fading along the trajectory + p->setUniform( + "vertexSortingMethod", + SortingMapping[info.sorting] + ); + + // This value is subtracted from the vertex id in the case of a potential ring + // buffer (as used in RenderableTrailOrbit) to keep the first vertex at its + // brightest + p->setUniform( + "idOffset", + offset + ); + + p->setUniform("nVertices", nVertices); + + if (renderPoints) { + // The stride parameter determines the distance between larger points and + // smaller ones + p->setUniform("stride", info.stride); + p->setUniform("pointSize", pointSize); + } + + // Fragile! Keep in sync with fragment shader + enum RenderPhase { + RenderPhaseLines = 0, + RenderPhasePoints + }; + + glBindVertexArray(info._vaoID); + if (renderLines) { + p->setUniform("renderPhase", RenderPhaseLines); + // Subclasses of this renderer might be using the index array or might now be + // so we check if there is data available and if there isn't, we use the + // glDrawArrays draw call; otherwise the glDrawElements + if (info._iBufferID == 0) { + glDrawArrays( + GL_LINE_STRIP, + info.first, + info.count + ); + } + else { + glDrawElements( + GL_LINE_STRIP, + info.count, + GL_UNSIGNED_INT, + reinterpret_cast(info.first * sizeof(unsigned int)) + ); + } + } + if (renderPoints) { + // Subclasses of this renderer might be using the index array or might now be + // so we check if there is data available and if there isn't, we use the + // glDrawArrays draw call; otherwise the glDrawElements + p->setUniform("renderPhase", RenderPhasePoints); + if (info._iBufferID == 0) { + glDrawArrays(GL_POINTS, info.first, info.count); + } + else { + glDrawElements( + GL_POINTS, + info.count, + GL_UNSIGNED_INT, + reinterpret_cast(info.first * sizeof(unsigned int)) + ); + } + } + }; + + // The combined size of vertices; -1 because we duplicate the penultimate point + int totalNumber = + _primaryRenderInformation.count + _floatingRenderInformation.count - 1; + + // The primary information might use an index buffer, so we might need to start at an + // offset + int primaryOffset = + _primaryRenderInformation._iBufferID == 0 ? 0 : _primaryRenderInformation.first; + + // Render the primary batch of vertices + render(_primaryRenderInformation, totalNumber, primaryOffset); + + // The secondary batch is optional, so we need to check whether we have any data here + if (_floatingRenderInformation._vaoID != 0 && _floatingRenderInformation.count != 0) { + render( + _floatingRenderInformation, + totalNumber, + // -1 because we duplicate the penultimate point between the vertices + -(primaryOffset + _primaryRenderInformation.count - 1) + ); + } + + if (renderPoints) { + glDisable(GL_PROGRAM_POINT_SIZE); + } + + glBindVertexArray(0); if (usingFramebufferRenderer) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); @@ -225,144 +378,4 @@ void RenderableTrail::render(const RenderData& data) { _programObject->deactivate(); } -void RenderableTrail::update(const UpdateData& data) { - if (data.isTimeJump) - _needsSweep = true; - - if (_needsSweep) { - fullYearSweep(data.time); - sendToGPU(); - _needsSweep = false; - return; - } - - double lightTime = 0.0; - - bool intervalSet = hasTimeInterval(); - double start = -DBL_MAX; - double end = DBL_MAX; - if (intervalSet) { - getInterval(start, end); - } - - // Points in the vertex array should always have a fixed distance. For this reason we - // keep the first entry in the array floating and always pointing to the current date - // As soon as the time difference between the current time and the last time is bigger - // than the fixed distance, we need to create a new fixed point - double deltaTime = std::abs(data.time - _oldTime); - int nValues = static_cast(floor(deltaTime / _increment)); - - glm::dvec3 p; - // Update the floating current time - if (start > data.time) - p = SpiceManager::ref().targetPosition(_target, _observer, _frame, {}, start, lightTime); - else if (end < data.time) - p = SpiceManager::ref().targetPosition(_target, _observer, _frame, {}, end, lightTime); - else - p = SpiceManager::ref().targetPosition(_target, _observer, _frame, {}, data.time, lightTime); - - psc pscPos = PowerScaledCoordinate::CreatePowerScaledCoordinate(p.x, p.y, p.z); - - pscPos[3] += 3; // KM to M - _vertexArray[0] = { pscPos[0], pscPos[1], pscPos[2], pscPos[3] }; - - if (nValues != 0) { - std::vector tmp(nValues); - for (int i = nValues; i > 0; --i) { - double et = _oldTime + i * _increment; - if (start > et) - et = start; - else if (end < et) - et = end; - glm::dvec3 p = - SpiceManager::ref().targetPosition(_target, _observer, _frame, {}, et, lightTime); - pscPos = PowerScaledCoordinate::CreatePowerScaledCoordinate(p.x, p.y, p.z); - pscPos[3] += 3; - tmp[nValues - i] = { pscPos[0], pscPos[1], pscPos[2], pscPos[3] }; - } - - size_t size = _vertexArray.size(); - _vertexArray.insert(_vertexArray.begin() + 1, tmp.begin(), tmp.end()); - _vertexArray.resize(size); - - _oldTime += nValues * _increment; - } - - glBindBuffer(GL_ARRAY_BUFFER, _vBufferID); - glBufferSubData(GL_ARRAY_BUFFER, 0, _vertexArray.size() * sizeof(TrailVBOLayout), &_vertexArray[0]); -} - -/* This algorithm estimates and precomputes the number of segments required for -* any planetary object in space, given a tropical orbit period and earth-to-planet -* orbit ratio. In doing so, it finds the exact increment of time corresponding -* to a planetary year. -* Therefore all planets need said constants, for other objects we need a different, -* and most likely heuristic measure to easily estimate a nodal time-increment. -* Trivial, yet - a TODO. -*/ -void RenderableTrail::fullYearSweep(double time) { - const int SecondsPerEarthYear = 31540000; - - double lightTime = 0.0; - float planetYear = SecondsPerEarthYear * _ratio; - int segments = static_cast(_tropic); - - bool intervalSet = hasTimeInterval(); - double start = -DBL_MAX; - double end = DBL_MAX; - if (intervalSet) { - intervalSet &= getInterval(start, end); - } - - _increment = planetYear / _tropic; - - _oldTime = time; - - _vertexArray.resize(segments+2); - glm::dvec3 p; - bool failed = false; - for (int i = 0; i < segments+2; i++) { - if (start > time && intervalSet) { - time = start; - } - else if (end < time && intervalSet) { - time = end; - } - - if (!failed || intervalSet) { - try { - p = - SpiceManager::ref().targetPosition(_target, _observer, _frame, {}, time, lightTime); - } - catch (const SpiceManager::SpiceException& e) { - // This fires for PLUTO BARYCENTER and SUN and uses the only value sometimes? - // ---abock - //LERROR(e.what()); - failed = true; - } - } - - psc pscPos = PowerScaledCoordinate::CreatePowerScaledCoordinate(p.x, p.y, p.z); - pscPos[3] += 3; - - _vertexArray[i] = {pscPos[0], pscPos[1], pscPos[2], pscPos[3]}; - time -= _increment; - } - -} - -void RenderableTrail::sendToGPU() { - glGenVertexArrays(1, &_vaoID); - glGenBuffers(1, &_vBufferID); - - glBindVertexArray(_vaoID); - glBindBuffer(GL_ARRAY_BUFFER, _vBufferID); - glBufferData(GL_ARRAY_BUFFER, _vertexArray.size() * sizeof(TrailVBOLayout), NULL, GL_STREAM_DRAW); // orphaning the buffer, sending NULL data. - glBufferSubData(GL_ARRAY_BUFFER, 0, _vertexArray.size() * sizeof(TrailVBOLayout), &_vertexArray[0]); - - glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0); - glBindVertexArray(0); -} - } // namespace openspace diff --git a/modules/base/rendering/renderabletrail.h b/modules/base/rendering/renderabletrail.h index fbdb5bf0e2..4b421cf88a 100644 --- a/modules/base/rendering/renderabletrail.h +++ b/modules/base/rendering/renderabletrail.h @@ -22,12 +22,18 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERABLETRAIL_H__ -#define __RENDERABLETRAIL_H__ +#ifndef __OPENSPACE_MODULE_BASE___RENDERABLETRAIL___H__ +#define __OPENSPACE_MODULE_BASE___RENDERABLETRAIL___H__ #include + +#include +#include +#include +#include +#include #include -#include +#include #include @@ -40,55 +46,119 @@ namespace opengl { namespace openspace { +class Translation; + +/** + * This is the base class for a trail that is drawn behind an arbitrary object. The two + * concreate implementations are RenderableTrailOrbit, for objects that have a (roughly) + * repeating orbit, and RenderableTrailTrajectory, for objects that are less orbit-like. + * The main difference between two subclasses is that RenderableTrailOrbit updates itself + * continously, whereas RenderableTrailTrajectory precomputes the entire trail in advance. + * + * This class is responsible for the rendering of the vertex buffer objects which are + * filled by the subclasses. The buffers contain a list of TrailVBOLayout objects that is + * the three dimensional position for each point along the line. + * + * Trails can be rendered either as lines, as points, or a combination of both with + * varying colors, line thicknesses, or fading settings. If trails are rendered as points, + * the RenderInformation's \c stride parameter determines the number of points between + * larger points. A potential use case for this is showing the passage of time along a + * trail by using a point separation of one hour and a subsampling of 4, you would get a + * point every 15 minutes with every hourly point being bigger. + * + * The positions for each point along the trail is provided through a Translation object, + * the type of which is specified in the dictionary that is passed to the constructor. A + * typical implementation of Translation used for the trail would be a SpiceTranslation. + */ class RenderableTrail : public Renderable { public: - explicit RenderableTrail(const ghoul::Dictionary& dictionary); - bool initialize() override; bool deinitialize() override; bool isReady() const override; + /** + * The render method will set up the shader information and then render first the + * information contained in the the \c _primaryRenderInformation, then the optional + * \c _floatingRenderInformation using the provided \p data + * \param data The data that is necessary to render this Renderable + */ void render(const RenderData& data) override; - void update(const UpdateData& data) override; -private: +protected: + explicit RenderableTrail(const ghoul::Dictionary& dictionary); + + /// Returns the documentation entries that the con + static openspace::Documentation Documentation(); + + /// The layout of the VBOs struct TrailVBOLayout { - float x, y, z, e; + float x, y, z; }; - void fullYearSweep(double time); - void sendToGPU(); - - properties::Vec3Property _lineColor; - properties::FloatProperty _lineFade; - properties::FloatProperty _lineWidth; - properties::BoolProperty _showTimestamps; - - std::unique_ptr _programObject; - - bool _successfullDictionaryFetch; - - std::string _target; - std::string _observer; - std::string _frame; - - float _tropic; - float _ratio; - float _day; - - GLuint _vaoID; - GLuint _vBufferID; - - bool _needsSweep; - + /// The backend storage for the vertex buffer object containing all points for this + /// trail. std::vector _vertexArray; - float _increment; - double _oldTime = 0.0; - float _distanceFade; + /// The index array that is potentially used in the draw call. If this is empty, no + /// element draw call is used. + std::vector _indexArray; + + /// The Translation object that provides the position of the individual trail points + std::unique_ptr _translation; + + /// The RenderInformation contains information filled in by the concrete subclasses to + /// be used by this class. + struct RenderInformation { + enum class VertexSorting { + NewestFirst = 0, ///< Newer vertices have a lower index than older ones + OldestFirst, ///< Older vertices have a lower index than newer ones + NoSorting ///< No ordering in the vertices; no fading applied + }; + /// The first element in the vertex buffer to be rendered + GLint first = 0; + /// The number of values to be rendered + GLsizei count = 0; + /// The stride between 'major' points in the array + int stride = 1; + /// Sorting of the vertices; required for correct fading + VertexSorting sorting = VertexSorting::NoSorting; + + /// Local model matrix transformation, used for rendering in camera space + glm::dmat4 _localTransform = glm::dmat4(1.0); + + /// The vertex array object for this RenderInformation + GLuint _vaoID = 0; + /// The main vertex buffer object + GLuint _vBufferID = 0; + /// The optional index buffer object + GLuint _iBufferID = 0; + }; + + /// Primary set of information about the main rendering parts + RenderInformation _primaryRenderInformation; + /// Optional render information that contains information about the last, floating + /// part of the trail + RenderInformation _floatingRenderInformation; + +private: + /// Specifies the base color of the line before fading + properties::Vec3Property _lineColor; + /// Settings that enables or disables the line fading + properties::BoolProperty _useLineFade; + /// Specifies a multiplicative factor that fades out the line + properties::FloatProperty _lineFade; + /// Line width for the line rendering part + properties::FloatProperty _lineWidth; + /// Point size for the point rendering part + properties::IntProperty _pointSize; + /// The option determining which rendering method to use + properties::OptionProperty _renderingModes; + + /// Program object used to render the data stored in RenderInformation + std::unique_ptr _programObject; }; } // namespace openspace -#endif // __RENDERABLETRAIL_H__ +#endif // __OPENSPACE_MODULE_BASE___RENDERABLETRAIL___H__ diff --git a/modules/base/rendering/renderabletrailnew.cpp b/modules/base/rendering/renderabletrailnew.cpp deleted file mode 100644 index 20eb7da66f..0000000000 --- a/modules/base/rendering/renderabletrailnew.cpp +++ /dev/null @@ -1,416 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#include - -#include -#include -#include -#include - -#include -#include -#include - -#include - -#include -#include - -namespace { - const std::string _loggerCat = "RenderableTrailNew"; - - // Spice - const std::string keyBody = "Body"; - const std::string keyFrame = "Frame"; - const std::string keyObserver = "Observer"; - // Rendering properties - const std::string keyLineColor = "LineColor"; - const std::string keyPointColor = "PointColor"; - const std::string keyLineFade = "LineFade"; - const std::string keyLineWidth = "LineWidth"; - const std::string keyRenderPart = "RenderPart"; - const std::string keyShowTimeStamps = "ShowTimeStamps"; - const std::string keyRenderFullTrail = "RenderFullTrail"; - // Time interval - const std::string keyTimeRange = "TimeRange"; - const std::string keySampleDeltaTime = "SampleDeltaTime"; - const std::string keySubSamples = "SubSamples"; - // Static Constants - static const glm::vec3 DEFAULT_COLOR = glm::vec3(1.0f); - static const float DEFAULT_LINE_FADE = 0.5f; - static const float DEFAULT_LINE_WIDTH = 2.0f; - static const int DEFAULT_POINT_STEPS = 1; - static const int DEFAULT_RENDER_PART = 1; - static const bool DEFAULT_SHOW_TIME_STAMPS = false; - static const bool DEFAULT_RENDER_FULL_TRAIL = false; -} - -namespace openspace { - -RenderableTrailNew::RenderableTrailNew(const ghoul::Dictionary& dictionary) - : Renderable(dictionary) - // Properties - , _lineColor("lineColor", "Line Color", DEFAULT_COLOR, glm::vec3(0), glm::vec3(1)) - , _pointColor("pointColor", "Point Color", DEFAULT_COLOR, glm::vec3(0), glm::vec3(1)) - , _lineFade("lineFade", "Line Fade", DEFAULT_LINE_FADE, 0, 1) - , _lineWidth("lineWidth", "Line Width", DEFAULT_LINE_WIDTH, 1, 10) - , _renderPart("renderPart", "Render Part", DEFAULT_RENDER_PART, 0, DEFAULT_RENDER_PART) - , _showTimeStamps("showTimeStamps", "Show TimeStamps", DEFAULT_SHOW_TIME_STAMPS) - , _renderFullTrail("renderFullTrail", "Render Full Trail", DEFAULT_RENDER_FULL_TRAIL) - // OpenGL - , _vaoGlobalID(0) - , _vBufferGlobalID(0) - , _vaoLocalID(0) - , _vBufferLocalID(0) - // Other - , _programObject(nullptr) - , _successfullDictionaryFetch(true) - , _currentTimeClamped(0) - , _subSamples(0) -{ - ghoul::Dictionary timeRangeDict; - - // Values that needs to be set - _successfullDictionaryFetch &= dictionary.getValue(keyBody, _body); - _successfullDictionaryFetch &= dictionary.getValue(keyObserver, _observer); - _successfullDictionaryFetch &= dictionary.getValue(keyFrame, _frame); - _successfullDictionaryFetch &= dictionary.getValue(keySampleDeltaTime, _sampleDeltaTime); - _successfullDictionaryFetch &= dictionary.getValue(keyTimeRange, timeRangeDict); - _successfullDictionaryFetch &= TimeRange::initializeFromDictionary( - timeRangeDict, _timeRange); - - // Validate - _successfullDictionaryFetch &= _sampleDeltaTime > 0; - - // Initialize optional values - glm::vec3 lineColor = glm::vec3(DEFAULT_COLOR); - glm::vec3 pointColor = glm::vec3(DEFAULT_COLOR); - float lineFade = DEFAULT_LINE_FADE; - float lineWidth = DEFAULT_LINE_WIDTH; - float pointSteps = DEFAULT_POINT_STEPS; - double renderPart = DEFAULT_RENDER_PART; - bool showTimeStamps = DEFAULT_SHOW_TIME_STAMPS; - bool renderFullTrail = DEFAULT_RENDER_FULL_TRAIL; - - // Fetch from dictionary - dictionary.getValue(keyLineColor, lineColor); - dictionary.getValue(keyPointColor, pointColor); - dictionary.getValue(keyLineFade, lineFade); - dictionary.getValue(keyLineWidth, lineWidth); - dictionary.getValue(keyRenderPart, renderPart); - dictionary.getValue(keyShowTimeStamps, showTimeStamps); - dictionary.getValue(keyRenderFullTrail, renderFullTrail); - float fSubSamples; // ghoul can not read ints from dictionaries... - if (dictionary.getValue(keySubSamples, fSubSamples)) - _subSamples = fSubSamples; - - // Set property values - _lineColor = lineColor; - _pointColor = pointColor; - _lineFade = lineFade; - _lineWidth = lineWidth; - _renderPart = renderPart; - _showTimeStamps = showTimeStamps; - _renderFullTrail = renderFullTrail; - - // Add all properties and set view options - addProperty(_lineColor); - addProperty(_pointColor); - addProperty(_lineFade); - addProperty(_lineWidth); - addProperty(_renderPart); - addProperty(_showTimeStamps); - addProperty(_renderFullTrail); - - _lineColor.setViewOption(properties::Property::ViewOptions::Color); - _pointColor.setViewOption(properties::Property::ViewOptions::Color); -} - -bool RenderableTrailNew::initialize() { - if (!_successfullDictionaryFetch) { - LERROR("The following keys need to be set in the Dictionary. Cannot initialize!"); - LERROR(keyBody << ": " << _body); - LERROR(keyObserver << ": " << _observer); - LERROR(keyFrame << ": " << _frame); - LERROR(keyTimeRange); - return false; - } - if (_subSamples < 0) - LERROR("SubSamples must not be less than 0: " << _subSamples); - - RenderEngine& renderEngine = OsEng.renderEngine(); - _programObject = renderEngine.buildRenderProgram("RenderableTrailNewProgram", - "${MODULE_BASE}/shaders/renderabletrailnew_vs.glsl", - "${MODULE_BASE}/shaders/renderabletrailnew_fs.glsl"); - - if (!_programObject) - return false; - - sweepTimeRange(); - initializeGlobalOpenGLPathData(); - initializeLocalOpenGLPathData(); - - return true; -} - -void RenderableTrailNew::initializeGlobalOpenGLPathData() { - glGenVertexArrays(1, &_vaoGlobalID); - glGenBuffers(1, &_vBufferGlobalID); - - glBindVertexArray(_vaoGlobalID); - glBindBuffer(GL_ARRAY_BUFFER, _vBufferGlobalID); - // No need to update the trail several times, no need for stream draw. - glBufferData( - GL_ARRAY_BUFFER, - _vertexPositionArray.size() * sizeof(glm::vec3), - &_vertexPositionArray[0], - GL_STATIC_DRAW); - - glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); - glBindVertexArray(0); -} - -void RenderableTrailNew::initializeLocalOpenGLPathData() { - glGenVertexArrays(1, &_vaoLocalID); - glGenBuffers(1, &_vBufferLocalID); - - glBindVertexArray(_vaoLocalID); - - glBindBuffer(GL_ARRAY_BUFFER, _vBufferLocalID); - - glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); - - glBindVertexArray(0); -} - -void RenderableTrailNew::deInitializeGlobalOpenGLPathData() { - glDeleteVertexArrays(1, &_vaoGlobalID); - glDeleteBuffers(1, &_vBufferGlobalID); -} - -void RenderableTrailNew::deInitializeLocalOpenGLPathData() { - glDeleteVertexArrays(1, &_vaoLocalID); - glDeleteBuffers(1, &_vBufferLocalID); -} - -bool RenderableTrailNew::deinitialize() { - deInitializeGlobalOpenGLPathData(); - deInitializeLocalOpenGLPathData(); - - RenderEngine& renderEngine = OsEng.renderEngine(); - if (_programObject) { - renderEngine.removeRenderProgram(_programObject); - _programObject = nullptr; - } - - return true; -} - -void RenderableTrailNew::sweepTimeRange() { - double lightTime = 0.0; - double subDeltaTime = _sampleDeltaTime / (1 + _subSamples); - glm::dvec3 bodyPosition; - // Loop through all points from time range start to end - for (double t = _timeRange.start; t < _timeRange.end; t += subDeltaTime) { - try { - bodyPosition = SpiceManager::ref().targetPosition( - _body, _observer, _frame, {}, t, lightTime); - } - catch (const SpiceManager::SpiceException& e) { - LERROR(e.what()); - break; - } - // Convert from km used by SPICE to meters used by OpenSpace - bodyPosition *= 1000; - _vertexPositionArray.push_back(glm::vec3(bodyPosition)); - } - // Last point - bodyPosition = SpiceManager::ref().targetPosition( - _body, _observer, _frame, {}, _timeRange.end, lightTime); - _vertexPositionArray.push_back(glm::vec3(bodyPosition)); -} - -bool RenderableTrailNew::isReady() const { - return (_programObject != nullptr) && _successfullDictionaryFetch; -} - -void RenderableTrailNew::render(const RenderData& data) { - _programObject->activate(); - if (_renderFullTrail.value() == true) { - preRender(_vertexPositionArray.size()); - preRenderSubPathGlobally(data); - // Easy but not beautiful solution to render all vertices with max alpha - _programObject->setUniform( - "vertexIDPadding", static_cast(_vertexPositionArray.size())); - - renderLines(_vaoGlobalID, _vertexPositionArray.size() - 1); - if (_showTimeStamps) { - renderPoints(_vaoGlobalID, _vertexPositionArray.size() - 1); - } - } - else { // Only render the trail up to the point of the object body - int nVerticesToDraw = glm::ceil(_vertexPositionArray.size() * - (_currentTimeClamped - _timeRange.start) / (_timeRange.end - _timeRange.start)); - - nVerticesToDraw = glm::min( - nVerticesToDraw, static_cast(_vertexPositionArray.size())) - 1; - if (nVerticesToDraw > 1) { - preRender(nVerticesToDraw); - // Perform rendering of the bulk of the trail in single floating point precision - preRenderSubPathGlobally(data); - // The last vertex is drawn with higher precision after this - // Hence we subtract one vertex from the ones to draw globally - int nVerticesToDrawGlobally = nVerticesToDraw - 1; - renderLines(_vaoGlobalID, nVerticesToDrawGlobally); - if (_showTimeStamps) { - renderPoints(_vaoGlobalID, nVerticesToDrawGlobally); - } - - // The last line segment is rendered relative to body to achieve high precision - preRenderSubPathLocally(data, nVerticesToDraw); - renderLines(_vaoLocalID, 2); - if (_showTimeStamps) { - renderPoints(_vaoLocalID, 2); - } - } - else if (_currentTimeClamped > _timeRange.start) { - preRenderSubPathLocally(data, 2); - renderLines(_vaoLocalID, 2); - } - } - _programObject->deactivate(); -} - -void RenderableTrailNew::preRender(int totalNumVerticesToDraw) { - // Upload uniforms that are the same for global and local rendering to the program - _programObject->setUniform("lineFade", _lineFade.value()); - _programObject->setUniform("subSamples", _subSamples); - _programObject->setUniform("maxNumVertices", - static_cast(_renderPart.value() * _vertexPositionArray.size())); - _programObject->setUniform("numVertices", totalNumVerticesToDraw); -} - -void RenderableTrailNew::preRenderSubPathGlobally(const RenderData& data) { - // Model transform and view transform needs to be in double precision - glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() * _modelTransform; - glm::mat4 modelViewProjectionTransform = - data.camera.projectionMatrix() * glm::mat4(modelViewTransform); - - // Upload uniforms that are specific to global rendering to the shader program - _programObject->setUniform( - "modelViewProjectionTransform", modelViewProjectionTransform); - _programObject->setUniform("vertexIDPadding", 0); -} - -void RenderableTrailNew::preRenderSubPathLocally( - const RenderData& data, int totalNumVerticesToDraw) { - glm::dvec3 v0; // Vertex that connects to the global part of the trail - glm::dvec3 v1; // last vertex of the trail is in the position of the body - - v0 = _vertexPositionArray[totalNumVerticesToDraw - 2]; - v1 = _clampedBodyPosition; - - // Define positions relative to body (v1) which gives the high precision - glm::vec3 vertexData[2] = {glm::vec3(v0 - v1), glm::vec3(0)}; - - // Translation translates from the position of body so vertices should - // be defined relative to body (hence the added v1 in translation part of model matrix) - glm::dmat4 localTranslation = glm::translate(glm::dmat4(1.0), v1); - glm::dmat4 modelTransformLocal = _modelTransform * localTranslation; - glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() * modelTransformLocal; - glm::mat4 modelViewProjectionTransform = - data.camera.projectionMatrix() * glm::mat4(modelViewTransform); - - // Upload the new MVP matrix to the shader program - _programObject->setUniform( - "modelViewProjectionTransform", modelViewProjectionTransform); - _programObject->setUniform("vertexIDPadding", totalNumVerticesToDraw - 2); - - // Update the attribute data on the GPU - glBindBuffer(GL_ARRAY_BUFFER, _vBufferLocalID); - glBufferData( - GL_ARRAY_BUFFER, - 2 * sizeof(glm::vec3), // Only two vertices for this part of the trail - vertexData, // Two vertices - GL_DYNAMIC_DRAW); // This part of the path is rendered dynamically - - glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); -} - -void RenderableTrailNew::renderLines(GLuint vao, int numberOfVertices) { - glLineWidth(_lineWidth); - - _programObject->setUniform("color", _lineColor.value()); - - glBindVertexArray(vao); - glDrawArrays(GL_LINE_STRIP, 0, static_cast(numberOfVertices)); - glBindVertexArray(0); - - glLineWidth(1.f); -} - -void RenderableTrailNew::renderPoints(GLuint vao, int numberOfVertices) { - glEnable(GL_PROGRAM_POINT_SIZE); - - _programObject->setUniform("color", _pointColor.value()); - _programObject->setUniform("pointSize", static_cast(_lineWidth * 3)); - - glBindVertexArray(vao); - glDrawArrays(GL_POINTS, 0, static_cast(numberOfVertices)); - glBindVertexArray(0); - - glDisable(GL_PROGRAM_POINT_SIZE); -} - -void RenderableTrailNew::update(const UpdateData& data) { - _currentTimeClamped = glm::clamp(data.time, _timeRange.start, _timeRange.end); - _modelTransform = - glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * - glm::dmat4(data.modelTransform.rotation) * - glm::dmat4(glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale))); - - // Fetch the body position using SPICE - double lightTime = 0.0; - try { - _clampedBodyPosition = SpiceManager::ref().targetPosition( - _body, _observer, _frame, {}, _currentTimeClamped, lightTime); - } - catch (const SpiceManager::SpiceException& e) { - try { - _clampedBodyPosition = SpiceManager::ref().targetPosition( - _body, _observer, _frame, {}, _currentTimeClamped, _timeRange.end); - } - catch (const SpiceManager::SpiceException& e) { - return; - } - } - // Convert from km used by SPICE to meters used by OpenSpace - _clampedBodyPosition *= 1000; -} - -} // namespace openspace diff --git a/modules/base/rendering/renderabletrailorbit.cpp b/modules/base/rendering/renderabletrailorbit.cpp new file mode 100644 index 0000000000..7215c17ab0 --- /dev/null +++ b/modules/base/rendering/renderabletrailorbit.cpp @@ -0,0 +1,453 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include + +#include + +// This class is using a VBO ring buffer + a constantly updated point as follows: +// Structure of the array with a _resolution of 16. FF denotes the floating position that +// is updated every frame: +// --------------------------------------------------------------------------------- +// | FF | | | | | | | | | | | | | | | | +// --------------------------------------------------------------------------------- +// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 +// <------ newer in time oldest +// +// In the begining the floating value starts at 0; this means that array element 0 is +// updated and uploaded to the GPU at every frame. The FF+1 element is the newest fixed +// location and FF-1 element is the oldest fixed location (including wrapping around the +// array) with the times of _lastPointTime and _firstPointTime. +// +// If the time progresses forwards and abs(time - _lastPointTime) becomes big enough, the +// oldest point is removed and a new fixed location is added. In the ring buffer this +// would be represented as: +// --------------------------------------------------------------------------------- +// | | | | | | | | | | | | | | | | FF | +// --------------------------------------------------------------------------------- +// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 +// <------ newer in time oldest +// +// Thus making the floating point traverse backwards through the array and element 0 being +// the newest fixed point. If the time processes backwards, the floating point moves +// towards the upper areas of the array instead. +// In both cases, only the values that have been changed will be uploaded to the GPU. +// +// For the rendering, this is achieved by using an index buffer that is twice the size of +// the vertex buffer containing identical two sequences indexing the vertex array. +// In an example of size 8: +// --------------------------------------------------------------------------------------- +// |0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15| 0| 1| 2| 3| 4| 5| 6| 7| 8| 9|10|11|12|13|14|15| +// --------------------------------------------------------------------------------------- +// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 +// +// The rendering step needs to know only the offset into the array (denoted by FF as the +// floating position above) and use the index array from the position. Since the indices +// in this array wrap around, so will the rendering of the vertices. Example: +// FF := 10 +// Rendering 16 elements will 'generate' the index buffer: +// 10 11 12 13 14 15 00 01 02 03 04 05 06 07 08 09 +// +// +// NB: This method was implemented without a ring buffer before by manually shifting the +// items in memory as was shown to be much slower than the current system. ---abock + +namespace { + const char* KeyPeriod = "Period"; + const char* KeyResolution = "Resolution"; +} + +namespace openspace { + +openspace::Documentation RenderableTrailOrbit::Documentation() { + using namespace documentation; + openspace::Documentation doc{ + "RenderableTrailOrbit", + "base_renderable_renderabletrailorbit", + { + { + "Type", + new StringEqualVerifier("RenderableTrailOrbit"), + "", + Optional::No + }, + { + KeyPeriod, + new DoubleVerifier, + "The objects period, i.e. the length of its orbit around the parent " + "object given in (Earth) days. In the case of Earth, this would be a " + "sidereal year (=365.242 days). If this values is specified as multiples " + "of the period, it is possible to show the effects of precession.", + Optional::No + }, + { + KeyResolution, + new IntVerifier, + "The number of samples along the orbit. This determines the resolution " + "of the trail; the tradeoff being that a higher resolution is able to " + "resolve more detail, but will take more resources while rendering, too. " + "The higher, the smoother the trail, but also more memory will be used.", + Optional::No + } + } + }; + + // Insert the parents documentation entries until we have a verifier that can deal + // with class hierarchy + openspace::Documentation parentDoc = RenderableTrail::Documentation(); + doc.entries.insert( + doc.entries.end(), + parentDoc.entries.begin(), + parentDoc.entries.end() + ); + + return doc; +} + +RenderableTrailOrbit::RenderableTrailOrbit(const ghoul::Dictionary& dictionary) + : RenderableTrail(dictionary) + , _period("period", "Period in days", 0.0, 0.0, 1e9) + , _resolution("resolution", "Number of Samples along Orbit", 10000, 1, 1e6) + , _needsFullSweep(true) + , _indexBufferDirty(true) +{ + documentation::testSpecificationAndThrow( + Documentation(), + dictionary, + "RenderableTrailOrbit" + ); + + _translation->onParameterChange([this](){ + _needsFullSweep = true; + }); + + // Period is in days + using namespace std::chrono; + int factor = duration_cast(hours(24)).count(); + _period = dictionary.value(KeyPeriod) * factor; + _period.onChange([&] { _needsFullSweep = true; _indexBufferDirty = true; }); + addProperty(_period); + + _resolution = static_cast(dictionary.value(KeyResolution)); + _resolution.onChange([&] { _needsFullSweep = true; _indexBufferDirty = true; }); + addProperty(_resolution); + + // We store the vertices with (excluding the wrapping) decending temporal order + _primaryRenderInformation.sorting = RenderInformation::VertexSorting::NewestFirst; +} + +bool RenderableTrailOrbit::initialize() { + bool res = RenderableTrail::initialize(); + + glGenVertexArrays(1, &_primaryRenderInformation._vaoID); + glGenBuffers(1, &_primaryRenderInformation._vBufferID); + glGenBuffers(1, &_primaryRenderInformation._iBufferID); + + return res; +} + +bool RenderableTrailOrbit::deinitialize() { + glDeleteVertexArrays(1, &_primaryRenderInformation._vaoID); + glDeleteBuffers(1, &_primaryRenderInformation._vBufferID); + glDeleteBuffers(1, &_primaryRenderInformation._iBufferID); + + return RenderableTrail::deinitialize(); +} + +void RenderableTrailOrbit::update(const UpdateData& data) { + // Overview: + // 1. Update trails + // 2. Update floating position + // 3. Determine which parts of the array to upload and upload the data + + // 1 + // Update the trails; the report contains whether any of the other values has been + // touched and if so, how many + UpdateReport report = updateTrails(data); + + // 2 + // Write the current location into the floating position + glm::vec3 p = _translation->position(data.time); + _vertexArray[_primaryRenderInformation.first] = { p.x, p.y, p.z }; + + glBindVertexArray(_primaryRenderInformation._vaoID); + glBindBuffer(GL_ARRAY_BUFFER, _primaryRenderInformation._vBufferID); + + // 3 + if (!report.needsUpdate) { + // If no other values have been touched, we only need to upload the floating value + glBufferSubData( + GL_ARRAY_BUFFER, + _primaryRenderInformation.first * sizeof(TrailVBOLayout), + sizeof(TrailVBOLayout), + _vertexArray.data() + _primaryRenderInformation.first + ); + } + else { + // Otherwise we need to check how many values have been changed + if (report.nUpdated == UpdateReport::All) { + // If all of the values have been invalidated, we need to upload the entire + // array + glBufferData( + GL_ARRAY_BUFFER, + _vertexArray.size() * sizeof(TrailVBOLayout), + _vertexArray.data(), + GL_STREAM_DRAW + ); + + if (_indexBufferDirty) { + // We only need to upload the index buffer if it has been invalidated + // by changing the number of values we want to represent + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _primaryRenderInformation._iBufferID); + glBufferData( + GL_ELEMENT_ARRAY_BUFFER, + _indexArray.size() * sizeof(unsigned int), + _indexArray.data(), + GL_STATIC_DRAW + ); + _indexBufferDirty = false; + } + } + else { + // The lambda expression that will upload parts of the array starting at + // begin and containing length number of elements + auto upload = [this](int begin, int length) { + glBufferSubData( + GL_ARRAY_BUFFER, + begin * sizeof(TrailVBOLayout), + sizeof(TrailVBOLayout) * length, + _vertexArray.data() + begin + ); + }; + + // Only update the changed ones + // Since we are using a ring buffer, the number of updated needed might be + // bigger than our current points, which means we have to split the upload + // into two calls. + if (report.nUpdated > 0) { + // deltaT is positive, so the pointer is moving backwards and update has + // to happen towards the front + + // Starting index + int i = _primaryRenderInformation.first; + // Number of values + int n = report.nUpdated + 1; // +1 for the floating position + // Total size of the array + int s = _primaryRenderInformation.count; + + if (i + n <= s) { + // The current index is small enough to just use one upload call + upload(i, n); + } + else { + // The current index is too close to the wrap around part, so we need + // to split the upload into two parts: + // 1. from the current index to the end of the array + // 2. the rest starting from the beginning of the array + int first = s - i; + int second = n - first; + upload(i, first); // 1 + upload(0, second); // 2 + } + } + else { + // deltaT is negative, so the pointer is moving forwards + + // The current index + int i = _primaryRenderInformation.first; + // Number of values + int n = report.nUpdated + 1; // +1 for the floating position + // Total size of the array + int s = _primaryRenderInformation.count; + + if (i + 1 >= n) { + // The current index is big enough to fit everything into one call + upload(i+1 - n, n); + } + else { + // The current index is too close to the beginning of the array, so we + // need to split the upload into two parts: + // 1. from the beginning of the array to the current index + // 2. filling the back of the array with the rest + int b = n - (i + 1); + upload(0, i + 1); // 1 + upload(s-b, b); // 2 + } + } + } + } + + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); + + glBindVertexArray(0); +} + +RenderableTrailOrbit::UpdateReport RenderableTrailOrbit::updateTrails( + const UpdateData& data) +{ + // If we are doing a time jump, it is in general faster to recalculate everything + // than to only update parts of the array + if (data.isTimeJump) { + _needsFullSweep = true; + } + if (_needsFullSweep) { + fullSweep(data.time); + return { true, UpdateReport::All } ; + } + + // When time stands still (at the iron hill), we don't need to perform any work + if (data.delta == 0.0) { + return { false, 0 }; + } + + double secondsPerPoint = _period / (_resolution - 1); + // How much time has passed since the last permanent point + double delta = data.time - _lastPointTime; + + // We'd like to test for equality with 0 here, but due to rounding issues, we won't + // get there. If this check is not here, we will trigger the positive or negative + // branch below even though we don't have to + // + // This might become a bigger issue if we are starting to look at very short time + // intervals + const double Epsilon = 1e-7; + if (abs(delta) < Epsilon) { + return { false, 0 }; + } + + if (delta > 0.0) { + // Check whether we need to drop a new permanent point. This is only the case if + // enough (> secondsPerPoint) time has passed since the last permanent point + if (abs(delta) < secondsPerPoint) { + return { false, 0 }; + } + + // See how many points we need to drop + int nNewPoints = floor(delta / secondsPerPoint); + + // If we would need to generate more new points than there are total points in the + // array, it is faster to regenerate the entire array + if (nNewPoints >= _resolution) { + fullSweep(data.time); + return { true, UpdateReport::All }; + } + + for (int i = 0; i < nNewPoints; ++i) { + _lastPointTime += secondsPerPoint; + + // Get the new permanent point and write it into the (previously) floating + // location + glm::vec3 p = _translation->position(_lastPointTime); + _vertexArray[_primaryRenderInformation.first] = { p.x, p.y, p.z }; + + // Move the current pointer back one step to be used as the new floating + // location + --_primaryRenderInformation.first; + // And loop around if necessary + if (_primaryRenderInformation.first < 0) { + _primaryRenderInformation.first += _primaryRenderInformation.count; + } + } + + // The previously oldest permanent point has been moved nNewPoints steps into the + // future + _firstPointTime += nNewPoints * secondsPerPoint; + + return { true, nNewPoints }; + } + else { + // See how many new points needs to be generated. Delta is negative, so we need + // to invert the ratio + int nNewPoints = -(floor(delta / secondsPerPoint)); + + // If we would need to generate more new points than there are total points in the + // array, it is faster to regenerate the entire array + if (nNewPoints >= _resolution) { + fullSweep(data.time); + return { true, UpdateReport::All }; + } + + for (int i = 0; i < nNewPoints; ++i) { + _firstPointTime -= secondsPerPoint; + + // Get the new permanent point and write it into the (previously) floating + // location + glm::vec3 p = _translation->position(_firstPointTime); + _vertexArray[_primaryRenderInformation.first] = { p.x, p.y, p.z }; + + // if we are on the upper bounds of the array, we start at 0 + if (_primaryRenderInformation.first == _primaryRenderInformation.count - 1) { + // If it is at the beginning, set it to the end first + _primaryRenderInformation.first = 0; + } + else { + // Move the current pointer fowards one step to be used as the new floating + ++_primaryRenderInformation.first; + } + } + + // The previously youngest point has become nNewPoints steps older + _lastPointTime -= nNewPoints * secondsPerPoint; + + return { true, -nNewPoints }; + } +} + +void RenderableTrailOrbit::fullSweep(double time) { + // Reserve the space for the vertices + _vertexArray.clear(); + _vertexArray.resize(_resolution); + + // The index buffer stays constant until we change the size of the array + if (_indexBufferDirty) { + // Create the index buffer and fill it with two ranges for [0, _resolution) + _indexArray.clear(); + _indexArray.resize(_resolution * 2); + std::iota(_indexArray.begin(), _indexArray.begin() + _resolution, 0); + std::iota(_indexArray.begin() + _resolution, _indexArray.end(), 0); + } + + _lastPointTime = time; + + double secondsPerPoint = _period / (_resolution - 1); + // starting at 1 because the first position is a floating current one + for (int i = 1; i < _resolution; ++i) { + glm::vec3 p = _translation->position(time); + _vertexArray[i] = { p.x, p.y, p.z }; + + time -= secondsPerPoint; + } + + _primaryRenderInformation.first = 0; + _primaryRenderInformation.count = _resolution; + + _firstPointTime = time + secondsPerPoint; + _needsFullSweep = false; +} + +} // namespace openspace diff --git a/modules/base/rendering/renderabletrailorbit.h b/modules/base/rendering/renderabletrailorbit.h new file mode 100644 index 0000000000..79371ce5d9 --- /dev/null +++ b/modules/base/rendering/renderabletrailorbit.h @@ -0,0 +1,105 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_BASE___RENDERABLETRAILORBIT___H__ +#define __OPENSPACE_MODULE_BASE___RENDERABLETRAILORBIT___H__ + +#include + +#include +#include +#include + +namespace openspace { + +/** + * This concrete implementation of a RenderableTrail renders an updated trail behind an + * object that is likely to have an orbit-like path. However, this is not required and + * this class can render any kind of trail as long as it's individual positions can be + * dynamically queried at runtime. This class always renders a number of points equal to + * the _resolution number. If the time progresses, old points are discarded and new points + * are rendered. Each of these fixed points are fixed time steps apart, where as the most + * current point is floating and updated every frame. The _period determines the length of + * the trail (the distance between the newest and oldest point being _period days). + */ +class RenderableTrailOrbit : public RenderableTrail { +public: + explicit RenderableTrailOrbit(const ghoul::Dictionary& dictionary); + + bool initialize() override; + bool deinitialize() override; + + void update(const UpdateData& data) override; + + static openspace::Documentation Documentation(); + +private: + /** + * Performs a full sweep of the orbit and fills the entire vertex buffer object. + * \param time The current time up to which the full sweep should be performed + */ + void fullSweep(double time); + + /// This structure is returned from the #updateTrails method and gives information + /// about which parts of the vertex array to update + struct UpdateReport { + static const int All = 0; ///< The entire array was touched in the update + + /// If \c true at least one point was touched + bool needsUpdate; + /// Returns the number of fixed points that were touched in the update method + /// If this value is negative, the newest values were replaced, if positive the + /// oldest + int nUpdated; + }; + /** + * Updates the trail based on the new incoming UpdateData information. This function + * might update an arbitrary number of values in the vertex buffer and returns an + * UpdateReport that will tell the #update method how many values were modified. + * \param data The UpdateData struct that comes from the #update method + * \return The UpdateReport containing information which array parts were touched + */ + UpdateReport updateTrails(const UpdateData& data); + + /// The orbital period of the RenderableTrail in days + properties::DoubleProperty _period; + /// The number of points that should be sampled between _period and now + properties::IntProperty _resolution; + + /// A dirty flag that determines whether a full sweep (recomputing of all values) + /// is necessary + bool _needsFullSweep; + /// A dirty flag to determine whether the index buffer needs to be regenerated and + /// then reuploaded + bool _indexBufferDirty; + + /// The time stamp of the oldest point in the array + double _firstPointTime; + /// The time stamp of the newest fixed point in the array + double _lastPointTime; +}; + +} // namespace openspace + +#endif // __OPENSPACE_MODULE_BASE___RENDERABLETRAILORBIT___H__ diff --git a/modules/base/rendering/renderabletrailtrajectory.cpp b/modules/base/rendering/renderabletrailtrajectory.cpp new file mode 100644 index 0000000000..89f2f7d947 --- /dev/null +++ b/modules/base/rendering/renderabletrailtrajectory.cpp @@ -0,0 +1,318 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include + +// This class creates the entire trajectory at once and keeps it in memory the entire +// time. This means that there is no need for updating the trail at runtime, but also that +// the whole trail has to fit in memory. +// Opposed to the RenderableTrailOrbit, no index buffer is needed as the vertex can be +// written into the vertex buffer object continuously and then selected by using the +// count variable from the RenderInformation struct to toggle rendering of the entire path +// or subpath. +// In addition, this RenderableTrail implementation uses an additional RenderInformation +// bucket that contains the line from the last shown point to the current location of the +// object iff not the entire path is shown and the object is between _startTime and +// _endTime. This buffer is updated every frame. + +namespace { + const char* KeyTranslation = "Translation"; + const char* KeyStartTime = "StartTime"; + const char* KeyEndTime = "EndTime"; + const char* KeySampleInterval = "SampleInterval"; + const char* KeyTimeStampSubsample = "TimeStampSubsampleFactor"; + const char* KeyShowFullTrail = "ShowFullTrail"; +} + +namespace openspace { + +openspace::Documentation RenderableTrailTrajectory::Documentation() { + using namespace documentation; + openspace::Documentation doc { + "RenderableTrailTrajectory", + "base_renderable_renderabletrailtrajectory", + { + { + "Type", + new StringEqualVerifier("RenderableTrailTrajectory"), + "", + Optional::No + }, + { + KeyStartTime, + new StringAnnotationVerifier("A valid date"), + "The start time for the range of this trajectory. The date must be in " + "ISO 8601 format: YYYY MM DD HH:mm:ss.xxx", + Optional::No + }, + { + KeyEndTime, + new StringAnnotationVerifier("A valid date"), + "The end time for the range of this trajectory. The date must be in " + "ISO 8601 format: YYYY MM DD HH:mm:ss.xxx", + Optional::No + }, + { + KeySampleInterval, + new DoubleVerifier, + "The interval between samples of the trajectory. This value (together " + "with 'TimeStampSubsampleFactor') determines how far apart (in time) the " + "samples are spaced along the trajectory. The time interval between " + "'StartTime' and 'EndTime' is split into 'SampleInterval' * " + "'TimeStampSubsampleFactor' segments.", + Optional::No + }, + { + KeyTimeStampSubsample, + new IntVerifier, + "The factor that is used to create subsamples along the trajectory. This " + "value (together with 'SampleInterval') determines how far apart (in " + "time) the samples are spaced along the trajectory. The time interval " + "between 'StartTime' and 'EndTime' is split into 'SampleInterval' * " + "'TimeStampSubsampleFactor' segments. The default value for this is 1", + Optional::Yes + }, + { + KeyShowFullTrail, + new BoolVerifier, + "If this value is set to 'true', the entire trail will be rendered; if " + "it is 'false', only the trail until the current time in the application " + "will be shown. The default value for this setting is 'false'.", + Optional::Yes + } + } + }; + + // Insert the parents documentation entries until we have a verifier that can deal + // with class hierarchy + openspace::Documentation parentDoc = RenderableTrail::Documentation(); + doc.entries.insert( + doc.entries.end(), + parentDoc.entries.begin(), + parentDoc.entries.end() + ); + + return doc; +} + +RenderableTrailTrajectory::RenderableTrailTrajectory(const ghoul::Dictionary& dictionary) + : RenderableTrail(dictionary) + , _startTime("startTime", "Start Time") + , _endTime("endTime", "End Time") + , _sampleInterval("sampleInterval", "Sample Interval", 2.0, 2.0, 1e6) + , _timeStampSubsamplingFactor( + "subSample", + "Time Stamp Subsampling Factor", + 1, 1, 1e9 + ) + , _renderFullTrail("renderFullTrail", "Render Full Trail", false) + , _needsFullSweep(true) + , _subsamplingIsDirty(true) +{ + documentation::testSpecificationAndThrow( + Documentation(), + dictionary, + "RenderableTrailTrajectory" + ); + + _translation->onParameterChange([this]() { + _needsFullSweep = true; + }); + + _startTime = dictionary.value(KeyStartTime); + _startTime.onChange([this] { _needsFullSweep = true; }); + addProperty(_startTime); + + _endTime = dictionary.value(KeyEndTime); + _endTime.onChange([this] { _needsFullSweep = true; }); + addProperty(_endTime); + + _sampleInterval = dictionary.value(KeySampleInterval); + _sampleInterval.onChange([this] { _needsFullSweep = true; }); + addProperty(_sampleInterval); + + if (dictionary.hasKeyAndValue(KeyTimeStampSubsample)) { + _timeStampSubsamplingFactor = dictionary.value(KeyTimeStampSubsample); + } + _timeStampSubsamplingFactor.onChange([this] { _subsamplingIsDirty = true; }); + addProperty(_timeStampSubsamplingFactor); + + if (dictionary.hasKeyAndValue(KeyShowFullTrail)) { + _renderFullTrail = dictionary.value(KeyShowFullTrail); + } + addProperty(_renderFullTrail); + + // We store the vertices with ascending temporal order + _primaryRenderInformation.sorting = RenderInformation::VertexSorting::OldestFirst; +} + +bool RenderableTrailTrajectory::initialize() { + bool res = RenderableTrail::initialize(); + + // We don't need an index buffer, so we keep it at the default value of 0 + glGenVertexArrays(1, &_primaryRenderInformation._vaoID); + glGenBuffers(1, &_primaryRenderInformation._vBufferID); + + // We do need an additional render information bucket for the additional line from the + // last shown permanent line to the current position of the object + glGenVertexArrays(1, &_floatingRenderInformation._vaoID); + glGenBuffers(1, &_floatingRenderInformation._vBufferID); + _floatingRenderInformation.sorting = RenderInformation::VertexSorting::OldestFirst; + + return res; +} + +bool RenderableTrailTrajectory::deinitialize() { + glDeleteVertexArrays(1, &_primaryRenderInformation._vaoID); + glDeleteBuffers(1, &_primaryRenderInformation._vBufferID); + + glDeleteVertexArrays(1, &_floatingRenderInformation._vaoID); + glDeleteBuffers(1, &_floatingRenderInformation._vBufferID); + + return RenderableTrail::deinitialize(); +} + +void RenderableTrailTrajectory::update(const UpdateData& data) { + if (_needsFullSweep) { + // Convert the start and end time from string representations to J2000 seconds + _start = SpiceManager::ref().ephemerisTimeFromDate(_startTime); + _end = SpiceManager::ref().ephemerisTimeFromDate(_endTime); + + double totalSampleInterval = _sampleInterval / _timeStampSubsamplingFactor; + // How many values do we need to compute given the distance between the start and + // end date and the desired sample interval + int nValues = (_end - _start) / totalSampleInterval; + + // Make space for the vertices + _vertexArray.clear(); + _vertexArray.resize(nValues); + + // ... fill all of the values + for (int i = 0; i < nValues; ++i) { + glm::vec3 p = _translation->position(_start + i * totalSampleInterval); + _vertexArray[i] = { p.x, p.y, p.z }; + } + + // ... and upload them to the GPU + glBindVertexArray(_primaryRenderInformation._vaoID); + glBindBuffer(GL_ARRAY_BUFFER, _primaryRenderInformation._vBufferID); + glBufferData( + GL_ARRAY_BUFFER, + _vertexArray.size() * sizeof(TrailVBOLayout), + _vertexArray.data(), + GL_STATIC_DRAW + ); + + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); + + // We clear the indexArray just in case. The base class will take care not to use + // it if it is empty + _indexArray.clear(); + + _subsamplingIsDirty = true; + _needsFullSweep = false; + } + + // This has to be done every update step; + if (_renderFullTrail) { + // If the full trail should be rendered at all times, we can directly render the + // entire set + _primaryRenderInformation.first = 0; + _primaryRenderInformation.count = _vertexArray.size(); + } + else { + // If only trail so far should be rendered, we need to find the corresponding time + // in the array and only render it until then + _primaryRenderInformation.first = 0; + double t = (data.time - _start) / (_end - _start); + _primaryRenderInformation.count = std::min( + ceil(_vertexArray.size() * t), + _vertexArray.size() - 1 + ); + } + + // If we are inside the valid time, we additionally want to draw a line from the last + // correct point to the current location of the object + if (data.time >= _start && data.time <= _end && !_renderFullTrail) { + // Copy the last valid location + glm::dvec3 v0( + _vertexArray[_primaryRenderInformation.count - 1].x, + _vertexArray[_primaryRenderInformation.count - 1].y, + _vertexArray[_primaryRenderInformation.count - 1].z + ); + + // And get the current location of the object + glm::dvec3 p = _translation->position(data.time); + glm::dvec3 v1 = { p.x, p.y, p.z }; + + // Comptue the difference between the points in double precision + glm::dvec3 p0 = v0 - v1; + _auxiliaryVboData[0] = { + static_cast(p0.x), + static_cast(p0.y), + static_cast(p0.z) + }; + _auxiliaryVboData[1] = { 0.f, 0.f, 0.f }; + + // Fill the render info with the data + _floatingRenderInformation.first = 0; + _floatingRenderInformation.count = 2; + + _floatingRenderInformation._localTransform = glm::translate(glm::dmat4(1.0), v1); + + glBindVertexArray(_floatingRenderInformation._vaoID); + glBindBuffer(GL_ARRAY_BUFFER, _floatingRenderInformation._vBufferID); + glBufferData( + GL_ARRAY_BUFFER, + _auxiliaryVboData.size() * sizeof(TrailVBOLayout), + _auxiliaryVboData.data(), + GL_DYNAMIC_DRAW + ); + + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); + } + else { + // if we are outside of the valid range, we don't render anything + _floatingRenderInformation.first = 0; + _floatingRenderInformation.count = 0; + } + + if (_subsamplingIsDirty) { + // If the subsampling information has changed (either by a property change or by + // a request of a full sweep) we update it here + _primaryRenderInformation.stride = _timeStampSubsamplingFactor; + _floatingRenderInformation.stride = _timeStampSubsamplingFactor; + _subsamplingIsDirty = false; + } + + glBindVertexArray(0); +} + +} // namespace openspace diff --git a/modules/base/rendering/renderabletrailtrajectory.h b/modules/base/rendering/renderabletrailtrajectory.h new file mode 100644 index 0000000000..519b505c6c --- /dev/null +++ b/modules/base/rendering/renderabletrailtrajectory.h @@ -0,0 +1,89 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_BASE___RENDERABLETRAILTRAJECTORY___H__ +#define __OPENSPACE_MODULE_BASE___RENDERABLETRAILTRAJECTORY___H__ + +#include + +#include +#include +#include +#include +#include + +namespace openspace { + +/** + * This concrete implementation of a RenderableTrail renders a fixed trail, regardless of + * its shape. The trail is sampled equitemporal (with an interval of _sampleInterval in + * seconds) between the _startTime and the _endTime. No further update is needed until any + * of these three values is changed. If _renderFullTrail is true, the entirety of the + * trail is rendered, regardless of the simulation time. If it is false, the trail is only + * rendered from the past to the current simulation time, not showing any part of the + * trail in the future. If _renderFullTrail is false, the current position of the object + * has to be updated constantly to make the trail connect to the object that has the + * trail. + */ +class RenderableTrailTrajectory : public RenderableTrail { +public: + explicit RenderableTrailTrajectory(const ghoul::Dictionary& dictionary); + + bool initialize() override; + bool deinitialize() override; + + void update(const UpdateData& data) override; + + static openspace::Documentation Documentation(); + +private: + /// The start time of the trail + properties::StringProperty _startTime; + /// The end time of the trail + properties::StringProperty _endTime; + /// The interval (in seconds) between sample points + properties::DoubleProperty _sampleInterval; + /// The factor that determines the time stamp subsampling, using different sized + /// points along the trajectory + properties::IntProperty _timeStampSubsamplingFactor; + /// Determines whether the full trail should be rendered or the future trail removed + properties::BoolProperty _renderFullTrail; + + /// Dirty flag that determines whether the full vertex buffer needs to be resampled + bool _needsFullSweep; + + /// Dirty flag to determine whether the stride information needs to be changed + bool _subsamplingIsDirty; + + std::array _auxiliaryVboData; + + /// The conversion of the _startTime into the internal time format + double _start; + /// The conversion of the _endTime into the internal time format + double _end; +}; + +} // namespace openspace + +#endif // __OPENSPACE_MODULE_BASE___RENDERABLETRAILTRAJECTORY___H__ diff --git a/modules/base/rendering/screenspaceframebuffer.cpp b/modules/base/rendering/screenspaceframebuffer.cpp index e2a8fa1a9d..1e9502a9f1 100644 --- a/modules/base/rendering/screenspaceframebuffer.cpp +++ b/modules/base/rendering/screenspaceframebuffer.cpp @@ -1,26 +1,26 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ #include #include @@ -33,10 +33,11 @@ #include namespace openspace { + ScreenSpaceFramebuffer::ScreenSpaceFramebuffer(const ghoul::Dictionary& dictionary) - :ScreenSpaceRenderable(dictionary) - ,_size("size", "Size", glm::vec4(0), glm::vec4(0), glm::vec4(2000)) - ,_framebuffer(nullptr) + : ScreenSpaceRenderable(dictionary) + , _size("size", "Size", glm::vec4(0), glm::vec4(0), glm::vec4(2000)) + , _framebuffer(nullptr) { _id = id(); setName("ScreenSpaceFramebuffer" + std::to_string(_id)); diff --git a/modules/base/rendering/screenspaceframebuffer.h b/modules/base/rendering/screenspaceframebuffer.h index e9f6586bb1..ab408e77ba 100644 --- a/modules/base/rendering/screenspaceframebuffer.h +++ b/modules/base/rendering/screenspaceframebuffer.h @@ -1,30 +1,33 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ -#ifndef __SCREENSPACEFRAMEBUFFER_H__ -#define __SCREENSPACEFRAMEBUFFER_H__ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_BASE___SCREENSPACEFRAMEBUFFER___H__ +#define __OPENSPACE_MODULE_BASE___SCREENSPACEFRAMEBUFFER___H__ #include + +#include #include #include @@ -64,4 +67,5 @@ private: }; } //namespace openspace -#endif //__SCREENSPACEFRAMEBUFFER_H__ \ No newline at end of file + +#endif //__OPENSPACE_MODULE_BASE___SCREENSPACEFRAMEBUFFER___H__ diff --git a/modules/base/rendering/screenspaceimage.cpp b/modules/base/rendering/screenspaceimage.cpp index fa208ee104..d68bd151c0 100644 --- a/modules/base/rendering/screenspaceimage.cpp +++ b/modules/base/rendering/screenspaceimage.cpp @@ -35,9 +35,9 @@ namespace { const std::string _loggerCat = "ScreenSpaceImage"; - const std::string KeyName = "Name"; - const std::string KeyTexturePath = "TexturePath"; - const std::string KeyUrl = "URL"; + const char* KeyName = "Name"; + const char* KeyTexturePath = "TexturePath"; + const char* KeyUrl = "URL"; } namespace openspace { diff --git a/modules/base/rendering/screenspaceimage.h b/modules/base/rendering/screenspaceimage.h index df66d02db7..190598b430 100644 --- a/modules/base/rendering/screenspaceimage.h +++ b/modules/base/rendering/screenspaceimage.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SCREENSPACEIMAGE_H__ -#define __SCREENSPACEIMAGE_H__ +#ifndef __OPENSPACE_MODULE_BASE___SCREENSPACEIMAGE___H__ +#define __OPENSPACE_MODULE_BASE___SCREENSPACEIMAGE___H__ #include @@ -63,4 +63,4 @@ private: } //namespace openspace -#endif //__SCREENSPACEIMAGE_H__ +#endif //__OPENSPACE_MODULE_BASE___SCREENSPACEIMAGE___H__ diff --git a/modules/base/rendering/wavefrontgeometry.cpp b/modules/base/rendering/wavefrontgeometry.cpp index 8125e73dd2..c24014f7ee 100644 --- a/modules/base/rendering/wavefrontgeometry.cpp +++ b/modules/base/rendering/wavefrontgeometry.cpp @@ -28,7 +28,7 @@ #include namespace { - const std::string _loggerCat = "WavefrontGeometry"; + static const std::string _loggerCat = "WavefrontGeometry"; } namespace openspace { diff --git a/modules/base/rotation/staticrotation.cpp b/modules/base/rotation/staticrotation.cpp index a009fa571e..5c645d4143 100644 --- a/modules/base/rotation/staticrotation.cpp +++ b/modules/base/rotation/staticrotation.cpp @@ -24,29 +24,67 @@ #include +#include + namespace { - const std::string KeyEulerAngles = "EulerAngles"; + const char* KeyRotation = "Rotation"; } namespace openspace { +Documentation StaticRotation::Documentation() { + using namespace openspace::documentation; + return { + "Static Rotation", + "base_transform_rotation_static", + { + { + "Type", + new StringEqualVerifier("StaticRotation"), + "", + Optional::No + }, + { + KeyRotation, + new OrVerifier( + new DoubleVector3Verifier(), + new DoubleMatrix3Verifier() + ), + "Stores the static rotation as either a vector containing Euler angles " + "or by specifiying the 3x3 rotation matrix directly", + Optional::No + } + }, + Exhaustive::Yes + }; +} + +StaticRotation::StaticRotation() + : _rotationMatrix("rotation", "Rotation", glm::dmat3(1.0)) +{} + StaticRotation::StaticRotation(const ghoul::Dictionary& dictionary) - : _rotationMatrix(1.0) + : StaticRotation() { - const bool hasEulerAngles = dictionary.hasKeyAndValue(KeyEulerAngles); - if (hasEulerAngles) { - glm::dvec3 tmp; - dictionary.getValue(KeyEulerAngles, tmp); - _rotationMatrix = glm::mat3_cast(glm::dquat(tmp)); + documentation::testSpecificationAndThrow( + Documentation(), + dictionary, + "StaticRotation" + ); + + + if (dictionary.hasKeyAndValue(KeyRotation)) { + _rotationMatrix = glm::mat3_cast( + glm::dquat(dictionary.value(KeyRotation)) + ); } + else { + // Must be glm::dmat3 due to specification restriction + _rotationMatrix = dictionary.value(KeyRotation); + } + + addProperty(_rotationMatrix); + _rotationMatrix.onChange([this]() { _matrix = _rotationMatrix; }); } -StaticRotation::~StaticRotation() {} - -const glm::dmat3& StaticRotation::matrix() const { - return _rotationMatrix; -} - -void StaticRotation::update(const UpdateData&) {} - -} // namespace openspace \ No newline at end of file +} // namespace openspace diff --git a/modules/base/rotation/staticrotation.h b/modules/base/rotation/staticrotation.h index 4474081057..c2439edde1 100644 --- a/modules/base/rotation/staticrotation.h +++ b/modules/base/rotation/staticrotation.h @@ -22,24 +22,27 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __STATICROTATION_H__ -#define __STATICROTATION_H__ +#ifndef __OPENSPACE_MODULE_BASE___STATICROTATION___H__ +#define __OPENSPACE_MODULE_BASE___STATICROTATION___H__ #include +#include +#include + namespace openspace { -class StaticRotation: public Rotation { +class StaticRotation : public Rotation { public: - StaticRotation(const ghoul::Dictionary& dictionary - = ghoul::Dictionary()); - virtual ~StaticRotation(); - virtual const glm::dmat3& matrix() const; - virtual void update(const UpdateData& data) override; + StaticRotation(); + StaticRotation(const ghoul::Dictionary& dictionary); + + static openspace::Documentation Documentation(); + private: - glm::dmat3 _rotationMatrix; + properties::DMat3Property _rotationMatrix; }; } // namespace openspace -#endif // __STATICROTATION_H__ +#endif // __OPENSPACE_MODULE_BASE___STATICROTATION___H__ diff --git a/modules/base/scale/staticscale.cpp b/modules/base/scale/staticscale.cpp index 214847d290..b868291e43 100644 --- a/modules/base/scale/staticscale.cpp +++ b/modules/base/scale/staticscale.cpp @@ -27,8 +27,8 @@ #include namespace { - const std::string _loggerCat = "StaticScale"; - const std::string KeyValue = "Scale"; + const char* _loggerCat = "StaticScale"; + const char* KeyValue = "Scale"; } namespace openspace { @@ -37,6 +37,7 @@ Documentation StaticScale::Documentation() { using namespace openspace::documentation; return { "Static Scaling", + "base_scale_static", {{ KeyValue, new DoubleVerifier, diff --git a/modules/base/scale/staticscale.h b/modules/base/scale/staticscale.h index e99e07fd60..8ab3e36c3e 100644 --- a/modules/base/scale/staticscale.h +++ b/modules/base/scale/staticscale.h @@ -22,12 +22,13 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __STATICSCALE_H__ -#define __STATICSCALE_H__ +#ifndef __OPENSPACE_MODULE_BASE___STATICSCALE___H__ +#define __OPENSPACE_MODULE_BASE___STATICSCALE___H__ #include #include +#include namespace openspace { @@ -45,4 +46,4 @@ private: } // namespace openspace -#endif // __STATICSCALE_H__ +#endif // __OPENSPACE_MODULE_BASE___STATICSCALE___H__ diff --git a/modules/base/shaders/atmosphere_common.glsl b/modules/base/shaders/atmosphere_common.glsl deleted file mode 100644 index c8c11238bd..0000000000 --- a/modules/base/shaders/atmosphere_common.glsl +++ /dev/null @@ -1,85 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -// Atmosphere Rendering Parameters -uniform float Rg; -uniform float Rt; -uniform float AVERAGE_GROUND_REFLECTANCE; -uniform float HR; -uniform vec3 betaR; -uniform float HM; -uniform vec3 betaMSca; -uniform vec3 betaMEx; -uniform float mieG; - -const float ATM_EPSILON = 1.0; -// const float RL = Rt + 1.0; - -// const float Rg = 6360.0; -// const float Rt = 6420.0; -// const float RL = 6421.0; -// const float ATM_EPSILON = 1.0; - -// const float AVERAGE_GROUND_REFLECTANCE = 0.1; - -// // Rayleigh -// const float HR = 8.0; -// const vec3 betaR = vec3(5.8e-3, 1.35e-2, 3.31e-2); - -// // Mie -// // DEFAULT -// const float HM = 1.2; -// const vec3 betaMSca = vec3(4e-3); -// //const vec3 betaMSca = vec3(2e-5); -// const vec3 betaMEx = betaMSca / 0.9; -// const float mieG = 1.0; - -// Integration steps -const int TRANSMITTANCE_STEPS = 500; -const int INSCATTER_INTEGRAL_SAMPLES = 50; -const int IRRADIANCE_INTEGRAL_SAMPLES = 32; -const int INSCATTER_SPHERICAL_INTEGRAL_SAMPLES = 16; - -// The next values crash NVIDIA driver for Quadro K620 -- JCC -// const int TRANSMITTANCE_INTEGRAL_SAMPLES = 1000; -// const int INSCATTER_INTEGRAL_SAMPLES = 100; -// const int IRRADIANCE_INTEGRAL_SAMPLES = 64; -// const int INSCATTER_SPHERICAL_INTEGRAL_SAMPLES = 32; - -const float M_PI = 3.141592657; - -const int TRANSMITTANCE_W = 256; -const int TRANSMITTANCE_H = 64; - -const int SKY_W = 64; -const int SKY_H = 16; - -const int OTHER_TEXTURES_W = 64; -const int OTHER_TEXTURES_H = 16; - - -const int RES_R = 32; -const int RES_MU = 128; -const int RES_MU_S = 32; -const int RES_NU = 8; \ No newline at end of file diff --git a/modules/base/shaders/atmosphere_fs.glsl b/modules/base/shaders/atmosphere_fs.glsl deleted file mode 100644 index efbccdc3a7..0000000000 --- a/modules/base/shaders/atmosphere_fs.glsl +++ /dev/null @@ -1,501 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#define EPSILON 0.0001f - -// Sun Irradiance -const float ISun = 50.0; -const uint numberOfShadows = 1; - -struct ShadowRenderingStruct { - float xu, xp; - float rs, rc; - vec3 sourceCasterVec; - vec3 casterPositionVec; - bool isShadowing; -}; - -uniform ShadowRenderingStruct shadowDataArray[numberOfShadows]; - -uniform mat4 completeInverse; -uniform mat4 projInverse; - -uniform vec4 campos; -uniform vec4 objpos; -uniform vec3 sun_pos; - -uniform vec4 cameraPosObj; -uniform vec4 planetPositionObj; -uniform vec3 sunPositionObj; - -uniform bool _performShading = true; -uniform float transparency; -uniform int shadows; - -uniform float screenX; -uniform float screenY; -uniform float screenWIDTH; -uniform float screenHEIGHT; - -uniform float time; -uniform sampler2D texture1; -uniform sampler2D nightTex; -uniform sampler2D cloudsTexture; - -uniform sampler2D reflectanceTexture; -uniform sampler2D transmittanceTexture; -uniform sampler2D irradianceTexture; -uniform sampler3D inscatterTexture; - -in vec2 vs_st; -in vec2 vs_nightTex; -in vec4 vs_normal; -in vec4 vs_position; -in vec4 vs_posWorld; - -#include "hdr.glsl" -#include "PowerScaling/powerScaling_fs.hglsl" -#include "fragment.glsl" -#include "atmosphere_common.glsl" - -vec4 butterworthFunc(const float d, const float r, const float n) { - return vec4(vec3(sqrt(r/(r + pow(d, 2*n)))), 1.0); -} - -/******************************************************************************* - ****** ALL CALCULATIONS FOR ATMOSPHERE ARE KM AND IN OBJECT SPACE SYSTEM ****** - *******************************************************************************/ - -/* Calculates the intersection of the view ray direction with the atmosphere and - * returns the first intersection (0.0 when inside atmosphere): offset - * and the second intersection: maxLength - */ - -struct Ray { - vec4 origin; - vec4 direction; -}; - -struct Ellipsoid { - vec4 center; - vec4 size; -}; - -bool intersectEllipsoid(const Ray ray, const Ellipsoid ellipsoid, out float offset, out float maxLength) { - vec4 O_C = ray.origin-ellipsoid.center; - vec4 dir = normalize(ray.direction); - - offset = 0.0f; - maxLength = 0.0f; - - float a = - ((dir.x*dir.x)/(ellipsoid.size.x*ellipsoid.size.x)) - + ((dir.y*dir.y)/(ellipsoid.size.y*ellipsoid.size.y)) - + ((dir.z*dir.z)/(ellipsoid.size.z*ellipsoid.size.z)); - float b = - ((2.f*O_C.x*dir.x)/(ellipsoid.size.x*ellipsoid.size.x)) - + ((2.f*O_C.y*dir.y)/(ellipsoid.size.y*ellipsoid.size.y)) - + ((2.f*O_C.z*dir.z)/(ellipsoid.size.z*ellipsoid.size.z)); - float c = - ((O_C.x*O_C.x)/(ellipsoid.size.x*ellipsoid.size.x)) - + ((O_C.y*O_C.y)/(ellipsoid.size.y*ellipsoid.size.y)) - + ((O_C.z*O_C.z)/(ellipsoid.size.z*ellipsoid.size.z)) - - 1.f; - - float d = ((b*b)-(4.f*a*c)); - if ( d<0.f || a==0.f || b==0.f || c==0.f ) - return false; - - d = sqrt(d); - - float t1 = (-b+d)/(2.f*a); - float t2 = (-b-d)/(2.f*a); - - if( t1<=EPSILON && t2<=EPSILON ) - return false; // both intersections are behind the ray origin - - bool back = (t1<=EPSILON || t2<=EPSILON); // If only one intersection (t>0) then we are inside the ellipsoid and the intersection is at the back of the ellipsoid - float t=0.f; - if( t1<=EPSILON ) - t = t2; - else - if( t2<=EPSILON ) - t = t1; - else - t=(t1= 0.0) { - // ray outside sphere - float m2 = l2 - (s*s); - if (m2 <= r2) { - // ray hits atmosphere - float q = sqrt(r2 - m2); - offset = s-q; - maxLength = (s+q)-offset; - - return true; - } - } - - return false; -} - -// Rayleigh phase function -float phaseFunctionR(float mu) { - return (3.0 / (16.0 * M_PI)) * (1.0 + mu * mu); -} - -// Mie phase function -float phaseFunctionM(float mu) { - return 1.5 * 1.0 / (4.0 * M_PI) * (1.0 - mieG*mieG) * pow(1.0 + (mieG*mieG) - 2.0*mieG*mu, -3.0/2.0) * (1.0 + mu * mu) / (2.0 + mieG*mieG); -} - -float opticalDepth(float H, float r, float mu, float d) { - float a = sqrt((0.5/H)*r); - vec2 a01 = a*vec2(mu, mu + d / r); - vec2 a01s = sign(a01); - vec2 a01sq = a01*a01; - float x = a01s.y > a01s.x ? exp(a01sq.x) : 0.0; - vec2 y = a01s / (2.3193*abs(a01) + sqrt(1.52*a01sq + 4.0)) * vec2(1.0, exp(-d/H*(d/(2.0*r)+mu))); - return sqrt((6.2831*H)*r) * exp((Rg-r)/H) * (x + dot(y, vec2(1.0, -1.0))); -} - -vec4 texture4D(sampler3D table, float r, float mu, float muS, float nu) -{ - float H = sqrt(Rt * Rt - Rg * Rg); - float rho = sqrt(r * r - Rg * Rg); - float rmu = r * mu; - float delta = rmu * rmu - r * r + Rg * Rg; - vec4 cst = rmu < 0.0 && delta > 0.0 ? vec4(1.0, 0.0, 0.0, 0.5 - 0.5 / float(RES_MU)) : vec4(-1.0, H * H, H, 0.5 + 0.5 / float(RES_MU)); - float uR = 0.5 / float(RES_R) + rho / H * (1.0 - 1.0 / float(RES_R)); - float uMu = cst.w + (rmu * cst.x + sqrt(delta + cst.y)) / (rho + cst.z) * (0.5 - 1.0 / float(RES_MU)); - float uMuS = 0.5 / float(RES_MU_S) + (atan(max(muS, -0.1975) * tan(1.26 * 1.1)) / 1.1 + (1.0 - 0.26)) * 0.5 * (1.0 - 1.0 / float(RES_MU_S)); - float lerp = (nu + 1.0) / 2.0 * (float(RES_NU) - 1.0); - float uNu = floor(lerp); - lerp = lerp - uNu; - return texture(table, vec3((uNu + uMuS) / float(RES_NU), uMu, uR)) * (1.0 - lerp) + - texture(table, vec3((uNu + uMuS + 1.0) / float(RES_NU), uMu, uR)) * lerp; -} - -vec3 analyticTransmittance(float r, float mu, float d) { - return exp(- betaR * opticalDepth(HR, r, mu, d) - betaMEx * opticalDepth(HM, r, mu, d)); -} - -vec3 getMie(vec4 rayMie) { - return rayMie.rgb * rayMie.a / max(rayMie.r, 1e-4) * (betaR.r / betaR); -} - -vec2 getTransmittanceUV(float r, float mu) { - float uR, uMu; - uR = sqrt((r - Rg) / (Rt - Rg)); - uMu = atan((mu + 0.15) / (1.0 + 0.15) * tan(1.5)) / 1.5; - return vec2(uMu, uR); -} - -vec3 transmittanceFromTexture(float r, float mu) { - vec2 uv = getTransmittanceUV(r, mu); - return texture(transmittanceTexture, uv).rgb; -} - -vec3 transmittanceWithShadow(float r, float mu) { - return mu < -sqrt(1.0 - (Rg / r) * (Rg / r)) ? vec3(0.0) : transmittanceFromTexture(r, mu); -} - -vec3 transmittance(float r, float mu, vec3 v, vec3 x0) { - vec3 result; - float r1 = length(x0); - float mu1 = dot(x0, v) / r; - if (mu > 0.0) { - result = min(transmittanceFromTexture(r, mu) / - transmittanceFromTexture(r1, mu1), 1.0); - } else { - result = min(transmittanceFromTexture(r1, -mu1) / - transmittanceFromTexture(r, -mu), 1.0); - } - return result; -} - -vec2 getIrradianceUV(float r, float muS) { - float uR = (r - Rg) / (Rt - Rg); - float uMuS = (muS + 0.2) / (1.0 + 0.2); - return vec2(uMuS, uR); -} - -vec3 irradiance(sampler2D sampler, float r, float muS) { - vec2 uv = getIrradianceUV(r, muS); - return texture(sampler, uv).rgb; -} - -/* - * Calculates the light scattering in the view direction comming from other - * light rays scattered in the atmosphere. - * The view direction here is the ray: x + tv, s is the sun direction, - * r and mu the position and zenith cossine angle as in the paper. - */ -vec3 inscatterLight(inout vec3 x, inout float t, vec3 v, vec3 s, - out float r, out float mu, out vec3 attenuation) { - vec3 result; - r = length(x); - mu = dot(x, v) / r; - float d = -r * mu - sqrt(r * r * (mu * mu - 1.0) + Rt * Rt); - if (d > 0.0) { - x += d * v; - t -= d; - mu = (r * mu + d) / Rt; - r = Rt; - } - // Intersects atmosphere? - if (r <= Rt) { - float nu = dot(v, s); - float muS = dot(x, s) / r; - float phaseR = phaseFunctionR(nu); - float phaseM = phaseFunctionM(nu); - vec4 inscatter = max(texture4D(inscatterTexture, r, mu, muS, nu), 0.0); - if (t > 0.0) { - vec3 x0 = x + t * v; - float r0 = length(x0); - float rMu0 = dot(x0, v); - float mu0 = rMu0 / r0; - float muS0 = dot(x0, s) / r0; - - attenuation = analyticTransmittance(r, mu, t); - //attenuation = transmittance(r, mu, v, x+t*v); - - //The following Code is generating surface acne on atmosphere. JCC - // We need a better acne avoindance constant (0.01). Done!! Adaptive from distance to x - if (r0 > Rg + 0.1*r) { - inscatter = max(inscatter - attenuation.rgbr * texture4D(inscatterTexture, r0, mu0, muS0, nu), 0.0); - const float EPS = 0.004; - float muHoriz = -sqrt(1.0 - (Rg / r) * (Rg / r)); - if (abs(mu - muHoriz) < EPS) { - float a = ((mu - muHoriz) + EPS) / (2.0 * EPS); - - mu = muHoriz - EPS; - r0 = sqrt(r * r + t * t + 2.0 * r * t * mu); - mu0 = (r * mu + t) / r0; - vec4 inScatter0 = texture4D(inscatterTexture, r, mu, muS, nu); - vec4 inScatter1 = texture4D(inscatterTexture, r0, mu0, muS0, nu); - vec4 inScatterA = max(inScatter0 - attenuation.rgbr * inScatter1, 0.0); - - mu = muHoriz + EPS; - r0 = sqrt(r * r + t * t + 2.0 * r * t * mu); - mu0 = (r * mu + t) / r0; - inScatter0 = texture4D(inscatterTexture, r, mu, muS, nu); - inScatter1 = texture4D(inscatterTexture, r0, mu0, muS0, nu); - vec4 inScatterB = max(inScatter0 - attenuation.rgbr * inScatter1, 0.0); - - inscatter = mix(inScatterA, inScatterB, a); - } - } - } - inscatter.w *= smoothstep(0.00, 0.02, muS); - result = max(inscatter.rgb * phaseR + getMie(inscatter) * phaseM, 0.0); - - } else { - // No intersection with earth - result = vec3(0.0); - } - return result * ISun; -} - -vec3 groundColor(vec3 x, float t, vec3 v, vec3 s, float r, float mu, vec3 attenuation) -{ - vec3 result; - // Ray hits ground - if (t > 0.0) { - vec3 x0 = x + t * v; - float r0 = length(x0); - vec3 n = x0 / r0; - - // Fixing texture coordinates: - vec4 reflectance = texture(reflectanceTexture, vs_st) * vec4(0.2, 0.2, 0.2, 1.0); - - // The following code is generating surface acne in ground. - // It is only necessary inside atmosphere rendering. JCC - // if (r0 > Rg + 0.01) { - // reflectance = vec4(0.4, 0.4, 0.4, 0.0); - // } - - float muS = dot(n, s); - vec3 sunLight = transmittanceWithShadow(r0, muS); - - vec3 groundSkyLight = irradiance(irradianceTexture, r0, muS); - - vec4 clouds = vec4(0.85)*texture(cloudsTexture, vs_st); - vec3 groundColor = (reflectance.rgb + clouds.rgb) * - (max(muS, 0.0) * sunLight + groundSkyLight) * ISun / M_PI; - - // Yellowish reflection from sun on oceans and rivers - if (reflectance.w > 0.0) { - vec3 h = normalize(s - v); - float fresnel = 0.02 + 0.98 * pow(1.0 - dot(-v, h), 5.0); - float waterBrdf = fresnel * pow(max(dot(h, n), 0.0), 150.0); - groundColor += reflectance.w * max(waterBrdf, 0.0) * sunLight * ISun; - } - - result = attenuation * groundColor; - } else { - // No hit - result = vec3(0.0); - } - return result; -} - -vec3 sunColor(vec3 x, float t, vec3 v, vec3 s, float r, float mu) { - if (t > 0.0) { - return vec3(0.0); - } else { - vec3 transmittance = r <= Rt ? transmittanceWithShadow(r, mu) : vec3(1.0); - float isun = step(cos(M_PI / 180.0), dot(v, s)) * ISun; - return transmittance * isun; - } -} - -/*********************************************************************** - ******* CALCULATIONS FOR SHADOWS ARE IN WORLD SPACE IN METERS ********* - ***********************************************************************/ - // TODO: Change calculations for view space in KM. -vec4 calcShadow(const ShadowRenderingStruct shadowInfoArray[numberOfShadows], const vec3 position) { - if (shadowInfoArray[0].isShadowing) { - vec3 pc = shadowInfoArray[0].casterPositionVec - position; - vec3 sc_norm = normalize(shadowInfoArray[0].sourceCasterVec); // we can pass this normalized to the shader - vec3 pc_proj = dot(pc, sc_norm) * sc_norm; - vec3 d = pc - pc_proj; - - float length_d = length(d); - float length_pc_proj = length(pc_proj); - - float r_p_pi = shadowInfoArray[0].rc * (length_pc_proj + shadowInfoArray[0].xp) / shadowInfoArray[0].xp; - - //float r_u_pi = shadowInfoArray[0].rc * (length_pc_proj + shadowInfoArray[0].xu) / shadowInfoArray[0].xu; - float r_u_pi = shadowInfoArray[0].rc * (shadowInfoArray[0].xu - length_pc_proj) / shadowInfoArray[0].xu; - - if ( length_d < r_u_pi ) { // umbra - //return vec4(0.0, 0.0, 0.0, 1.0); - //return vec4(1.0, 0.0, 0.0, 1.0); - return butterworthFunc(length_d, r_u_pi, 4.0); - } - else if ( length_d < r_p_pi ) {// penumbra - //return vec4(0.5, 0.5, 0.5, 1.0); - //return vec4(0.0, 1.0, 0.0, 1.0); - return vec4(vec3(length_d/r_p_pi), 1.0); - } - } - - return vec4(1.0); -} - -Fragment getFragment() { - vec4 position = vs_position; - float depth = pscDepth(position); - vec4 diffuse = texture(texture1, vs_st); - vec4 diffuse2 = texture(nightTex, vs_st); - vec4 clouds = texture(cloudsTexture, vs_st); - - Fragment frag; - if (_performShading) { - // atmosphere - vec4 viewport = vec4(screenX, screenY, screenWIDTH, screenHEIGHT); - vec4 ndcPos; - ndcPos.xy = ((2.0 * gl_FragCoord.xy) - (2.0 * viewport.xy)) / (viewport.zw) - 1; - ndcPos.z = (2.0 * gl_FragCoord.z - gl_DepthRange.near - gl_DepthRange.far) / - (gl_DepthRange.far - gl_DepthRange.near); - ndcPos.w = 1.0; - vec4 clipPos = ndcPos / gl_FragCoord.w; - vec4 projCoords = projInverse * clipPos; - vec4 viewDirection = normalize(completeInverse * vec4(projCoords.xyz, 0.0)); - vec3 v = normalize(viewDirection.xyz); - - float offset, maxLength; - vec4 ppos = vec4(0.0); - //if (intersectAtmosphere(planetPositionObj, v, Rt, offset, maxLength)) { - if (intersectAtmosphere(ppos, v, Rg, offset, maxLength)) { - // Following paper nomenclature - float t = offset; - vec3 x = cameraPosObj.xyz;// + offset * v; - float r = length(x); - float mu = dot(x, v) / r; - vec3 s = normalize(sunPositionObj); - - vec3 attenuation; - vec3 inscatterColor = inscatterLight(x, t, v, s, r, mu, attenuation); - vec3 groundColor = groundColor(x, t, v, s, r, mu, attenuation); - vec3 sunColor = sunColor(x, t, v, s, r, mu); - - //diffuse = HDR(vec4(sunColor + groundColor + inscatterColor, 1.0)); - //diffuse = HDR(vec4(sunColor, 1.0)); - //diffuse = HDR(vec4(groundColor, 1.0)); - //diffuse = HDR(vec4(inscatterColor, 1.0)); - - //diffuse = HDR(vec4(sunColor + groundColor + inscatterColor, 1.0) + diffuse2); - diffuse = HDR((vec4(sunColor + groundColor + inscatterColor, 1.0) + diffuse2) * - calcShadow(shadowDataArray, vs_posWorld.xyz) ); - } - // else - // diffuse = HDR(diffuse); - } - - diffuse[3] = transparency; - frag.color = diffuse; - frag.depth = depth; - - return frag; -} diff --git a/modules/base/shaders/atmosphere_vs.glsl b/modules/base/shaders/atmosphere_vs.glsl deleted file mode 100644 index d514c15a90..0000000000 --- a/modules/base/shaders/atmosphere_vs.glsl +++ /dev/null @@ -1,76 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#version __CONTEXT__ - -uniform mat4 ViewProjection; -uniform mat4 ModelTransform; -uniform mat4 NormalTransform; - -layout(location = 0) in vec4 in_position; -layout(location = 1) in vec2 in_st; -layout(location = 2) in vec3 in_normal; -//layout(location = 3) in vec2 in_nightTex; - - -out vec2 vs_st; -out vec4 vs_normal; -out vec4 vs_position; -out vec4 vs_posWorld; -out float s; -out vec4 ray; - -#include "PowerScaling/powerScaling_vs.hglsl" - -void main() -{ - // set variables - vs_st = in_st; - vs_position = in_position; - vec4 tmp = in_position; - - // this is wrong for the normal. The normal transform is the transposed inverse of the model transform - //vs_normal = normalize(ModelTransform * vec4(in_normal,0)); - - // This is the wright transformation for the normals - vs_normal = normalize(NormalTransform * vec4(in_normal,0)); - - // The position is not in world coordinates, it is in - // regular view/eye coordinates. - vec4 position = pscTransform(tmp, ModelTransform); - - // Vertex position in world coordinates in meters and - // with no powerscalling coordiantes - vec3 local_vertex_pos = mat3(ModelTransform) * in_position.xyz; - vec4 vP = psc_addition(vec4(local_vertex_pos,in_position.w),objpos); - vec4 conv = vec4(vP.xyz * pow(10,vP.w), 1.0); - vs_posWorld = conv; - - vs_position = tmp; - - // Now the position is transformed from view coordinates to SGCT projection - // coordinates. - position = ViewProjection * position; - gl_Position = z_normalization(position); -} \ No newline at end of file diff --git a/modules/base/shaders/deltaE_calc_vs.glsl b/modules/base/shaders/deltaE_calc_vs.glsl deleted file mode 100644 index 578d7ab02f..0000000000 --- a/modules/base/shaders/deltaE_calc_vs.glsl +++ /dev/null @@ -1,31 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#version __CONTEXT__ - -layout(location = 0) in vec3 in_position; - -void main() { - gl_Position = vec4(in_position, 1.0); -} \ No newline at end of file diff --git a/modules/base/shaders/deltaJ_calc_fs.glsl b/modules/base/shaders/deltaJ_calc_fs.glsl deleted file mode 100644 index b087cd7b11..0000000000 --- a/modules/base/shaders/deltaJ_calc_fs.glsl +++ /dev/null @@ -1,192 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#include "atmosphere_common.glsl" -#include "fragment.glsl" -#include "PowerScaling/powerScalingMath.hglsl" - -layout(location = 1) out vec4 renderTarget1; - -uniform float r; -uniform vec4 dhdH; - -uniform sampler2D transmittanceTexture; -uniform sampler2D deltaETexture; -uniform sampler3D deltaSRTexture; -uniform sampler3D deltaSMTexture; -uniform float first; - -const float dphi = M_PI / float(INSCATTER_SPHERICAL_INTEGRAL_SAMPLES); -const float dtheta = M_PI / float(INSCATTER_SPHERICAL_INTEGRAL_SAMPLES); - -void getMuMuSNu(const float r, vec4 dhdH, out float mu, out float mu_s, out float nu) { - float x = gl_FragCoord.x - 0.5; - float y = gl_FragCoord.y - 0.5; - if (y < float(RES_MU) / 2.0) { - float d = 1.0 - y / (float(RES_MU) / 2.0 - 1.0); - d = min(max(dhdH.z, d * dhdH.w), dhdH.w * 0.999); - mu = (Rg * Rg - r * r - d * d) / (2.0 * r * d); - mu = min(mu, -sqrt(1.0 - (Rg / r) * (Rg / r)) - 0.001); - } else { - float d = (y - float(RES_MU) / 2.0) / (float(RES_MU) / 2.0 - 1.0); - d = min(max(dhdH.x, d * dhdH.y), dhdH.y * 0.999); - mu = (Rt * Rt - r * r - d * d) / (2.0 * r * d); - } - mu_s = mod(x, float(RES_MU_S)) / (float(RES_MU_S) - 1.0); - mu_s = tan((2.0 * mu_s - 1.0 + 0.26) * 1.1) / tan(1.26 * 1.1); - nu = -1.0 + floor(x / float(RES_MU_S)) / (float(RES_NU) - 1.0) * 2.0; -} - -vec3 transmittanceFromTexture(const float r, const float mu) { - float u_r = sqrt((r - Rg) / (Rt - Rg)); - // See Colliene to understand the different mapping. - float u_mu = atan((mu + 0.15) / (1.0 + 0.15) * tan(1.5)) / 1.5; - - return texture(transmittanceTexture, vec2(u_mu, u_r)).rgb; -} - -vec3 transmittance(const float r, const float mu, float d) { - vec3 result; - float r1 = sqrt(r * r + d * d + 2.0 * r * mu * d); - float mu1 = (r * mu + d) / r1; - if (mu > 0.0) { - result = min(transmittanceFromTexture(r, mu) / - transmittanceFromTexture(r1, mu1), 1.0); - } else { - result = min(transmittanceFromTexture(r1, -mu1) / - transmittanceFromTexture(r, -mu), 1.0); - } - return result; -} - -// Rayleigh phase -float phaseFunctionR(const float mu) { - return (3.0 / (16.0 * M_PI)) * (1.0 + mu * mu); -} - -// Mie phase -float phaseFunctionM(const float mu) { - return (3.0 / (8.0 * M_PI)) * - ( ( (1.0 - (mieG*mieG) ) * (1+mu*mu) ) / - ( (2+mieG*mieG) * pow(1+mieG*mieG - 2.0*mieG*mu, 3.0/2.0) ) ); -} - -vec3 irradiance(sampler2D calcTexture, const float r, const float mu_s) { - float u_r = (r - Rg) / (Rt - Rg); - float u_mu_s = (mu_s + 0.2) / (1.0 + 0.2); - return texture(calcTexture, vec2(u_mu_s, u_r)).rgb; -} - -vec4 texture4D(sampler3D table, const float r, const float mu, - const float mu_s, const float nu) -{ - float H = sqrt(Rt * Rt - Rg * Rg); - float rho = sqrt(r * r - Rg * Rg); - float rmu = r * mu; - float delta = rmu * rmu - r * r + Rg * Rg; - vec4 cst = rmu < 0.0 && delta > 0.0 ? vec4(1.0, 0.0, 0.0, 0.5 - 0.5 / float(RES_MU)) : vec4(-1.0, H * H, H, 0.5 + 0.5 / float(RES_MU)); - float u_r = 0.5 / float(RES_R) + rho / H * (1.0 - 1.0 / float(RES_R)); - float u_mu = cst.w + (rmu * cst.x + sqrt(delta + cst.y)) / (rho + cst.z) * (0.5 - 1.0 / float(RES_MU)); - float u_mu_s = 0.5 / float(RES_MU_S) + (atan(max(mu_s, -0.1975) * tan(1.26 * 1.1)) / 1.1 + (1.0 - 0.26)) * 0.5 * (1.0 - 1.0 / float(RES_MU_S)); - float lerp = (nu + 1.0) / 2.0 * (float(RES_NU) - 1.0); - float uNu = floor(lerp); - lerp = lerp - uNu; - return texture(table, vec3((uNu + u_mu_s) / float(RES_NU), u_mu, u_r)) * (1.0 - lerp) + - texture(table, vec3((uNu + u_mu_s + 1.0) / float(RES_NU), u_mu, u_r)) * lerp; -} - -void inscatter(float r, float mu, float mu_s, float nu, out vec3 raymie) { - r = clamp(r, Rg, Rt); - mu = clamp(mu, -1.0, 1.0); - mu_s = clamp(mu_s, -1.0, 1.0); - float var = sqrt(1.0 - mu * mu) * sqrt(1.0 - mu_s * mu_s); - nu = clamp(nu, mu_s * mu - var, mu_s * mu + var); - - float cthetamin = -sqrt(1.0 - (Rg / r) * (Rg / r)); - - vec3 v = vec3(sqrt(1.0 - mu * mu), 0.0, mu); - float sx = v.x == 0.0 ? 0.0 : (nu - mu_s * mu) / v.x; - vec3 s = vec3(sx, sqrt(max(0.0, 1.0 - sx * sx - mu_s * mu_s)), mu_s); - - raymie = vec3(0.0); - - for (int itheta = 0; itheta < INSCATTER_SPHERICAL_INTEGRAL_SAMPLES; ++itheta) { - float theta = (float(itheta) + 0.5) * dtheta; - float ctheta = cos(theta); - - float greflectance = 0.0; - float dground = 0.0; - vec3 gtransp = vec3(0.0); - if (ctheta < cthetamin) { - greflectance = AVERAGE_GROUND_REFLECTANCE / M_PI; - dground = -r * ctheta - sqrt(r * r * (ctheta * ctheta - 1.0) + Rg * Rg); - gtransp = transmittance(Rg, -(r * ctheta + dground) / Rg, dground); - } - - for (int iphi = 0; iphi < 2 * INSCATTER_SPHERICAL_INTEGRAL_SAMPLES; ++iphi) { - float phi = (float(iphi) + 0.5) * dphi; - float dw = dtheta * dphi * sin(theta); - vec3 w = vec3(cos(phi) * sin(theta), sin(phi) * sin(theta), ctheta); - - float nu1 = dot(s, w); - float nu2 = dot(v, w); - float pr2 = phaseFunctionR(nu2); - float pm2 = phaseFunctionM(nu2); - - vec3 gnormal = (vec3(0.0, 0.0, r) + dground * w) / Rg; - vec3 girradiance = irradiance(deltaETexture, Rg, dot(gnormal, s)); - - vec3 raymie1; - - raymie1 = greflectance * girradiance * gtransp; - - if (first == 1.0) { - float pr1 = phaseFunctionR(nu1); - float pm1 = phaseFunctionM(nu1); - vec3 ray1 = texture4D(deltaSRTexture, r, w.z, mu_s, nu1).rgb; - vec3 mie1 = texture4D(deltaSMTexture, r, w.z, mu_s, nu1).rgb; - raymie1 += ray1 * pr1 + mie1 * pm1; - } else { - raymie1 += texture4D(deltaSRTexture, r, w.z, mu_s, nu1).rgb; - } - - raymie += raymie1 * (betaR * exp(-(r - Rg) / HR) * pr2 + betaMSca * exp(-(r - Rg) / HM) * pm2) * dw; - } - } -} - -Fragment getFragment() { - vec3 raymie; - float mu, mu_s, nu; - getMuMuSNu(r, dhdH, mu, mu_s, nu); - inscatter(r, mu, mu_s, nu, raymie); - - renderTarget1 = vec4(raymie, 1.0); - - Fragment frag; - frag.color = vec4(1.0); - frag.depth = 1.0; - - return frag; -} diff --git a/modules/base/shaders/deltaS_calc_fs.glsl b/modules/base/shaders/deltaS_calc_fs.glsl deleted file mode 100644 index c99ab18ad9..0000000000 --- a/modules/base/shaders/deltaS_calc_fs.glsl +++ /dev/null @@ -1,51 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#include "atmosphere_common.glsl" -#include "fragment.glsl" -#include "PowerScaling/powerScalingMath.hglsl" - -layout(location = 1) out vec4 renderTarget1; - -uniform int layer; - -uniform sampler3D deltaSRTexture; -uniform sampler3D deltaSMTexture; - -Fragment getFragment() { - vec3 uvw = vec3(gl_FragCoord.xy, float(layer) + 0.5) / vec3(ivec3(RES_MU_S * RES_NU, RES_MU, RES_R)); - vec4 ray = texture(deltaSRTexture, uvw); - vec4 mie = texture(deltaSMTexture, uvw); - - // We are using only the red component of the Mie scattering - // See the Precomputed Atmosphere Scattering paper for details about - // the angular precision. - renderTarget1 = vec4(ray.rgb, mie.r); - - Fragment frag; - frag.color = vec4(1.0); - frag.depth = 1.0; - - return frag; -} \ No newline at end of file diff --git a/modules/base/shaders/deltaS_calc_vs.glsl b/modules/base/shaders/deltaS_calc_vs.glsl deleted file mode 100644 index 578d7ab02f..0000000000 --- a/modules/base/shaders/deltaS_calc_vs.glsl +++ /dev/null @@ -1,31 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#version __CONTEXT__ - -layout(location = 0) in vec3 in_position; - -void main() { - gl_Position = vec4(in_position, 1.0); -} \ No newline at end of file diff --git a/modules/base/shaders/deltaS_sup_calc_vs.glsl b/modules/base/shaders/deltaS_sup_calc_vs.glsl deleted file mode 100644 index 7e3574bd9d..0000000000 --- a/modules/base/shaders/deltaS_sup_calc_vs.glsl +++ /dev/null @@ -1,31 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#version __CONTEXT__ - -layout(location = 0) in vec3 in_position; - -void main() { - gl_Position = vec4(in_position, 1.0); -} \ No newline at end of file diff --git a/modules/base/shaders/inScattering_calc_fs.glsl b/modules/base/shaders/inScattering_calc_fs.glsl deleted file mode 100644 index 1eec8a78e2..0000000000 --- a/modules/base/shaders/inScattering_calc_fs.glsl +++ /dev/null @@ -1,154 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#include "atmosphere_common.glsl" -#include "fragment.glsl" -#include "PowerScaling/powerScalingMath.hglsl" - -layout(location = 1) out vec4 renderTarget1; -layout(location = 2) out vec4 renderTarget2; - -uniform float r; -uniform vec4 dhdH; - -uniform sampler2D transmittanceTexture; - -// In the following shaders r (altitude) is the length of vector/position x in the -// atmosphere (or on the top of it when considering an observer in space), -// where the light is comming from the opposity direction of the view direction, -// here the vector v or viewDirection. -// Rg is the planet radius - -void getMuMuSNu(const float r, vec4 dhdH, out float mu, out float mu_s, out float nu) { - float x = gl_FragCoord.x - 0.5; - float y = gl_FragCoord.y - 0.5; - if (y < float(RES_MU) / 2.0) { - float d = 1.0 - y / (float(RES_MU) / 2.0 - 1.0); - d = min(max(dhdH.z, d * dhdH.w), dhdH.w * 0.999); - mu = (Rg * Rg - r * r - d * d) / (2.0 * r * d); - mu = min(mu, -sqrt(1.0 - (Rg / r) * (Rg / r)) - 0.001); - } else { - float d = (y - float(RES_MU) / 2.0) / (float(RES_MU) / 2.0 - 1.0); - d = min(max(dhdH.x, d * dhdH.y), dhdH.y * 0.999); - mu = (Rt * Rt - r * r - d * d) / (2.0 * r * d); - } - mu_s = mod(x, float(RES_MU_S)) / (float(RES_MU_S) - 1.0); - mu_s = tan((2.0 * mu_s - 1.0 + 0.26) * 1.1) / tan(1.26 * 1.1); - nu = -1.0 + floor(x / float(RES_MU_S)) / (float(RES_NU) - 1.0) * 2.0; -} - -vec3 transmittanceFromTexture(const float r, const float mu) { - float u_r = sqrt((r - Rg) / (Rt - Rg)); - // See Colliene to understand the different mapping. - float u_mu = atan((mu + 0.15) / (1.0 + 0.15) * tan(1.5)) / 1.5; - - return texture(transmittanceTexture, vec2(u_mu, u_r)).rgb; -} - -vec3 transmittance(const float r, const float mu, float d) { - vec3 result; - float r1 = sqrt(r * r + d * d + 2.0 * r * mu * d); - float mu1 = (r * mu + d) / r1; - if (mu > 0.0) { - result = min(transmittanceFromTexture(r, mu) / - transmittanceFromTexture(r1, mu1), 1.0); - } else { - result = min(transmittanceFromTexture(r1, -mu1) / - transmittanceFromTexture(r, -mu), 1.0); - } - return result; -} - -void integrand(const float r, const float mu, const float muS, const float nu, - const float t, out vec3 ray, out vec3 mie) { - ray = vec3(0.0); - mie = vec3(0.0); - float ri = sqrt(r * r + t * t + 2.0 * r * mu * t); - float muSi = (nu * t + muS * r) / ri; - ri = max(Rg, ri); - if (muSi >= -sqrt(1.0 - Rg * Rg / (ri * ri))) { - vec3 ti = transmittance(r, mu, t) * transmittanceFromTexture(ri, muSi); - ray = exp(-(ri - Rg) / HR) * ti; - mie = exp(-(ri - Rg) / HM) * ti; - } -} - -float rayDistance(const float r, const float mu) { - // cosine law - float distanceAtmosphereIntersect = -r * mu + sqrt(r * r * (mu * mu - 1.0) + - (Rt + ATM_EPSILON)*(Rt + ATM_EPSILON)); - float distance = distanceAtmosphereIntersect; - float delta = r * r * (mu * mu - 1.0) + Rg * Rg; - // No imaginary numbers... :-) - if (delta >= 0.0) { - float distanceEarthIntersect = -r * mu - sqrt(delta); - if (distanceEarthIntersect >= 0.0) { - distance = min(distanceAtmosphereIntersect, distanceEarthIntersect); - } - } - return distance; -} - -void inscatter(float r, float mu, float muS, float nu, out vec3 ray, out vec3 mie) { - // Integrating using the Trapezoidal rule: - // Integral(f(y)dy)(from a to b) = (b-a)/2n_steps*(Sum(f(y_i+1)+f(y_i))) - ray = vec3(0.0); - mie = vec3(0.0); - float dx = rayDistance(r, mu) / float(INSCATTER_INTEGRAL_SAMPLES); - float xi = 0.0; - vec3 rayi; - vec3 miei; - integrand(r, mu, muS, nu, 0.0, rayi, miei); - for (int i = 1; i <= INSCATTER_INTEGRAL_SAMPLES; ++i) { - float xj = float(i) * dx; - vec3 rayj; - vec3 miej; - integrand(r, mu, muS, nu, xj, rayj, miej); - ray += (rayi + rayj) / 2.0 * dx; - mie += (miei + miej) / 2.0 * dx; - xi = xj; - rayi = rayj; - miei = miej; - } - ray *= betaR; - mie *= betaMSca; -} - -Fragment getFragment() { - vec3 ray; - vec3 mie; - float mu, muS, nu; - getMuMuSNu(r, dhdH, mu, muS, nu); - inscatter(r, mu, muS, nu, ray, mie); - // store separately Rayleigh and Mie contributions, WITHOUT the phase function factor - // (cf "Angular precision") - renderTarget1 = vec4(ray, 1.0); - renderTarget2 = vec4(mie, 1.0); - - Fragment frag; - frag.color = vec4(1.0); - frag.depth = 1.0; - - return frag; -} \ No newline at end of file diff --git a/modules/base/shaders/inScattering_calc_vs.glsl b/modules/base/shaders/inScattering_calc_vs.glsl deleted file mode 100644 index 578d7ab02f..0000000000 --- a/modules/base/shaders/inScattering_calc_vs.glsl +++ /dev/null @@ -1,31 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#version __CONTEXT__ - -layout(location = 0) in vec3 in_position; - -void main() { - gl_Position = vec4(in_position, 1.0); -} \ No newline at end of file diff --git a/modules/base/shaders/inScattering_sup_calc_fs.glsl b/modules/base/shaders/inScattering_sup_calc_fs.glsl deleted file mode 100644 index 13551e5abe..0000000000 --- a/modules/base/shaders/inScattering_sup_calc_fs.glsl +++ /dev/null @@ -1,155 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#include "atmosphere_common.glsl" -#include "fragment.glsl" -#include "PowerScaling/powerScalingMath.hglsl" - -layout(location = 1) out vec4 renderTarget1; - -uniform float r; -uniform vec4 dhdH; - -uniform sampler2D transmittanceTexture; -uniform sampler3D deltaJTexture; - -void getMuMuSNu(const float r, vec4 dhdH, out float mu, out float mu_s, out float nu) { - float x = gl_FragCoord.x - 0.5; - float y = gl_FragCoord.y - 0.5; - if (y < float(RES_MU) / 2.0) { - float d = 1.0 - y / (float(RES_MU) / 2.0 - 1.0); - d = min(max(dhdH.z, d * dhdH.w), dhdH.w * 0.999); - mu = (Rg * Rg - r * r - d * d) / (2.0 * r * d); - mu = min(mu, -sqrt(1.0 - (Rg / r) * (Rg / r)) - 0.001); - } else { - float d = (y - float(RES_MU) / 2.0) / (float(RES_MU) / 2.0 - 1.0); - d = min(max(dhdH.x, d * dhdH.y), dhdH.y * 0.999); - mu = (Rt * Rt - r * r - d * d) / (2.0 * r * d); - } - mu_s = mod(x, float(RES_MU_S)) / (float(RES_MU_S) - 1.0); - mu_s = tan((2.0 * mu_s - 1.0 + 0.26) * 1.1) / tan(1.26 * 1.1); - nu = -1.0 + floor(x / float(RES_MU_S)) / (float(RES_NU) - 1.0) * 2.0; -} - -vec4 texture4D(sampler3D table, float r, float mu, float muS, float nu) -{ - float H = sqrt(Rt * Rt - Rg * Rg); - float rho = sqrt(r * r - Rg * Rg); - float rmu = r * mu; - float delta = rmu * rmu - r * r + Rg * Rg; - vec4 cst = rmu < 0.0 && delta > 0.0 ? vec4(1.0, 0.0, 0.0, 0.5 - 0.5 / float(RES_MU)) : vec4(-1.0, H * H, H, 0.5 + 0.5 / float(RES_MU)); - float uR = 0.5 / float(RES_R) + rho / H * (1.0 - 1.0 / float(RES_R)); - float uMu = cst.w + (rmu * cst.x + sqrt(delta + cst.y)) / (rho + cst.z) * (0.5 - 1.0 / float(RES_MU)); - float uMuS = 0.5 / float(RES_MU_S) + (atan(max(muS, -0.1975) * tan(1.26 * 1.1)) / 1.1 + (1.0 - 0.26)) * 0.5 * (1.0 - 1.0 / float(RES_MU_S)); - float lerp = (nu + 1.0) / 2.0 * (float(RES_NU) - 1.0); - float uNu = floor(lerp); - lerp = lerp - uNu; - return texture(table, vec3((uNu + uMuS) / float(RES_NU), uMu, uR)) * (1.0 - lerp) + - texture(table, vec3((uNu + uMuS + 1.0) / float(RES_NU), uMu, uR)) * lerp; -} - -float limit(float r, float mu) { - float dout = -r * mu + sqrt(r * r * (mu * mu - 1.0) + ((Rt+ATM_EPSILON) * (Rt+ATM_EPSILON))); - float delta2 = r * r * (mu * mu - 1.0) + Rg * Rg; - if (delta2 >= 0.0) { - float din = -r * mu - sqrt(delta2); - if (din >= 0.0) { - dout = min(dout, din); - } - } - return dout; -} - -vec3 transmittanceFromTexture(const float r, const float mu) { - float u_r = sqrt((r - Rg) / (Rt - Rg)); - // See Colliene to understand the different mapping. - float u_mu = atan((mu + 0.15) / (1.0 + 0.15) * tan(1.5)) / 1.5; - - return texture(transmittanceTexture, vec2(u_mu, u_r)).rgb; -} - -vec3 transmittance(const float r, const float mu, const float d) { - vec3 result; - float r1 = sqrt(r * r + d * d + 2.0 * r * mu * d); - float mu1 = (r * mu + d) / r1; - if (mu > 0.0) { - result = min(transmittanceFromTexture(r, mu) / - transmittanceFromTexture(r1, mu1), 1.0); - } else { - result = min(transmittanceFromTexture(r1, -mu1) / - transmittanceFromTexture(r, -mu), 1.0); - } - return result; -} - -vec3 integrand(float r, float mu, float muS, float nu, float t) { - float ri = sqrt(r * r + t * t + 2.0 * r * mu * t); - float mui = (r * mu + t) / ri; - float muSi = (nu * t + muS * r) / ri; - return texture4D(deltaJTexture, ri, mui, muSi, nu).rgb * transmittance(r, mu, t); -} - -float rayDistance(const float r, const float mu) { - // cosine law - float distanceAtmosphereIntersect = -r * mu + sqrt(r * r * (mu * mu - 1.0) + - (Rt + ATM_EPSILON)*(Rt + ATM_EPSILON)); - float distance = distanceAtmosphereIntersect; - float delta = r * r * (mu * mu - 1.0) + Rg * Rg; - // No imaginary numbers... :-) - if (delta >= 0.0) { - float distanceEarthIntersect = -r * mu - sqrt(delta); - if (distanceEarthIntersect >= 0.0) { - distance = min(distanceAtmosphereIntersect, distanceEarthIntersect); - } - } - return distance; -} - -vec3 inscatter(float r, float mu, float muS, float nu) { - vec3 raymie = vec3(0.0); - float dx = rayDistance(r, mu) / float(INSCATTER_INTEGRAL_SAMPLES); - float xi = 0.0; - vec3 raymiei = integrand(r, mu, muS, nu, 0.0); - for (int i = 1; i <= INSCATTER_INTEGRAL_SAMPLES; ++i) { - float xj = float(i) * dx; - vec3 raymiej = integrand(r, mu, muS, nu, xj); - raymie += (raymiei + raymiej) / 2.0 * dx; - xi = xj; - raymiei = raymiej; - } - return raymie; -} - -Fragment getFragment() { - float mu, muS, nu; - getMuMuSNu(r, dhdH, mu, muS, nu); - - renderTarget1 = vec4(inscatter(r, mu, muS, nu), 1.0); - - Fragment frag; - frag.color = vec4(1.0); - frag.depth = 1.0; - - return frag; -} \ No newline at end of file diff --git a/modules/base/shaders/inScattering_sup_calc_vs.glsl b/modules/base/shaders/inScattering_sup_calc_vs.glsl deleted file mode 100644 index 7e3574bd9d..0000000000 --- a/modules/base/shaders/inScattering_sup_calc_vs.glsl +++ /dev/null @@ -1,31 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#version __CONTEXT__ - -layout(location = 0) in vec3 in_position; - -void main() { - gl_Position = vec4(in_position, 1.0); -} \ No newline at end of file diff --git a/modules/base/shaders/irradiance_calc_vs.glsl b/modules/base/shaders/irradiance_calc_vs.glsl deleted file mode 100644 index 578d7ab02f..0000000000 --- a/modules/base/shaders/irradiance_calc_vs.glsl +++ /dev/null @@ -1,31 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#version __CONTEXT__ - -layout(location = 0) in vec3 in_position; - -void main() { - gl_Position = vec4(in_position, 1.0); -} \ No newline at end of file diff --git a/modules/base/shaders/irradiance_sup_calc_fs.glsl b/modules/base/shaders/irradiance_sup_calc_fs.glsl deleted file mode 100644 index cf87003e1c..0000000000 --- a/modules/base/shaders/irradiance_sup_calc_fs.glsl +++ /dev/null @@ -1,101 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#include "atmosphere_common.glsl" -#include "fragment.glsl" -#include "PowerScaling/powerScalingMath.hglsl" - -layout(location = 1) out vec4 renderTableColor; - -uniform float first; - -const float dphi = M_PI / float(IRRADIANCE_INTEGRAL_SAMPLES); -const float dtheta = M_PI / float(IRRADIANCE_INTEGRAL_SAMPLES); - -uniform sampler2D transmittanceTexture; -uniform sampler3D deltaSRTexture; -uniform sampler3D deltaSMTexture; - -// Rayleigh phase -float phaseFunctionR(const float mu) { - return (3.0 / (16.0 * M_PI)) * (1.0 + mu * mu); -} - -// Mie phase -float phaseFunctionM(const float mu) { - return (3.0 / (8.0 * M_PI)) * - ( ( (1.0 - (mieG*mieG) ) * (1+mu*mu) ) / - ( (2+mieG*mieG) * pow(1+mieG*mieG - 2.0*mieG*mu, 3.0/2.0) ) ); -} - -vec4 texture4D(sampler3D table, const float r, const float mu, - const float muS, const float nu) -{ - float H = sqrt(Rt * Rt - Rg * Rg); - float rho = sqrt(r * r - Rg * Rg); - float rmu = r * mu; - float delta = rmu * rmu - r * r + Rg * Rg; - vec4 cst = rmu < 0.0 && delta > 0.0 ? vec4(1.0, 0.0, 0.0, 0.5 - 0.5 / float(RES_MU)) : vec4(-1.0, H * H, H, 0.5 + 0.5 / float(RES_MU)); - float uR = 0.5 / float(RES_R) + rho / H * (1.0 - 1.0 / float(RES_R)); - float uMu = cst.w + (rmu * cst.x + sqrt(delta + cst.y)) / (rho + cst.z) * (0.5 - 1.0 / float(RES_MU)); - float uMuS = 0.5 / float(RES_MU_S) + (atan(max(muS, -0.1975) * tan(1.26 * 1.1)) / 1.1 + (1.0 - 0.26)) * 0.5 * (1.0 - 1.0 / float(RES_MU_S)); - float lerp = (nu + 1.0) / 2.0 * (float(RES_NU) - 1.0); - float uNu = floor(lerp); - lerp = lerp - uNu; - return texture(table, vec3((uNu + uMuS) / float(RES_NU), uMu, uR)) * (1.0 - lerp) + - texture(table, vec3((uNu + uMuS + 1.0) / float(RES_NU), uMu, uR)) * lerp; -} - -Fragment getFragment() { - float r = Rg + (gl_FragCoord.y - 0.5) / (float(SKY_H) - 1.0) * (Rt - Rg); - float mu_s = -0.2 + (gl_FragCoord.x - 0.5) / (float(SKY_W) - 1.0) * (1.0 + 0.2); - vec3 s = vec3(max(sqrt(1.0 - mu_s * mu_s), 0.0), 0.0, mu_s); - - vec3 result = vec3(0.0); - for (int iphi = 0; iphi < 2 * IRRADIANCE_INTEGRAL_SAMPLES; ++iphi) { - float phi = (float(iphi) + 0.5) * dphi; - for (int itheta = 0; itheta < IRRADIANCE_INTEGRAL_SAMPLES / 2; ++itheta) { - float theta = (float(itheta) + 0.5) * dtheta; - float dw = dtheta * dphi * sin(theta); - vec3 w = vec3(cos(phi) * sin(theta), sin(phi) * sin(theta), cos(theta)); - float nu = dot(s, w); - if (first == 1.0) { - float pr1 = phaseFunctionR(nu); - float pm1 = phaseFunctionM(nu); - vec3 ray1 = texture4D(deltaSRTexture, r, w.z, mu_s, nu).rgb; - vec3 mie1 = texture4D(deltaSMTexture, r, w.z, mu_s, nu).rgb; - result += (ray1 * pr1 + mie1 * pm1) * w.z * dw; - } else { - result += texture4D(deltaSRTexture, r, w.z, mu_s, nu).rgb * w.z * dw; - } - } - } - - renderTableColor = vec4(result, 0.0); - Fragment frag; - frag.color = vec4(1.0); - frag.depth = 1.0; - - return frag; -} \ No newline at end of file diff --git a/modules/base/shaders/irradiance_sup_calc_vs.glsl b/modules/base/shaders/irradiance_sup_calc_vs.glsl deleted file mode 100644 index 578d7ab02f..0000000000 --- a/modules/base/shaders/irradiance_sup_calc_vs.glsl +++ /dev/null @@ -1,31 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#version __CONTEXT__ - -layout(location = 0) in vec3 in_position; - -void main() { - gl_Position = vec4(in_position, 1.0); -} \ No newline at end of file diff --git a/modules/base/shaders/path_fs.glsl b/modules/base/shaders/path_fs.glsl index b4aacad237..f2c701ae64 100644 --- a/modules/base/shaders/path_fs.glsl +++ b/modules/base/shaders/path_fs.glsl @@ -30,8 +30,8 @@ in vec4 vs_pointColor; Fragment getFragment() { - if (vs_pointColor.a < 0.01) - discard; + if (vs_pointColor.a < 0.01) + discard; Fragment frag; frag.color = vs_pointColor; frag.depth = vs_positionScreenSpace.w; diff --git a/modules/base/shaders/irradiance_calc_fs.glsl b/modules/base/shaders/renderabletrail_fs.glsl similarity index 67% rename from modules/base/shaders/irradiance_calc_fs.glsl rename to modules/base/shaders/renderabletrail_fs.glsl index 329fe2de7d..288aa5dc12 100644 --- a/modules/base/shaders/irradiance_calc_fs.glsl +++ b/modules/base/shaders/renderabletrail_fs.glsl @@ -22,36 +22,46 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include "atmosphere_common.glsl" +// Fragile! Keep in sync with RenderableTrail::render::RenderPhase +#define RenderPhaseLines 0 +#define RenderPhasePoints 1 + +#define Delta 0.25 + +in vec4 vs_positionScreenSpace; +in float fade; + +uniform vec3 color; +uniform int renderPhase; + #include "fragment.glsl" -#include "PowerScaling/powerScalingMath.hglsl" - -layout(location = 1) out vec4 renderTableColor; - -uniform sampler2D transmittanceTexture; - -void getRAndMu(out float r, out float mu) { - // See Bruneton and Colliene to understand the mapping. - mu = -0.2 + (gl_FragCoord.x - 0.5) / (float(OTHER_TEXTURES_W) - 1.0) * (1.0 + 0.2); - r = Rg + (gl_FragCoord.y - 0.5) / (float(OTHER_TEXTURES_H) - 1.0) * (Rt - Rg); -} - -vec3 transmittance(const float r, const float mu) { - float u_r = sqrt((r - Rg) / (Rt - Rg)); - // See Colliene to understand the different mapping. - float u_mu = atan((mu + 0.15) / (1.0 + 0.15) * tan(1.5)) / 1.5; - - return texture(transmittanceTexture, vec2(u_mu, u_r)).rgb; -} Fragment getFragment() { - float mu, r; - getRAndMu(r, mu); - renderTableColor = vec4(transmittance(r, mu) * max(mu, 0.0), 1.0); - Fragment frag; - frag.color = vec4(1.0); - frag.depth = 1.0; - + frag.color = vec4(color * fade, fade); + frag.depth = vs_positionScreenSpace.w; + frag.blend = BLEND_MODE_ADDITIVE; + + if (renderPhase == RenderPhasePoints) { + // Use the length of the vector (dot(circCoord, circCoord)) as factor in the + // smoothstep to gradually decrease the alpha on the edges of the point + vec2 circCoord = 2.0 * gl_PointCoord - 1.0; + frag.color.a *= 1.0 - smoothstep(1.0 - Delta, 1.0, dot(circCoord, circCoord)); + + + + // if (dot(circCoord, circCoord) > 1.0) { + + // } + // frag.color.a *= smoothstep(); + + // // Check for length > 1.0 without a square root + // frag.color.a *= smoothstep(dot(circCoord, circCoord), 1.0, 1.0 - 1.0 / pointSize); + // if (dot(circCoord, circCoord) > 1.0) { + // discard; + // } + } + + return frag; -} \ No newline at end of file +} diff --git a/modules/base/shaders/deltaJ_calc_vs.glsl b/modules/base/shaders/renderabletrail_vs.glsl similarity index 60% rename from modules/base/shaders/deltaJ_calc_vs.glsl rename to modules/base/shaders/renderabletrail_vs.glsl index 578d7ab02f..2db1690fda 100644 --- a/modules/base/shaders/deltaJ_calc_vs.glsl +++ b/modules/base/shaders/renderabletrail_vs.glsl @@ -24,8 +24,56 @@ #version __CONTEXT__ -layout(location = 0) in vec3 in_position; +// Fragile! Keep in sync with RenderableTrail::render +#define VERTEX_SORTING_NEWESTFIRST 0 +#define VERTEX_SORTING_OLDESTFIRST 1 +#define VERTEX_SORTING_NOSORTING 2 + +layout(location = 0) in vec3 in_point_position; + +out vec4 vs_positionScreenSpace; +out float fade; + +uniform dmat4 modelViewTransform; +uniform mat4 projectionTransform; + +uniform int idOffset; +uniform int nVertices; +uniform bool useLineFade; +uniform float lineFade; +uniform int vertexSortingMethod; +uniform int pointSize; +uniform int stride; + +#include "PowerScaling/powerScaling_vs.hglsl" void main() { - gl_Position = vec4(in_position, 1.0); -} \ No newline at end of file + int modId = gl_VertexID; + + if ((vertexSortingMethod != VERTEX_SORTING_NOSORTING) && useLineFade) { + // Account for a potential rolling buffer + modId = gl_VertexID - idOffset; + if (modId < 0) { + modId += nVertices; + } + + // Convert the index to a [0,1] ranger + float id = float(modId) / float(nVertices); + + if (vertexSortingMethod == VERTEX_SORTING_NEWESTFIRST) { + id = 1.0 - id; + } + + fade = clamp(id * lineFade, 0.0, 1.0); + } + else { + fade = 1.0; + } + + vs_positionScreenSpace = z_normalization( + projectionTransform * vec4(modelViewTransform * dvec4(in_point_position, 1)) + ); + + gl_PointSize = (stride == 1 || int(modId) % stride == 0) ? float(pointSize) : float(pointSize) / 2; + gl_Position = vs_positionScreenSpace; +} diff --git a/modules/base/shaders/transmittance_calc_fs.glsl b/modules/base/shaders/transmittance_calc_fs.glsl deleted file mode 100644 index 7270a1d1f2..0000000000 --- a/modules/base/shaders/transmittance_calc_fs.glsl +++ /dev/null @@ -1,109 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#include "atmosphere_common.glsl" -#include "fragment.glsl" -#include "PowerScaling/powerScalingMath.hglsl" - -layout(location = 1) out vec4 renderTableColor; - -// In the following shaders r (altitude) is the length of vector/position x in the -// atmosphere (or on the top of it when considering an observer in space), -// where the light is comming from the opposity direction of the view direction, -// here the vector v or viewDirection. -// Rg is the planet radius - -float rayDistance(const float r, const float mu) { - // cosine law - float distanceAtmosphereIntersect = -r * mu + sqrt(r * r * (mu * mu - 1.0) + - (Rt + ATM_EPSILON)*(Rt + ATM_EPSILON)); - float distance = distanceAtmosphereIntersect; - float delta = r * r * (mu * mu - 1.0) + Rg * Rg; - // No imaginary numbers... :-) - if (delta >= 0.0) { - float distanceEarthIntersect = -r * mu - sqrt(delta); - if (distanceEarthIntersect >= 0.0) { - distance = min(distanceAtmosphereIntersect, distanceEarthIntersect); - } - } - return distance; -} - -float opticalDepth(const float r, const float mu, const float scaleHeight) { - - float r2 = r*r; - // Is ray below horizon? - // cosine law for triangles: y_i^2 = a^2 + b^2 - 2abcos(alpha) - float cosZenithHorizon = -sqrt(1.0 - ((Rg*Rg)/r2)); - if (mu < cosZenithHorizon) - return 1e9; - - // Integrating using the Trapezoidal rule: - // Integral(f(y)dy)(from a to b) = (b-a)/2n_steps*(Sum(f(y_i+1)+f(y_i))) - float b_a = rayDistance(r, mu); - float deltaStep = b_a / float(TRANSMITTANCE_STEPS); - // cosine law - float y_i = exp(-(r - Rg) / scaleHeight); - - float x_step = 0.0; - float accumulation = 0.0; - for (int i = 1; i <= TRANSMITTANCE_STEPS; ++i) { - float x_i = float(i) * deltaStep; - // cosine law for triangles: y_i^2 = a^2 + b^2 - 2abcos(alpha) - // In this case, a = r, b = x_i and cos(alpha) = cos(PI-zenithView) = mu - float y_ii = exp(-(sqrt(r2 + x_i * x_i + 2.0 * x_i * r * mu) - Rg) / scaleHeight); - accumulation += (y_ii + y_i); - //x_step = x_i; - y_i = y_ii; - } - return accumulation * (b_a/(2*TRANSMITTANCE_STEPS)); -} - -void getRandMU(out float r, out float mu) { - float u_mu = gl_FragCoord.x / float(TRANSMITTANCE_W); - float u_r = gl_FragCoord.y / float(TRANSMITTANCE_H); - - // In the paper u_r^2 = (r^2-Rg^2)/(Rt^2-Rg^2) - r = sqrt(Rg*Rg + (u_r * u_r) * (Rt*Rt - Rg*Rg)); - - // In the paper the author suggest mu = dot(v,x)/||x|| with ||v|| = 1.0 - // Later he proposes u_mu = (1-exp(-3mu-0.6))/(1-exp(-3.6)) - // But the below one is better. See Colliene. - mu = -0.15 + tan(1.5 * u_mu) / tan(1.5) * (1.0 + 0.15); -} - -Fragment getFragment() { - float r, mu; - - getRandMU(r, mu); - vec3 depth = betaMEx * opticalDepth(r, mu, HM) + betaR * opticalDepth(r, mu, HR); - - renderTableColor = vec4(exp(-depth), 1.0); - - Fragment frag; - frag.color = vec4(1.0); - frag.depth = 1.0; - - return frag; -} \ No newline at end of file diff --git a/modules/base/shaders/transmittance_calc_vs.glsl b/modules/base/shaders/transmittance_calc_vs.glsl deleted file mode 100644 index 578d7ab02f..0000000000 --- a/modules/base/shaders/transmittance_calc_vs.glsl +++ /dev/null @@ -1,31 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#version __CONTEXT__ - -layout(location = 0) in vec3 in_position; - -void main() { - gl_Position = vec4(in_position, 1.0); -} \ No newline at end of file diff --git a/modules/base/ephemeris/staticephemeris.cpp b/modules/base/translation/statictranslation.cpp similarity index 86% rename from modules/base/ephemeris/staticephemeris.cpp rename to modules/base/translation/statictranslation.cpp index 551da7a05c..e0e3e85b42 100644 --- a/modules/base/ephemeris/staticephemeris.cpp +++ b/modules/base/translation/statictranslation.cpp @@ -22,17 +22,17 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include +#include #include namespace { - const std::string KeyPosition = "Position"; + const char* KeyPosition = "Position"; } namespace openspace { -Documentation StaticEphemeris::Documentation() { +Documentation StaticTranslation::Documentation() { using namespace openspace::documentation; return { "Static Translation", @@ -40,7 +40,7 @@ Documentation StaticEphemeris::Documentation() { { { "Type", - new StringEqualVerifier("StaticEphemeris"), + new StringEqualVerifier("StaticTranslation"), "", Optional::No }, @@ -57,7 +57,7 @@ Documentation StaticEphemeris::Documentation() { } -StaticEphemeris::StaticEphemeris() +StaticTranslation::StaticTranslation() : _position( "position", "Position", @@ -69,8 +69,8 @@ StaticEphemeris::StaticEphemeris() addProperty(_position); } -StaticEphemeris::StaticEphemeris(const ghoul::Dictionary& dictionary) - : StaticEphemeris() +StaticTranslation::StaticTranslation(const ghoul::Dictionary& dictionary) + : StaticTranslation() { documentation::testSpecificationAndThrow( Documentation(), @@ -81,12 +81,12 @@ StaticEphemeris::StaticEphemeris(const ghoul::Dictionary& dictionary) _position = dictionary.value(KeyPosition); } -StaticEphemeris::~StaticEphemeris() {} +StaticTranslation::~StaticTranslation() {} -glm::dvec3 StaticEphemeris::position() const { +glm::dvec3 StaticTranslation::position() const { return _position; } -void StaticEphemeris::update(const UpdateData&) {} +void StaticTranslation::update(const UpdateData&) {} } // namespace openspace diff --git a/modules/base/ephemeris/staticephemeris.h b/modules/base/translation/statictranslation.h similarity index 84% rename from modules/base/ephemeris/staticephemeris.h rename to modules/base/translation/statictranslation.h index d85f3eba41..a699497888 100644 --- a/modules/base/ephemeris/staticephemeris.h +++ b/modules/base/translation/statictranslation.h @@ -22,21 +22,21 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __STATICEPHEMERIS_H__ -#define __STATICEPHEMERIS_H__ +#ifndef __OPENSPACE_MODULE_BASE___STATICTRANSLATION___H__ +#define __OPENSPACE_MODULE_BASE___STATICTRANSLATION___H__ -#include +#include #include -#include +#include namespace openspace { -class StaticEphemeris : public Ephemeris { +class StaticTranslation : public Translation { public: - StaticEphemeris(); - StaticEphemeris(const ghoul::Dictionary& dictionary); - virtual ~StaticEphemeris(); + StaticTranslation(); + StaticTranslation(const ghoul::Dictionary& dictionary); + virtual ~StaticTranslation(); virtual glm::dvec3 position() const; virtual void update(const UpdateData& data) override; @@ -48,4 +48,4 @@ private: } // namespace openspace -#endif // __STATICEPHEMERIS_H__ +#endif // __OPENSPACE_MODULE_BASE___STATICTRANSLATION___H__ diff --git a/modules/debugging/debuggingmodule.h b/modules/debugging/debuggingmodule.h index 8a33551351..8ea478a4d0 100644 --- a/modules/debugging/debuggingmodule.h +++ b/modules/debugging/debuggingmodule.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __DEBUGGINGMODULE_H__ -#define __DEBUGGINGMODULE_H__ +#ifndef __OPENSPACE_MODULE_BASE___DEBUGGINGMODULE___H__ +#define __OPENSPACE_MODULE_BASE___DEBUGGINGMODULE___H__ #include @@ -39,4 +39,4 @@ protected: } // namespace openspace -#endif // __DEBUGGINGMODULE_H__ +#endif // __OPENSPACE_MODULE_BASE___DEBUGGINGMODULE___H__ diff --git a/modules/debugging/rendering/debugrenderer.cpp b/modules/debugging/rendering/debugrenderer.cpp index 26b161daff..de3305a842 100644 --- a/modules/debugging/rendering/debugrenderer.cpp +++ b/modules/debugging/rendering/debugrenderer.cpp @@ -41,215 +41,233 @@ namespace { namespace openspace { - DebugRenderer* DebugRenderer::_reference = nullptr; +DebugRenderer* DebugRenderer::_reference = nullptr; - DebugRenderer::DebugRenderer() { - _programObject = OsEng.renderEngine().buildRenderProgram( - "BasicDebugShader", - "${MODULE_DEBUGGING}/rendering/debugshader_vs.glsl", - "${MODULE_DEBUGGING}/rendering/debugshader_fs.glsl" - ); - } +DebugRenderer::DebugRenderer() { + _programObject = OsEng.renderEngine().buildRenderProgram( + "BasicDebugShader", + "${MODULE_DEBUGGING}/rendering/debugshader_vs.glsl", + "${MODULE_DEBUGGING}/rendering/debugshader_fs.glsl" + ); +} - DebugRenderer::DebugRenderer(std::unique_ptr programObject) - : _programObject(std::move(programObject)) - { - // nothing to do - } +DebugRenderer::DebugRenderer(std::unique_ptr programObject) + : _programObject(std::move(programObject)) +{ + // nothing to do +} - DebugRenderer::~DebugRenderer() - { - // nothing to do - } +DebugRenderer::~DebugRenderer() +{ + // nothing to do +} - const DebugRenderer& DebugRenderer::ref() { - if (_reference == nullptr) { - try { - _reference = new DebugRenderer(); - } - catch (const ShaderObject::ShaderCompileError& e) { - LERROR(e.what()); - } +const DebugRenderer& DebugRenderer::ref() { + if (_reference == nullptr) { + try { + _reference = new DebugRenderer(); } - return *_reference; + catch (const ghoul::opengl::ShaderObject::ShaderCompileError& e) { + LERROR(e.what()); + } + } + return *_reference; +} + +void DebugRenderer::renderVertices(const Vertices& clippingSpacePoints, GLenum mode, + RGBA rgba) const +{ + if (clippingSpacePoints.size() == 0) { + // nothing to render + return; } - void DebugRenderer::renderVertices(const Vertices& clippingSpacePoints, GLenum mode, RGBA rgba) const { - if (clippingSpacePoints.size() == 0) { - // nothing to render - return; - } + // Generate a vao, vertex array object (keeping track of pointers to vbo) + GLuint _vaoID; + glGenVertexArrays(1, &_vaoID); + ghoul_assert(_vaoID != 0, "Could not generate vertex arrays"); - // Generate a vao, vertex array object (keeping track of pointers to vbo) - GLuint _vaoID; - glGenVertexArrays(1, &_vaoID); - ghoul_assert(_vaoID != 0, "Could not generate vertex arrays"); + // Generate a vbo, vertex buffer object (storeing actual data) + GLuint _vertexBufferID; + glGenBuffers(1, &_vertexBufferID); + ghoul_assert(_vertexBufferID != 0, "Could not create vertex buffer"); - // Generate a vbo, vertex buffer object (storeing actual data) - GLuint _vertexBufferID; - glGenBuffers(1, &_vertexBufferID); - ghoul_assert(_vertexBufferID != 0, "Could not create vertex buffer"); + // Activate the shader program and set the uniform color within the shader + _programObject->activate(); + _programObject->setUniform("color", rgba); - // Activate the shader program and set the uniform color within the shader - _programObject->activate(); - _programObject->setUniform("color", rgba); - - glBindVertexArray(_vaoID); - glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferID); - glBufferData( - GL_ARRAY_BUFFER, - clippingSpacePoints.size() * sizeof(clippingSpacePoints[0]), - &clippingSpacePoints[0], - GL_STATIC_DRAW); + glBindVertexArray(_vaoID); + glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferID); + glBufferData( + GL_ARRAY_BUFFER, + clippingSpacePoints.size() * sizeof(clippingSpacePoints[0]), + &clippingSpacePoints[0], + GL_STATIC_DRAW); - glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(clippingSpacePoints[0]), 0); + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(clippingSpacePoints[0]), 0); - // Draw the vertices - glDrawArrays(mode, 0, clippingSpacePoints.size()); + // Draw the vertices + glDrawArrays(mode, 0, clippingSpacePoints.size()); - // Check for errors - GLenum error = glGetError(); - if (error != GL_NO_ERROR) { - LERROR(error); - } + // Check for errors + GLenum error = glGetError(); + if (error != GL_NO_ERROR) { + // Commenting this line. It causes errors to be printed. However + // the errors are not caused by DebugRenderer!! + //LERROR(error); + } - // Clean up after the draw call was made - glBindVertexArray(0); - glDeleteVertexArrays(1, &_vaoID); - glDeleteBuffers(1, &_vertexBufferID); - _programObject->deactivate(); - } + // Clean up after the draw call was made + glBindVertexArray(0); + glDeleteVertexArrays(1, &_vaoID); + glDeleteBuffers(1, &_vertexBufferID); + _programObject->deactivate(); +} - void DebugRenderer::renderBoxFaces(const Vertices& clippingSpaceBoxCorners, RGBA rgba) const { - ghoul_assert(clippingSpaceBoxCorners.size() == 8, "Box must have 8 vertices"); - const Vertices& V = clippingSpaceBoxCorners; +void DebugRenderer::renderBoxFaces(const Vertices& clippingSpaceBoxCorners, + RGBA rgba) const +{ + ghoul_assert(clippingSpaceBoxCorners.size() == 8, "Box must have 8 vertices"); + const Vertices& V = clippingSpaceBoxCorners; - std::vector T; + std::vector T; - // add "sides" - T.push_back(V[1]); T.push_back(V[0]); T.push_back(V[4]); - T.push_back(V[4]); T.push_back(V[5]); T.push_back(V[1]); + // add "sides" + T.push_back(V[1]); T.push_back(V[0]); T.push_back(V[4]); + T.push_back(V[4]); T.push_back(V[5]); T.push_back(V[1]); - T.push_back(V[3]); T.push_back(V[1]); T.push_back(V[5]); - T.push_back(V[5]); T.push_back(V[7]); T.push_back(V[3]); + T.push_back(V[3]); T.push_back(V[1]); T.push_back(V[5]); + T.push_back(V[5]); T.push_back(V[7]); T.push_back(V[3]); - T.push_back(V[6]); T.push_back(V[3]); T.push_back(V[7]); - T.push_back(V[3]); T.push_back(V[6]); T.push_back(V[2]); + T.push_back(V[6]); T.push_back(V[3]); T.push_back(V[7]); + T.push_back(V[3]); T.push_back(V[6]); T.push_back(V[2]); - T.push_back(V[4]); T.push_back(V[2]); T.push_back(V[6]); - T.push_back(V[2]); T.push_back(V[4]); T.push_back(V[0]); + T.push_back(V[4]); T.push_back(V[2]); T.push_back(V[6]); + T.push_back(V[2]); T.push_back(V[4]); T.push_back(V[0]); - // add "top" - T.push_back(V[5]); T.push_back(V[6]); T.push_back(V[7]); - T.push_back(V[6]); T.push_back(V[5]); T.push_back(V[4]); + // add "top" + T.push_back(V[5]); T.push_back(V[6]); T.push_back(V[7]); + T.push_back(V[6]); T.push_back(V[5]); T.push_back(V[4]); - // add bottom - T.push_back(V[0]); T.push_back(V[1]); T.push_back(V[2]); - T.push_back(V[3]); T.push_back(V[2]); T.push_back(V[1]); + // add bottom + T.push_back(V[0]); T.push_back(V[1]); T.push_back(V[2]); + T.push_back(V[3]); T.push_back(V[2]); T.push_back(V[1]); - renderVertices(T, GL_TRIANGLES, rgba); - } + renderVertices(T, GL_TRIANGLES, rgba); +} - void DebugRenderer::renderBoxEdges(const Vertices& clippingSpaceBoxCorners, RGBA rgba) const { - ghoul_assert(clippingSpaceBoxCorners.size() == 8, "Box must have 8 vertices"); - const Vertices& V = clippingSpaceBoxCorners; +void DebugRenderer::renderBoxEdges(const Vertices& clippingSpaceBoxCorners, + RGBA rgba) const +{ + ghoul_assert(clippingSpaceBoxCorners.size() == 8, "Box must have 8 vertices"); + const Vertices& V = clippingSpaceBoxCorners; - std::vector lineVertices; + std::vector lineVertices; - for (size_t i = 0; i < 4; i++) { - lineVertices.push_back(V[2 * i]); - lineVertices.push_back(V[2 * i + 1]); - lineVertices.push_back(V[i]); - lineVertices.push_back(V[i + 4]); + for (size_t i = 0; i < 4; i++) { + lineVertices.push_back(V[2 * i]); + lineVertices.push_back(V[2 * i + 1]); + lineVertices.push_back(V[i]); + lineVertices.push_back(V[i + 4]); + } + lineVertices.push_back(V[0]); lineVertices.push_back(V[2]); + lineVertices.push_back(V[1]); lineVertices.push_back(V[3]); + lineVertices.push_back(V[4]); lineVertices.push_back(V[6]); + lineVertices.push_back(V[5]); lineVertices.push_back(V[7]); + + DebugRenderer::ref().renderVertices(lineVertices, GL_LINES, rgba); +} + +void DebugRenderer::renderNiceBox(const Vertices& clippingSpaceBoxCorners, + RGBA rgba) const +{ + renderBoxFaces(clippingSpaceBoxCorners, rgba); + + glLineWidth(4.0f); + DebugRenderer::ref().renderBoxEdges(clippingSpaceBoxCorners, rgba); + + glPointSize(10.0f); + DebugRenderer::ref().renderVertices(clippingSpaceBoxCorners, GL_POINTS, rgba); +} + +void DebugRenderer::renderCameraFrustum(const RenderData& data, const Camera& otherCamera, + RGBA rgba) const +{ + using namespace glm; + dmat4 modelTransform = translate(dmat4(1), data.position.dvec3()); + dmat4 viewTransform = dmat4(data.camera.combinedViewMatrix()); + dmat4 vp = dmat4(data.camera.projectionMatrix()) * viewTransform; + + dmat4 inverseSavedV = glm::inverse(otherCamera.combinedViewMatrix()); + dmat4 inverseSavedP = glm::inverse(otherCamera.projectionMatrix()); + Vertices clippingSpaceFrustumCorners(8); + // loop through the corners of the saved camera frustum + for (size_t i = 0; i < 8; i++) { + bool cornerIsRight = i % 2 == 0; + bool cornerIsUp = i > 3; + bool cornerIsFar = (i / 2) % 2 == 1; + + double x = cornerIsRight ? 1 : -1; + double y = cornerIsUp ? 1 : -1; + double z = cornerIsFar ? 1 : 0; + + // p represents a corner in the frustum of the saved camera + dvec4 pSavedClippingSpace(x, y, z, 1); + dvec4 pSavedCameraSpace = inverseSavedP * pSavedClippingSpace; + if (cornerIsFar) { + pSavedCameraSpace.w *= 1e-7; } - lineVertices.push_back(V[0]); lineVertices.push_back(V[2]); - lineVertices.push_back(V[1]); lineVertices.push_back(V[3]); - lineVertices.push_back(V[4]); lineVertices.push_back(V[6]); - lineVertices.push_back(V[5]); lineVertices.push_back(V[7]); + pSavedCameraSpace = glm::abs(1.0 / pSavedCameraSpace.w) * pSavedCameraSpace; - DebugRenderer::ref().renderVertices(lineVertices, GL_LINES, rgba); + dvec4 pWorldSpace = inverseSavedV * pSavedCameraSpace; + dvec4 pCurrentClippingSpace = vp * pWorldSpace; + clippingSpaceFrustumCorners[i] = pCurrentClippingSpace; } - void DebugRenderer::renderNiceBox(const Vertices& clippingSpaceBoxCorners, RGBA rgba) const { - renderBoxFaces(clippingSpaceBoxCorners, rgba); - glLineWidth(4.0f); - DebugRenderer::ref().renderBoxEdges(clippingSpaceBoxCorners, rgba); - - glPointSize(10.0f); - DebugRenderer::ref().renderVertices(clippingSpaceBoxCorners, GL_POINTS, rgba); - } - - void DebugRenderer::renderCameraFrustum(const RenderData& data, const Camera& otherCamera, RGBA rgba) const { - using namespace glm; - dmat4 modelTransform = translate(dmat4(1), data.position.dvec3()); - dmat4 viewTransform = dmat4(data.camera.combinedViewMatrix()); - dmat4 vp = dmat4(data.camera.projectionMatrix()) * viewTransform; - - dmat4 inverseSavedV = glm::inverse(otherCamera.combinedViewMatrix()); - dmat4 inverseSavedP = glm::inverse(otherCamera.projectionMatrix()); - Vertices clippingSpaceFrustumCorners(8); - // loop through the corners of the saved camera frustum - for (size_t i = 0; i < 8; i++) { - bool cornerIsRight = i % 2 == 0; - bool cornerIsUp = i > 3; - bool cornerIsFar = (i / 2) % 2 == 1; - - double x = cornerIsRight ? 1 : -1; - double y = cornerIsUp ? 1 : -1; - double z = cornerIsFar ? 1 : 0; - - // p represents a corner in the frustum of the saved camera - dvec4 pSavedClippingSpace(x, y, z, 1); - dvec4 pSavedCameraSpace = inverseSavedP * pSavedClippingSpace; - if (cornerIsFar) { - pSavedCameraSpace.w *= 1e-7; - } - pSavedCameraSpace = glm::abs(1.0 / pSavedCameraSpace.w) * pSavedCameraSpace; - - dvec4 pWorldSpace = inverseSavedV * pSavedCameraSpace; - dvec4 pCurrentClippingSpace = vp * pWorldSpace; - clippingSpaceFrustumCorners[i] = pCurrentClippingSpace; - } - - - glDisable(GL_CULL_FACE); - renderNiceBox(clippingSpaceFrustumCorners, rgba); - glEnable(GL_CULL_FACE); - } + glDisable(GL_CULL_FACE); + renderNiceBox(clippingSpaceFrustumCorners, rgba); + glEnable(GL_CULL_FACE); +} - void DebugRenderer::renderAABB2(const AABB2& screenSpaceAABB, RGBA rgba) const { - Vertices vertices(4); - vertices[0] = vec4(screenSpaceAABB.min.x, screenSpaceAABB.min.y, 1, 1); - vertices[1] = vec4(screenSpaceAABB.min.x, screenSpaceAABB.max.y, 1, 1); - vertices[2] = vec4(screenSpaceAABB.max.x, screenSpaceAABB.min.y, 1, 1); - vertices[3] = vec4(screenSpaceAABB.max.x, screenSpaceAABB.max.y, 1, 1); +#ifdef OPENSPACE_MODULE_GLOBEBROWSING_ENABLED +void DebugRenderer::renderAABB2(const globebrowsing::AABB2& screenSpaceAABB, + RGBA rgba) const +{ + Vertices vertices(4); + vertices[0] = glm::vec4(screenSpaceAABB.min.x, screenSpaceAABB.min.y, 1, 1); + vertices[1] = glm::vec4(screenSpaceAABB.min.x, screenSpaceAABB.max.y, 1, 1); + vertices[2] = glm::vec4(screenSpaceAABB.max.x, screenSpaceAABB.min.y, 1, 1); + vertices[3] = glm::vec4(screenSpaceAABB.max.x, screenSpaceAABB.max.y, 1, 1); - renderVertices(vertices, GL_LINES, rgba); + renderVertices(vertices, GL_LINES, rgba); +} +#endif // OPENSPACE_MODULE_GLOBEBROWSING_ENABLED + +#ifdef OPENSPACE_MODULE_GLOBEBROWSING_ENABLED +const DebugRenderer::Vertices DebugRenderer::verticesFor( + const globebrowsing::AABB3& screenSpaceAABB) const +{ + Vertices vertices(8); + for (size_t i = 0; i < 8; i++) { + bool cornerIsRight = i % 2 == 0; + bool cornerIsUp = i > 3; + bool cornerIsFar = (i / 2) % 2 == 1; + + double x = cornerIsRight ? screenSpaceAABB.max.x : screenSpaceAABB.min.x; + double y = cornerIsUp ? screenSpaceAABB.max.y : screenSpaceAABB.min.y; + double z = cornerIsFar ? screenSpaceAABB.max.z : screenSpaceAABB.min.z; + + vertices[i] = glm::vec4(x, y, z, 1); } - - const DebugRenderer::Vertices DebugRenderer::verticesFor(const AABB3& screenSpaceAABB) const { - Vertices vertices(8); - for (size_t i = 0; i < 8; i++) { - bool cornerIsRight = i % 2 == 0; - bool cornerIsUp = i > 3; - bool cornerIsFar = (i / 2) % 2 == 1; - - double x = cornerIsRight ? screenSpaceAABB.max.x : screenSpaceAABB.min.x; - double y = cornerIsUp ? screenSpaceAABB.max.y : screenSpaceAABB.min.y; - double z = cornerIsFar ? screenSpaceAABB.max.z : screenSpaceAABB.min.z; - - vertices[i] = vec4(x, y, z, 1); - } - return std::move(vertices); - } - + return std::move(vertices); +} +#endif // OPENSPACE_MODULE_GLOBEBROWSING_ENABLED } // namespace openspace - diff --git a/modules/debugging/rendering/debugrenderer.h b/modules/debugging/rendering/debugrenderer.h index 52082cfcc7..95e143e87c 100644 --- a/modules/debugging/rendering/debugrenderer.h +++ b/modules/debugging/rendering/debugrenderer.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __DEBUG_RENDERER_H__ -#define __DEBUG_RENDERER_H__ +#ifndef __OPENSPACE_MODULE_BASE___DEBUGRENDERER___H__ +#define __OPENSPACE_MODULE_BASE___DEBUGRENDERER___H__ #include #include @@ -36,121 +36,130 @@ #include #include - - #include namespace openspace { - using namespace ghoul::opengl; + +/** + * A helper class for quick rendering of vertices IN clipping space. + * The class is practically stateless. It only stores a ghoul::opengl::ProgramObject + * which can be reused despite the fact that rendering calls are invoked from different + * callers. Therefore a static reference is provided for convenience which is accessed + * through ref(). Note: That constructors are still public and the class is not a strict + * singleton. + */ +class DebugRenderer { +public: + typedef std::vector Vertices; + typedef glm::vec4 RGBA; /** - A helper class for quick rendering of vertices IN clipping space. + * Consider using ref() before creating a new default instance! + */ + DebugRenderer(); - The class is practically stateless. It only stores a ghoul::opengl::ProgramObject - which can be reused despite the fact that rendering calls are invoked from different callers. - Therefor a static reference is provided for convenience which is accessed through ref(). Note: - That constructors are still public and the class is not a strict singleton. - */ - class DebugRenderer { - public: - typedef std::vector Vertices; - typedef glm::vec4 RGBA; + /** + * Instantiate a new DebugRenderer with a custom shader program + */ + DebugRenderer(std::unique_ptr programObject); + ~DebugRenderer(); - /** - * Consider using ref() before creating a new default instance! - */ - DebugRenderer(); + /** + * Access the static reference + */ + static const DebugRenderer& ref(); - /** - * Instantiate a new DebugRenderer with a custom shader program - */ - DebugRenderer(std::unique_ptr programObject); - ~DebugRenderer(); + /** + * Render the vector of clipping space points in the specified mode and color. + */ + void renderVertices(const Vertices& clippingSpacePoints, GLenum mode, + RGBA color = {1, 0, 0, 1}) const; - /** - * Access the static reference - */ - static const DebugRenderer& ref(); - - /** - * Render the vector of clipping space points in the specified mode and color. - */ - void renderVertices(const Vertices& clippingSpacePoints, GLenum mode, RGBA = {1, 0, 0, 1}) const; - - /** - * Takes a vector of exactly 8 vertices, i.e. corner points in a box. - * The box corners should be ordered from smaller to larger, - * first by x, the, y and finally z. - * - * 6-------7 - * |\ |\ - * | 2-------3 - * 4 | - - 5 | - * \| \| - * 0-------1 - * - */ - void renderBoxFaces(const Vertices& clippingSpaceBoxCorners, RGBA rgba = { 1, 0, 0, 1 }) const; + /** + * Takes a vector of exactly 8 vertices, i.e. corner points in a box. + * The box corners should be ordered from smaller to larger, + * first by x, the, y and finally z. + * + * 6-------7 + * |\ |\ + * | 2-------3 + * 4 | - - 5 | + * \| \| + * 0-------1 + * + */ + void renderBoxFaces(const Vertices& clippingSpaceBoxCorners, + RGBA rgba = { 1, 0, 0, 1 }) const; - /** - * Takes a vector of exactly 8 vertices, i.e. corner points in a box. - * The box corners should be ordered from smaller to larger, - * first by x, the, y and finally z. - * - * 6-------7 - * |\ |\ - * | 2-------3 - * 4 | - - 5 | - * \| \| - * 0-------1 - * - */ - void renderBoxEdges(const Vertices& clippingSpaceBoxCorners, RGBA rgba = { 1, 0, 0, 1 }) const; + /** + * Takes a vector of exactly 8 vertices, i.e. corner points in a box. + * The box corners should be ordered from smaller to larger, + * first by x, the, y and finally z. + * + * 6-------7 + * |\ |\ + * | 2-------3 + * 4 | - - 5 | + * \| \| + * 0-------1 + * + */ + void renderBoxEdges(const Vertices& clippingSpaceBoxCorners, + RGBA rgba = { 1, 0, 0, 1 }) const; - /** - * Takes a vector of exactly 8 vertices, i.e. corner points in a box. - * The box corners should be ordered from smaller to larger, - * first by x, the, y and finally z. - * - * 6-------7 - * |\ |\ - * | 2-------3 - * 4 | - - 5 | - * \| \| - * 0-------1 - * - */ - void renderNiceBox(const Vertices& clippingSpaceBoxCorners, RGBA rgba = { 1, 0, 0, 0.3 }) const; + /** + * Takes a vector of exactly 8 vertices, i.e. corner points in a box. + * The box corners should be ordered from smaller to larger, + * first by x, the, y and finally z. + * + * 6-------7 + * |\ |\ + * | 2-------3 + * 4 | - - 5 | + * \| \| + * 0-------1 + * + */ + void renderNiceBox(const Vertices& clippingSpaceBoxCorners, + RGBA rgba = { 1, 0, 0, 0.3 }) const; - /** - * Input arguments: - * 1. const RenderData& data: defines position and camera that we will see the - * other cameras view frustum from - * 2. const Camera& otherCamera: The camera who's view frustum is to be rendered - * 3. RGBA rgba Color to draw the view frustum with - */ - void renderCameraFrustum(const RenderData& data, const Camera& otherCamera, RGBA rgba = { 1, 1, 1, 0.3 }) const; + /** + * Input arguments: + * 1. const RenderData& data: defines position and camera that we will see the + * other cameras view frustum from + * 2. const Camera& otherCamera: The camera who's view frustum is to be rendered + * 3. RGBA rgba Color to draw the view frustum with + */ + void renderCameraFrustum(const RenderData& data, const Camera& otherCamera, + RGBA rgba = { 1, 1, 1, 0.3 }) const; - /** - * Renders a screen space AABB2 to the screen with the provided color - */ - void renderAABB2(const AABB2& screenSpaceAABB, RGBA rgba = { 1, 1, 1, 0.3 }) const; +#ifdef OPENSPACE_MODULE_GLOBEBROWSING_ENABLED + /** + * Renders a screen space AABB2 to the screen with the provided color + */ + void renderAABB2(const globebrowsing::AABB2& screenSpaceAABB, + RGBA rgba = { 1, 1, 1, 0.3 }) const; +#endif // OPENSPACE_MODULE_GLOBEBROWSING_ENABLED - /** - * Takes a AABB3 in screen space and returns vertices representing the corner points - * of the AABB. The ordering of the corner points is compatible with the box rendering - * methods in this class. - */ - const Vertices verticesFor(const AABB3& screenSpaceAABB) const; - protected: - std::unique_ptr _programObject; +#ifdef OPENSPACE_MODULE_GLOBEBROWSING_ENABLED + /** + * Takes a AABB3 in screen space and returns vertices representing the corner points + * of the AABB. The ordering of the corner points is compatible with the box + * rendering methods in this class. + */ + const Vertices verticesFor(const globebrowsing::AABB3& screenSpaceAABB) const; +#endif // OPENSPACE_MODULE_GLOBEBROWSING_ENABLED + +protected: + std::unique_ptr _programObject; - // A raw pointer for the reason that it should not be deleted by the static - // destructor and the normal destructor. This class has ownership - static DebugRenderer* _reference; - }; + // A raw pointer for the reason that it should not be deleted by the static + // destructor and the normal destructor. This class has ownership + static DebugRenderer* _reference; +}; + } // namespace openspace -#endif // __DEBUG_RENDERER_H__ +#endif // __OPENSPACE_MODULE_BASE___DEBUGRENDERER___H__ diff --git a/modules/debugging/rendering/renderabledebugplane.h b/modules/debugging/rendering/renderabledebugplane.h index 40b2621aba..ffa476d0e9 100644 --- a/modules/debugging/rendering/renderabledebugplane.h +++ b/modules/debugging/rendering/renderabledebugplane.h @@ -22,13 +22,13 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERABLEDEBUGPLANE_H__ -#define __RENDERABLEDEBUGPLANE_H__ +#ifndef __OPENSPACE_MODULE_BASE___RENDERABLEDEBUGPLANE___H__ +#define __OPENSPACE_MODULE_BASE___RENDERABLEDEBUGPLANE___H__ #include #include -#include +#include #include namespace ghoul { @@ -82,4 +82,4 @@ private: } // namespace openspace -#endif // __RENDERABLEDEBUGPLANE_H__ +#endif // __OPENSPACE_MODULE_BASE___RENDERABLEDEBUGPLANE___H__ diff --git a/modules/fieldlines/fieldlinesmodule.cpp b/modules/fieldlines/fieldlinesmodule.cpp index 23928afba8..734ede9741 100644 --- a/modules/fieldlines/fieldlinesmodule.cpp +++ b/modules/fieldlines/fieldlinesmodule.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * diff --git a/modules/fieldlines/fieldlinesmodule.h b/modules/fieldlines/fieldlinesmodule.h index 782b8ff9fa..4d6731383c 100644 --- a/modules/fieldlines/fieldlinesmodule.h +++ b/modules/fieldlines/fieldlinesmodule.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __FIELDLINESMODULE_H__ -#define __FIELDLINESMODULE_H__ +#ifndef __OPENSPACE_MODULE_FIELDLINES___FIELDLINESMODULE___H__ +#define __OPENSPACE_MODULE_FIELDLINES___FIELDLINESMODULE___H__ #include @@ -39,4 +39,4 @@ protected: } // namespace openspace -#endif // __FIELDLINESMODULE_H__ +#endif // __OPENSPACE_MODULE_FIELDLINES___FIELDLINESMODULE___H__ diff --git a/modules/fieldlines/include.cmake b/modules/fieldlines/include.cmake index 3751826997..1172d03089 100644 --- a/modules/fieldlines/include.cmake +++ b/modules/fieldlines/include.cmake @@ -1,3 +1,4 @@ set (OPENSPACE_DEPENDENCIES kameleon + space ) \ No newline at end of file diff --git a/modules/fieldlines/rendering/renderablefieldlines.cpp b/modules/fieldlines/rendering/renderablefieldlines.cpp index 5be1822c83..c9ed83c96e 100644 --- a/modules/fieldlines/rendering/renderablefieldlines.cpp +++ b/modules/fieldlines/rendering/renderablefieldlines.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -41,30 +41,30 @@ namespace { const float defaultFieldlineStepSize = 0.5f;; const glm::vec4 defaultFieldlineColor = glm::vec4(1.f, 0.f, 0.f, 1.f); - const std::string keyVectorField = "VectorField"; - const std::string keyVectorFieldType = "Type"; - const std::string keyVectorFieldFile = "File"; - const std::string keyVectorFieldVolumeModel = "Model"; - const std::string keyVectorFieldVolumeVariable = "Variables"; + const char* keyVectorField = "VectorField"; + const char* keyVectorFieldType = "Type"; + const char* keyVectorFieldFile = "File"; + const char* keyVectorFieldVolumeModel = "Model"; + const char* keyVectorFieldVolumeVariable = "Variables"; - const std::string keyFieldlines = "Fieldlines"; - const std::string keyFieldlinesStepSize = "Stepsize"; - const std::string keyFieldlinesClassification = "Classification"; - const std::string keyFieldlinesColor = "Color"; + const char* keyFieldlines = "Fieldlines"; + const char* keyFieldlinesStepSize = "Stepsize"; + const char* keyFieldlinesClassification = "Classification"; + const char* keyFieldlinesColor = "Color"; - const std::string keySeedPoints = "SeedPoints"; - const std::string keySeedPointsType = "Type"; - const std::string keySeedPointsFile = "File"; - const std::string keySeedPointsTable = "SeedPoints"; + const char* keySeedPoints = "SeedPoints"; + const char* keySeedPointsType = "Type"; + const char* keySeedPointsFile = "File"; + const char* keySeedPointsTable = "SeedPoints"; - const std::string seedPointsSourceFile = "File"; - const std::string seedPointsSourceTable = "Table"; + const char* seedPointsSourceFile = "File"; + const char* seedPointsSourceTable = "Table"; - const std::string vectorFieldTypeVolumeKameleon = "VolumeKameleon"; + const char* vectorFieldTypeVolumeKameleon = "VolumeKameleon"; - const std::string vectorFieldKameleonModelBATSRUS = "BATSRUS"; + const char* vectorFieldKameleonModelBATSRUS = "BATSRUS"; - const std::string vectorFieldKameleonVariableLorentz = "Lorentz"; + const char* vectorFieldKameleonVariableLorentz = "Lorentz"; const int SeedPointSourceFile = 0; const int SeedPointSourceTable = 1; @@ -353,7 +353,7 @@ void RenderableFieldlines::loadSeedPointsFromTable() { _seedPointsInfo.getValue(keySeedPointsTable, seedpointsDictionary); glm::vec3 seedPos; for (const std::string& index : seedpointsDictionary.keys()) { - _fieldlineInfo.getValue(keySeedPointsTable + "." + index, seedPos); + _fieldlineInfo.getValue(std::string(keySeedPointsTable) + "." + index, seedPos); _seedPoints.push_back(seedPos); } } @@ -403,9 +403,9 @@ RenderableFieldlines::generateFieldlinesVolumeKameleon() return {}; } - std::string v1 = keyVectorFieldVolumeVariable + ".1"; - std::string v2 = keyVectorFieldVolumeVariable + ".2"; - std::string v3 = keyVectorFieldVolumeVariable + ".3"; + std::string v1 = std::string(keyVectorFieldVolumeVariable) + ".1"; + std::string v2 = std::string(keyVectorFieldVolumeVariable) + ".2"; + std::string v3 = std::string(keyVectorFieldVolumeVariable) + ".3"; bool threeVariables = _vectorFieldInfo.hasKeyAndValue(v1) && diff --git a/modules/fieldlines/rendering/renderablefieldlines.h b/modules/fieldlines/rendering/renderablefieldlines.h index 14b9162a07..6ffbf0ed09 100644 --- a/modules/fieldlines/rendering/renderablefieldlines.h +++ b/modules/fieldlines/rendering/renderablefieldlines.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERABLEFIELDLINES_H__ -#define __RENDERABLEFIELDLINES_H__ +#ifndef __OPENSPACE_MODULE_FIELDLINES___RENDERABLEFIELDLINES___H__ +#define __OPENSPACE_MODULE_FIELDLINES___RENDERABLEFIELDLINES___H__ #include @@ -95,4 +95,4 @@ private: } // namespace openspace -#endif // __RENDERABLEFIELDLINES_H__ +#endif // __OPENSPACE_MODULE_FIELDLINES___RENDERABLEFIELDLINES___H__ diff --git a/modules/galaxy/galaxymodule.cpp b/modules/galaxy/galaxymodule.cpp index 714818604e..193cf9f5bb 100644 --- a/modules/galaxy/galaxymodule.cpp +++ b/modules/galaxy/galaxymodule.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * diff --git a/modules/galaxy/galaxymodule.h b/modules/galaxy/galaxymodule.h index 26b4341b30..0171435b68 100644 --- a/modules/galaxy/galaxymodule.h +++ b/modules/galaxy/galaxymodule.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __GALAXYMODULE_H__ -#define __GALAXYMODULE_H__ +#ifndef __OPENSPACE_MODULE_GALAXY___GALAXYMODULE___H__ +#define __OPENSPACE_MODULE_GALAXY___GALAXYMODULE___H__ #include @@ -37,4 +37,4 @@ public: } // namespace openspace -#endif // __GALAXYMODULE_H__ +#endif // __OPENSPACE_MODULE_GALAXY___GALAXYMODULE___H__ diff --git a/modules/galaxy/include.cmake b/modules/galaxy/include.cmake index 1fbd4a3ae5..b72153a3c4 100644 --- a/modules/galaxy/include.cmake +++ b/modules/galaxy/include.cmake @@ -1,3 +1,4 @@ set (OPENSPACE_DEPENDENCIES volume + space ) \ No newline at end of file diff --git a/modules/galaxy/rendering/galaxyraycaster.cpp b/modules/galaxy/rendering/galaxyraycaster.cpp index 91a6689f35..84b12f6be8 100644 --- a/modules/galaxy/rendering/galaxyraycaster.cpp +++ b/modules/galaxy/rendering/galaxyraycaster.cpp @@ -134,7 +134,7 @@ bool GalaxyRaycaster::cameraIsInside(const RenderData& data, glm::vec3& localPos glm::vec4 modelPos = (glm::inverse(scaledModelTransform) / divisor) * camWorldPos; - localPosition = (modelPos.xyz() + glm::vec3(0.5)); + localPosition = (glm::vec3(modelPos) + glm::vec3(0.5)); return (localPosition.x > 0 && localPosition.y > 0 && localPosition.z > 0 && localPosition.x < 1 && localPosition.y < 1 && localPosition.z < 1); } diff --git a/modules/galaxy/rendering/galaxyraycaster.h b/modules/galaxy/rendering/galaxyraycaster.h index f3f9641160..fce9370fb5 100644 --- a/modules/galaxy/rendering/galaxyraycaster.h +++ b/modules/galaxy/rendering/galaxyraycaster.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __GALAXYRAYCASTER_H__ -#define __GALAXYRAYCASTER_H__ +#ifndef __OPENSPACE_MODULE_GALAXY___GALAXYRAYCASTER___H__ +#define __OPENSPACE_MODULE_GALAXY___GALAXYRAYCASTER___H__ #include @@ -49,7 +49,6 @@ class RaycastData; class GalaxyRaycaster : public VolumeRaycaster { public: - GalaxyRaycaster(ghoul::opengl::Texture& texture); virtual ~GalaxyRaycaster(); @@ -84,6 +83,6 @@ private: }; // GalaxyRaycaster -} // openspace +} // namespace openspace -#endif // __GALAXYRRAYCASTER_H__ +#endif // __OPENSPACE_MODULE_GALAXY___GALAXYRAYCASTER___H__ diff --git a/modules/galaxy/rendering/renderablegalaxy.cpp b/modules/galaxy/rendering/renderablegalaxy.cpp index 6ecfd1a46d..cd891e87eb 100644 --- a/modules/galaxy/rendering/renderablegalaxy.cpp +++ b/modules/galaxy/rendering/renderablegalaxy.cpp @@ -226,8 +226,7 @@ bool RenderableGalaxy::initialize() { _pointsProgram = renderEngine.buildRenderProgram("Galaxy points", "${MODULE_GALAXY}/shaders/points.vs", "${MODULE_GALAXY}/shaders/points.fs", - ghoul::Dictionary(), - RenderEngine::RenderProgramType::Post); + ghoul::Dictionary()); _pointsProgram->setIgnoreUniformLocationError(ghoul::opengl::ProgramObject::IgnoreError::Yes); @@ -331,7 +330,7 @@ float RenderableGalaxy::safeLength(const glm::vec3& vector) { return glm::length(vector / maxComponent) * maxComponent; } -void RenderableGalaxy::postRender(const RenderData& data) { +/*void RenderableGalaxy::postRender(const RenderData& data) { _raycaster->setStepSize(_pointStepSize); @@ -362,6 +361,6 @@ void RenderableGalaxy::postRender(const RenderData& data) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); OsEng.ref().renderEngine().postRaycast(*_pointsProgram); -} +}*/ } diff --git a/modules/galaxy/rendering/renderablegalaxy.h b/modules/galaxy/rendering/renderablegalaxy.h index 69b395a2dd..fc104b36e4 100644 --- a/modules/galaxy/rendering/renderablegalaxy.h +++ b/modules/galaxy/rendering/renderablegalaxy.h @@ -22,14 +22,15 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERABLEGALAXY_H__ -#define __RENDERABLEGALAXY_H__ +#ifndef __OPENSPACE_MODULE_GALAXY___RENDERABLEGALAXY___H__ +#define __OPENSPACE_MODULE_GALAXY___RENDERABLEGALAXY___H__ #include #include #include #include #include +#include namespace openspace { @@ -44,7 +45,6 @@ public: bool deinitialize() override; bool isReady() const override; void render(const RenderData& data, RendererTasks& tasks) override; - void postRender(const RenderData& data) override; void update(const UpdateData& data) override; private: @@ -75,6 +75,7 @@ private: GLuint _positionVbo; GLuint _colorVbo; }; -} -#endif // __RENDERABLEGALAXY_H__ +} // namespace openspace + +#endif // __OPENSPACE_MODULE_GALAXY___RENDERABLEGALAXY___H__ diff --git a/modules/globebrowsing/CMakeLists.txt b/modules/globebrowsing/CMakeLists.txt index e73af3e486..d5859f8bed 100644 --- a/modules/globebrowsing/CMakeLists.txt +++ b/modules/globebrowsing/CMakeLists.txt @@ -25,119 +25,122 @@ include(${OPENSPACE_CMAKE_EXT_DIR}/module_definition.cmake) set(HEADER_FILES + ${CMAKE_CURRENT_SOURCE_DIR}/chunk/chunk.h + ${CMAKE_CURRENT_SOURCE_DIR}/chunk/chunklevelevaluator.h + ${CMAKE_CURRENT_SOURCE_DIR}/chunk/chunknode.h + ${CMAKE_CURRENT_SOURCE_DIR}/chunk/culling.h + ${CMAKE_CURRENT_SOURCE_DIR}/geometry/aabb.h + ${CMAKE_CURRENT_SOURCE_DIR}/geometry/angle.h + ${CMAKE_CURRENT_SOURCE_DIR}/geometry/angle.inl + ${CMAKE_CURRENT_SOURCE_DIR}/geometry/convexhull.h + ${CMAKE_CURRENT_SOURCE_DIR}/geometry/ellipsoid.h + ${CMAKE_CURRENT_SOURCE_DIR}/geometry/geodetic2.h + + ${CMAKE_CURRENT_SOURCE_DIR}/globes/chunkedlodglobe.h + ${CMAKE_CURRENT_SOURCE_DIR}/globes/pointglobe.h ${CMAKE_CURRENT_SOURCE_DIR}/globes/renderableglobe.h - ${CMAKE_CURRENT_SOURCE_DIR}/chunk/chunkedlodglobe.h - ${CMAKE_CURRENT_SOURCE_DIR}/chunk/chunknode.h - ${CMAKE_CURRENT_SOURCE_DIR}/chunk/chunkindex.h - ${CMAKE_CURRENT_SOURCE_DIR}/chunk/chunk.h - ${CMAKE_CURRENT_SOURCE_DIR}/chunk/chunkrenderer.h - ${CMAKE_CURRENT_SOURCE_DIR}/chunk/culling.h - ${CMAKE_CURRENT_SOURCE_DIR}/chunk/chunklevelevaluator.h - - - ${CMAKE_CURRENT_SOURCE_DIR}/meshes/trianglesoup.h - ${CMAKE_CURRENT_SOURCE_DIR}/meshes/grid.h ${CMAKE_CURRENT_SOURCE_DIR}/meshes/basicgrid.h + ${CMAKE_CURRENT_SOURCE_DIR}/meshes/grid.h ${CMAKE_CURRENT_SOURCE_DIR}/meshes/skirtedgrid.h + ${CMAKE_CURRENT_SOURCE_DIR}/meshes/trianglesoup.h - ${CMAKE_CURRENT_SOURCE_DIR}/geometry/geodetic2.h - ${CMAKE_CURRENT_SOURCE_DIR}/geometry/angle.h - ${CMAKE_CURRENT_SOURCE_DIR}/geometry/ellipsoid.h - ${CMAKE_CURRENT_SOURCE_DIR}/geometry/aabb.h - ${CMAKE_CURRENT_SOURCE_DIR}/geometry/convexhull.h + ${CMAKE_CURRENT_SOURCE_DIR}/other/concurrentjobmanager.h + ${CMAKE_CURRENT_SOURCE_DIR}/other/concurrentjobmanager.inl + ${CMAKE_CURRENT_SOURCE_DIR}/other/concurrentqueue.h + ${CMAKE_CURRENT_SOURCE_DIR}/other/concurrentqueue.inl + ${CMAKE_CURRENT_SOURCE_DIR}/other/distanceswitch.h + ${CMAKE_CURRENT_SOURCE_DIR}/other/lrucache.h + ${CMAKE_CURRENT_SOURCE_DIR}/other/lrucache.inl + ${CMAKE_CURRENT_SOURCE_DIR}/other/statscollector.h + ${CMAKE_CURRENT_SOURCE_DIR}/other/statscollector.inl + ${CMAKE_CURRENT_SOURCE_DIR}/other/threadpool.h - ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/tileprovider.h - ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/singleimageprovider.h - ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/texttileprovider.h - ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/cachingtileprovider.h - ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/temporaltileprovider.h + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/chunkrenderer.h + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/gpulayermanager.h + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/layermanager.h + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/layershadermanager.h + ${CMAKE_CURRENT_SOURCE_DIR}/tile/asynctilereader.h + ${CMAKE_CURRENT_SOURCE_DIR}/tile/chunktile.h + ${CMAKE_CURRENT_SOURCE_DIR}/tile/pixelregion.h ${CMAKE_CURRENT_SOURCE_DIR}/tile/tile.h - ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileselector.h - ${CMAKE_CURRENT_SOURCE_DIR}/tile/tilediskcache.h ${CMAKE_CURRENT_SOURCE_DIR}/tile/tiledataset.h ${CMAKE_CURRENT_SOURCE_DIR}/tile/tiledatatype.h ${CMAKE_CURRENT_SOURCE_DIR}/tile/tiledepthtransform.h - ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileioresult.h - ${CMAKE_CURRENT_SOURCE_DIR}/tile/asynctilereader.h - ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovidermanager.h - ${CMAKE_CURRENT_SOURCE_DIR}/tile/layeredtextureshaderprovider.h - ${CMAKE_CURRENT_SOURCE_DIR}/tile/layeredtextures.h - ${CMAKE_CURRENT_SOURCE_DIR}/tile/pixelregion.h - - ${CMAKE_CURRENT_SOURCE_DIR}/other/distanceswitch.h - ${CMAKE_CURRENT_SOURCE_DIR}/other/lrucache.h - ${CMAKE_CURRENT_SOURCE_DIR}/other/concurrentjobmanager.h - ${CMAKE_CURRENT_SOURCE_DIR}/other/concurrentqueue.h - ${CMAKE_CURRENT_SOURCE_DIR}/other/statscollector.h - ${CMAKE_CURRENT_SOURCE_DIR}/other/threadpool.h - - + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tilediskcache.h + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileindex.h + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileselector.h + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/cachingtileprovider.h + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/singleimageprovider.h + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/temporaltileprovider.h + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/texttileprovider.h + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/tileprovider.h + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/tileproviderbyindex.h + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/tileproviderbylevel.h ) set(SOURCE_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/globes/renderableglobe.cpp - - ${CMAKE_CURRENT_SOURCE_DIR}/chunk/chunkedlodglobe.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/chunk/chunknode.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/chunk/chunkindex.cpp ${CMAKE_CURRENT_SOURCE_DIR}/chunk/chunk.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/chunk/chunkrenderer.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/chunk/culling.cpp ${CMAKE_CURRENT_SOURCE_DIR}/chunk/chunklevelevaluator.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/chunk/chunknode.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/chunk/culling.cpp - - ${CMAKE_CURRENT_SOURCE_DIR}/meshes/trianglesoup.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/meshes/grid.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/meshes/basicgrid.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/meshes/skirtedgrid.cpp - - ${CMAKE_CURRENT_SOURCE_DIR}/geometry/geodetic2.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/geometry/angle.inl - ${CMAKE_CURRENT_SOURCE_DIR}/geometry/ellipsoid.cpp ${CMAKE_CURRENT_SOURCE_DIR}/geometry/aabb.cpp ${CMAKE_CURRENT_SOURCE_DIR}/geometry/convexhull.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/geometry/ellipsoid.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/geometry/geodetic2.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/tileprovider.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/singleimageprovider.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/texttileprovider.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/cachingtileprovider.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/temporaltileprovider.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/globes/chunkedlodglobe.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/globes/pointglobe.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/globes/renderableglobe.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/tile/tile.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileselector.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/tile/tilediskcache.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/tile/tiledataset.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/tile/tiledatatype.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileioresult.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/tile/asynctilereader.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovidermanager.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/tile/layeredtextureshaderprovider.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/tile/layeredtextures.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/tile/pixelregion.cpp - + ${CMAKE_CURRENT_SOURCE_DIR}/meshes/basicgrid.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/meshes/grid.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/meshes/skirtedgrid.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/meshes/trianglesoup.cpp ${CMAKE_CURRENT_SOURCE_DIR}/other/distanceswitch.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/other/lrucache.inl - ${CMAKE_CURRENT_SOURCE_DIR}/other/concurrentjobmanager.inl ${CMAKE_CURRENT_SOURCE_DIR}/other/statscollector.cpp ${CMAKE_CURRENT_SOURCE_DIR}/other/threadpool.cpp + + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/chunkrenderer.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/gpulayermanager.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/layershadermanager.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/layermanager.cpp + + ${CMAKE_CURRENT_SOURCE_DIR}/tile/asynctilereader.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/tile/pixelregion.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tile.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tiledataset.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tiledatatype.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tilediskcache.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileindex.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileselector.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/cachingtileprovider.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/singleimageprovider.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/temporaltileprovider.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/texttileprovider.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/tileprovider.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/tileproviderbyindex.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/tile/tileprovider/tileproviderbylevel.cpp ) source_group("Source Files" FILES ${SOURCE_FILES}) set(SHADER_FILES ${CMAKE_CURRENT_SOURCE_DIR}/shaders/blending.hglsl ${CMAKE_CURRENT_SOURCE_DIR}/shaders/ellipsoid.hglsl - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/tile.hglsl - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/texturetilemapping.hglsl - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/globalchunkedlodpatch_vs.glsl ${CMAKE_CURRENT_SOURCE_DIR}/shaders/globalchunkedlodpatch_fs.glsl - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/localchunkedlodpatch_vs.glsl ${CMAKE_CURRENT_SOURCE_DIR}/shaders/localchunkedlodpatch_fs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/pointglobe_vs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/pointglobe_fs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/texturetilemapping.hglsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/tile.hglsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/tilefragcolor.hglsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/tilevertexheight.hglsl ) source_group("Shader Files" FILES ${SHADER_FILES}) @@ -148,7 +151,6 @@ create_new_module( ${HEADER_FILES} ${SOURCE_FILES} ${SHADER_FILES} ) - if (WIN32) target_include_directories( openspace-module-globebrowsing @@ -176,4 +178,4 @@ else (WIN32) openspace-module-globebrowsing ${GDAL_LIBRARY} ) -endif () \ No newline at end of file +endif () diff --git a/modules/globebrowsing/Doxyfile b/modules/globebrowsing/Doxyfile deleted file mode 100644 index 7c52cb1206..0000000000 --- a/modules/globebrowsing/Doxyfile +++ /dev/null @@ -1,451 +0,0 @@ -# Doxyfile 1.7.6.1 - -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- - -DOXYFILE_ENCODING = UTF-8 -PROJECT_NAME = OpenSpace -PROJECT_NUMBER = -PROJECT_LOGO = -OUTPUT_DIRECTORY = doc/ -CREATE_SUBDIRS = NO -OUTPUT_LANGUAGE = English -BRIEF_MEMBER_DESC = YES -REPEAT_BRIEF = YES -ALWAYS_DETAILED_SEC = YES -INLINE_INHERITED_MEMB = NO -FULL_PATH_NAMES = YES -JAVADOC_AUTOBRIEF = YES -QT_AUTOBRIEF = YES - -# This tag can be used to specify a number of aliases that acts -# as commands in the documentation. An alias has the form "name=value". -# For example adding "sideeffect=\par Side Effects:\n" will allow you to -# put the command \sideeffect (or @sideeffect) in the documentation, which -# will result in a user-defined paragraph with heading "Side Effects:". -# You can put \n's in the value part of an alias to insert newlines. - -ALIASES = -BUILTIN_STL_SUPPORT = NO - -SUBGROUPING = YES - -# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and -# unions are shown inside the group in which they are included (e.g. using -# @ingroup) instead of on a separate page (for HTML and Man pages) or -# section (for LaTeX and RTF). - -INLINE_GROUPED_CLASSES = NO -INLINE_SIMPLE_STRUCTS = YES -TYPEDEF_HIDES_STRUCT = NO -LOOKUP_CACHE_SIZE = 1 - -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- - -EXTRACT_ALL = YES -EXTRACT_PRIVATE = YES -EXTRACT_STATIC = YES -EXTRACT_LOCAL_CLASSES = YES -EXTRACT_LOCAL_METHODS = NO -EXTRACT_ANON_NSPACES = NO -HIDE_IN_BODY_DOCS = NO -INTERNAL_DOCS = NO -CASE_SENSE_NAMES = NO -HIDE_SCOPE_NAMES = YES -SHOW_INCLUDE_FILES = YES -FORCE_LOCAL_INCLUDES = NO -INLINE_INFO = NO -SORT_MEMBER_DOCS = YES -SORT_BRIEF_DOCS = YES -SORT_MEMBERS_CTORS_1ST = YES -SORT_GROUP_NAMES = NO -SORT_BY_SCOPE_NAME = NO -STRICT_PROTO_MATCHING = NO -GENERATE_TODOLIST = YES -GENERATE_TESTLIST = NO -GENERATE_BUGLIST = YES -GENERATE_DEPRECATEDLIST= YES -MAX_INITIALIZER_LINES = 30 -SHOW_USED_FILES = NO -SHOW_FILES = NO -SHOW_NAMESPACES = YES -LAYOUT_FILE = - -#--------------------------------------------------------------------------- -# configuration options related to warning and progress messages -#--------------------------------------------------------------------------- - -QUIET = YES -WARNINGS = YES -WARN_IF_DOC_ERROR = YES -WARN_NO_PARAMDOC = YES -WARN_FORMAT = "$file:$line: $text" - -#--------------------------------------------------------------------------- -# configuration options related to the input files -#--------------------------------------------------------------------------- - -INPUT = . - -INPUT_ENCODING = UTF-8 -FILE_PATTERNS = *.c \ - *.cpp \ - *.h \ - *.inl - -RECURSIVE = YES -EXCLUDE = ext/ -EXCLUDE_SYMLINKS = NO -EXCLUDE_PATTERNS = -EXCLUDE_SYMBOLS = - -#--------------------------------------------------------------------------- -# configuration options related to source browsing -#--------------------------------------------------------------------------- - -SOURCE_BROWSER = YES -INLINE_SOURCES = NO -STRIP_CODE_COMMENTS = YES -REFERENCED_BY_RELATION = NO -REFERENCES_RELATION = NO -REFERENCES_LINK_SOURCE = YES -VERBATIM_HEADERS = NO - -#--------------------------------------------------------------------------- -# configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- - -ALPHABETICAL_INDEX = YES -COLS_IN_ALPHA_INDEX = 4 -IGNORE_PREFIX = - -#--------------------------------------------------------------------------- -# configuration options related to the HTML output -#--------------------------------------------------------------------------- - -GENERATE_HTML = YES -HTML_OUTPUT = html -HTML_FILE_EXTENSION = .html -HTML_HEADER = ../../support/doxygen/header.html -HTML_FOOTER = ../../support/doxygen/footer.html -HTML_STYLESHEET = ../../support/doxygen/stylesheet.css -#HTML_EXTRA_FILES = -HTML_COLORSTYLE_HUE = 200 -HTML_COLORSTYLE_SAT = 100 -HTML_COLORSTYLE_GAMMA = 80 -HTML_TIMESTAMP = NO -HTML_DYNAMIC_SECTIONS = NO -# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html -# for more information. -GENERATE_DOCSET = NO -DOCSET_FEEDNAME = -DOCSET_BUNDLE_ID = -DOCSET_PUBLISHER_ID = -DOCSET_PUBLISHER_NAME = -GENERATE_HTMLHELP = NO -CHM_FILE = -HHC_LOCATION = -GENERATE_CHI = NO -CHM_INDEX_ENCODING = -BINARY_TOC = NO -TOC_EXPAND = NO -DISABLE_INDEX = YES -GENERATE_TREEVIEW = YES -ENUM_VALUES_PER_LINE = 6 -TREEVIEW_WIDTH = 300 -EXT_LINKS_IN_WINDOW = NO -FORMULA_FONTSIZE = 10 -FORMULA_TRANSPARENT = YES -USE_MATHJAX = NO -MATHJAX_RELPATH = http://www.mathjax.org/mathjax -MATHJAX_EXTENSIONS = -SEARCHENGINE = YES -SERVER_BASED_SEARCH = NO - -#--------------------------------------------------------------------------- -# configuration options related to the LaTeX output -#--------------------------------------------------------------------------- - -GENERATE_LATEX = NO -LATEX_OUTPUT = latex -LATEX_CMD_NAME = latex -MAKEINDEX_CMD_NAME = makeindex -COMPACT_LATEX = NO -PAPER_TYPE = a4wide -EXTRA_PACKAGES = -LATEX_HEADER = -LATEX_FOOTER = -PDF_HYPERLINKS = YES -USE_PDFLATEX = YES -LATEX_BATCHMODE = NO -LATEX_HIDE_INDICES = NO -LATEX_SOURCE_CODE = NO -LATEX_BIB_STYLE = plain - -#--------------------------------------------------------------------------- -# configuration options related to the RTF output -#--------------------------------------------------------------------------- - -GENERATE_RTF = NO -RTF_OUTPUT = rtf -COMPACT_RTF = NO -RTF_HYPERLINKS = NO -RTF_STYLESHEET_FILE = -RTF_EXTENSIONS_FILE = - -#--------------------------------------------------------------------------- -# configuration options related to the man page output -#--------------------------------------------------------------------------- - -GENERATE_MAN = NO -MAN_OUTPUT = man -MAN_EXTENSION = .3 -MAN_LINKS = NO - -#--------------------------------------------------------------------------- -# configuration options related to the XML output -#--------------------------------------------------------------------------- - -GENERATE_XML = NO -XML_OUTPUT = xml -XML_SCHEMA = -XML_DTD = -XML_PROGRAMLISTING = YES - -#--------------------------------------------------------------------------- -# configuration options for the AutoGen Definitions output -#--------------------------------------------------------------------------- - -GENERATE_AUTOGEN_DEF = NO - -#--------------------------------------------------------------------------- -# configuration options related to the Perl module output -#--------------------------------------------------------------------------- - -GENERATE_PERLMOD = NO -PERLMOD_LATEX = NO -PERLMOD_PRETTY = YES -PERLMOD_MAKEVAR_PREFIX = - -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- - -ENABLE_PREPROCESSING = YES -MACRO_EXPANSION = YES -EXPAND_ONLY_PREDEF = YES -SEARCH_INCLUDES = YES -INCLUDE_PATH = -INCLUDE_FILE_PATTERNS = -PREDEFINED = -EXPAND_AS_DEFINED = YES -SKIP_FUNCTION_MACROS = NO - -#--------------------------------------------------------------------------- -# Configuration::additions related to external references -#--------------------------------------------------------------------------- - -TAGFILES = -GENERATE_TAGFILE = -ALLEXTERNALS = NO -EXTERNAL_GROUPS = YES -PERL_PATH = /usr/bin/perl - -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- - -CLASS_DIAGRAMS = YES -MSCGEN_PATH = -HIDE_UNDOC_RELATIONS = YES - -# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is -# available from the path. This tool is part of Graphviz, a graph visualization -# toolkit from AT&T and Lucent Bell Labs. The other options in this section -# have no effect if this option is set to NO (the default) - -HAVE_DOT = NO - -# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is -# allowed to run in parallel. When set to 0 (the default) doxygen will -# base this on the number of processors available in the system. You can set it -# explicitly to a value larger than 0 to get control over the balance -# between CPU load and processing speed. - -DOT_NUM_THREADS = 0 - -# By default doxygen will use the Helvetica font for all dot files that -# doxygen generates. When you want a differently looking font you can specify -# the font name using DOT_FONTNAME. You need to make sure dot is able to find -# the font, which can be done by putting it in a standard location or by setting -# the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the -# directory containing the font. - -DOT_FONTNAME = Helvetica - -# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. -# The default size is 10pt. - -DOT_FONTSIZE = 10 - -# By default doxygen will tell dot to use the Helvetica font. -# If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to -# set the path where dot can find it. - -DOT_FONTPATH = - -# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen -# will generate a graph for each documented class showing the direct and -# indirect inheritance relations. Setting this tag to YES will force the -# CLASS_DIAGRAMS tag to NO. - -CLASS_GRAPH = YES - -# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen -# will generate a graph for each documented class showing the direct and -# indirect implementation dependencies (inheritance, containment, and -# class references variables) of the class with other documented classes. - -COLLABORATION_GRAPH = YES - -# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen -# will generate a graph for groups, showing the direct groups dependencies - -GROUP_GRAPHS = YES - -# If the UML_LOOK tag is set to YES doxygen will generate inheritance and -# collaboration diagrams in a style similar to the OMG's Unified Modeling -# Language. - -UML_LOOK = NO - -# If set to YES, the inheritance and collaboration graphs will show the -# relations between templates and their instances. - -TEMPLATE_RELATIONS = NO - -# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT -# tags are set to YES then doxygen will generate a graph for each documented -# file showing the direct and indirect include dependencies of the file with -# other documented files. - -INCLUDE_GRAPH = YES - -# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and -# HAVE_DOT tags are set to YES then doxygen will generate a graph for each -# documented header file showing the documented files that directly or -# indirectly include this file. - -INCLUDED_BY_GRAPH = YES - -# If the CALL_GRAPH and HAVE_DOT options are set to YES then -# doxygen will generate a call dependency graph for every global function -# or class method. Note that enabling this option will significantly increase -# the time of a run. So in most cases it will be better to enable call graphs -# for selected functions only using the \callgraph command. - -CALL_GRAPH = NO - -# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then -# doxygen will generate a caller dependency graph for every global function -# or class method. Note that enabling this option will significantly increase -# the time of a run. So in most cases it will be better to enable caller -# graphs for selected functions only using the \callergraph command. - -CALLER_GRAPH = NO - -# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen -# will generate a graphical hierarchy of all classes instead of a textual one. - -GRAPHICAL_HIERARCHY = YES - -# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES -# then doxygen will show the dependencies a directory has on other directories -# in a graphical way. The dependency relations are determined by the #include -# relations between the files in the directories. - -DIRECTORY_GRAPH = YES - -# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images -# generated by dot. Possible values are svg, png, jpg, or gif. -# If left blank png will be used. If you choose svg you need to set -# HTML_FILE_EXTENSION to xhtml in order to make the SVG files -# visible in IE 9+ (other browsers do not have this requirement). - -DOT_IMAGE_FORMAT = png - -# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to -# enable generation of interactive SVG images that allow zooming and panning. -# Note that this requires a modern browser other than Internet Explorer. -# Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you -# need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files -# visible. Older versions of IE do not have SVG support. - -INTERACTIVE_SVG = NO - -# The tag DOT_PATH can be used to specify the path where the dot tool can be -# found. If left blank, it is assumed the dot tool can be found in the path. - -DOT_PATH = - -# The DOTFILE_DIRS tag can be used to specify one or more directories that -# contain dot files that are included in the documentation (see the -# \dotfile command). - -DOTFILE_DIRS = - -# The MSCFILE_DIRS tag can be used to specify one or more directories that -# contain msc files that are included in the documentation (see the -# \mscfile command). - -MSCFILE_DIRS = - -# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of -# nodes that will be shown in the graph. If the number of nodes in a graph -# becomes larger than this value, doxygen will truncate the graph, which is -# visualized by representing a node as a red box. Note that doxygen if the -# number of direct children of the root node in a graph is already larger than -# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note -# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. - -DOT_GRAPH_MAX_NODES = 50 - -# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the -# graphs generated by dot. A depth value of 3 means that only nodes reachable -# from the root by following a path via at most 3 edges will be shown. Nodes -# that lay further from the root node will be omitted. Note that setting this -# option to 1 or 2 may greatly reduce the computation time needed for large -# code bases. Also note that the size of a graph can be further restricted by -# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. - -MAX_DOT_GRAPH_DEPTH = 0 - -# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent -# background. This is disabled by default, because dot on Windows does not -# seem to support this out of the box. Warning: Depending on the platform used, -# enabling this option may lead to badly anti-aliased labels on the edges of -# a graph (i.e. they become hard to read). - -DOT_TRANSPARENT = NO - -# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output -# files in one run (i.e. multiple -o and -T options on the command line). This -# makes dot run faster, but since only newer versions of dot (>1.8.10) -# support this, this feature is disabled by default. - -DOT_MULTI_TARGETS = NO - -# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will -# generate a legend page explaining the meaning of the various boxes and -# arrows in the dot generated graphs. - -GENERATE_LEGEND = YES - -# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will -# remove the intermediate dot files that are used to generate -# the various graphs. - -DOT_CLEANUP = YES diff --git a/modules/globebrowsing/chunk/chunk.cpp b/modules/globebrowsing/chunk/chunk.cpp index da46d3ac56..a70509c48c 100644 --- a/modules/globebrowsing/chunk/chunk.cpp +++ b/modules/globebrowsing/chunk/chunk.cpp @@ -22,190 +22,190 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ - -#include - -#include - #include -#include -#include -#include -#include - -namespace { - const std::string _loggerCat = "Chunk"; -} +#include +#include +#include +#include namespace openspace { +namespace globebrowsing { - const float Chunk::DEFAULT_HEIGHT = 0.0f; +const float Chunk::DEFAULT_HEIGHT = 0.0f; - Chunk::Chunk(ChunkedLodGlobe* owner, const ChunkIndex& chunkIndex, bool initVisible) - : _owner(owner) - , _surfacePatch(chunkIndex) - , _index(chunkIndex) - , _isVisible(initVisible) - { +Chunk::Chunk(const RenderableGlobe& owner, const TileIndex& tileIndex, bool initVisible) + : _owner(owner) + , _surfacePatch(tileIndex) + , _tileIndex(tileIndex) + , _isVisible(initVisible) +{} +const GeodeticPatch& Chunk::surfacePatch() const { + return _surfacePatch; +} + +const RenderableGlobe& Chunk::owner() const { + return _owner; +} + +const TileIndex Chunk::tileIndex() const { + return _tileIndex; +} + +bool Chunk::isVisible() const { + return _isVisible; +} + +Chunk::Status Chunk::update(const RenderData& data) { + auto savedCamera = _owner.savedCamera(); + const Camera& camRef = savedCamera != nullptr ? *savedCamera : data.camera; + RenderData myRenderData = { camRef, data.position, data.doPerformanceMeasurement }; + + _isVisible = true; + if (_owner.chunkedLodGlobe()->testIfCullable(*this, myRenderData)) { + _isVisible = false; + return Status::WANT_MERGE; } - const GeodeticPatch& Chunk::surfacePatch() const { - return _surfacePatch; + int desiredLevel = _owner.chunkedLodGlobe()->getDesiredLevel(*this, myRenderData); + + if (desiredLevel < _tileIndex.level) { + return Status::WANT_MERGE; } - - ChunkedLodGlobe* const Chunk::owner() const { - return _owner; + else if (_tileIndex.level < desiredLevel) { + return Status::WANT_SPLIT; } - - const ChunkIndex Chunk::index() const { - return _index; + else { + return Status::DO_NOTHING; } +} - bool Chunk::isVisible() const { - return _isVisible; - } +Chunk::BoundingHeights Chunk::getBoundingHeights() const { + BoundingHeights boundingHeights; + boundingHeights.max = 0; + boundingHeights.min = 0; + boundingHeights.available = false; - void Chunk::setIndex(const ChunkIndex& index) { - _index = index; - _surfacePatch = GeodeticPatch(index); - } - - void Chunk::setOwner(ChunkedLodGlobe* newOwner) { - _owner = newOwner; - } - - Chunk::Status Chunk::update(const RenderData& data) { - auto savedCamera = _owner->getSavedCamera(); - const Camera& camRef = savedCamera != nullptr ? *savedCamera : data.camera; - RenderData myRenderData = { camRef, data.position, data.doPerformanceMeasurement }; - - - _isVisible = true; - if (_owner->testIfCullable(*this, myRenderData)) { - _isVisible = false; - return Status::WANT_MERGE; - } - - int desiredLevel = _owner->getDesiredLevel(*this, myRenderData); - - if (desiredLevel < _index.level) return Status::WANT_MERGE; - else if (_index.level < desiredLevel) return Status::WANT_SPLIT; - else return Status::DO_NOTHING; - } - - Chunk::BoundingHeights Chunk::getBoundingHeights() const { - BoundingHeights boundingHeights; - boundingHeights.max = 0; - boundingHeights.min = 0; - boundingHeights.available = false; - - // In the future, this should be abstracted away and more easily queryable. - // One must also handle how to sample pick one out of multiplte heightmaps - auto tileProviderManager = owner()->getTileProviderManager(); - - - auto heightMapProviders = tileProviderManager->getTileProviderGroup(LayeredTextures::HeightMaps).getActiveTileProviders(); + // In the future, this should be abstracted away and more easily queryable. + // One must also handle how to sample pick one out of multiplte heightmaps + auto layerManager = owner().chunkedLodGlobe()->layerManager(); - - size_t HEIGHT_CHANNEL = 0; - const TileProviderGroup& heightmaps = tileProviderManager->getTileProviderGroup(LayeredTextures::HeightMaps); - std::vector tiles = TileSelector::getTilesSortedByHighestResolution(heightmaps, _index); - bool lastHadMissingData = true; - for (auto tile : tiles) { - bool goodTile = tile.tile.status == Tile::Status::OK; - bool hasPreprocessData = tile.tile.preprocessData != nullptr; + // The raster of a height map is the first one. We assume that the height map is + // a single raster image. If it is not we will just use the first raster + // (that is channel 0). + size_t HEIGHT_CHANNEL = 0; + const LayerGroup& heightmaps = layerManager->layerGroup(LayerManager::HeightLayers); + std::vector chunkTiles = TileSelector::getTilesSortedByHighestResolution( + heightmaps, _tileIndex + ); - if (goodTile && hasPreprocessData) { - auto preprocessData = tile.tile.preprocessData; + bool lastHadMissingData = true; + for (auto chunkTile : chunkTiles) { + bool goodTile = chunkTile.tile.status == Tile::Status::OK; + bool hastileMetaData = chunkTile.tile.metaData != nullptr; - if (!boundingHeights.available) { - if (preprocessData->hasMissingData[HEIGHT_CHANNEL]) { - boundingHeights.min = std::min(DEFAULT_HEIGHT, preprocessData->minValues[HEIGHT_CHANNEL]); - boundingHeights.max = std::max(DEFAULT_HEIGHT, preprocessData->maxValues[HEIGHT_CHANNEL]); - } - else { - boundingHeights.min = preprocessData->minValues[HEIGHT_CHANNEL]; - boundingHeights.max = preprocessData->maxValues[HEIGHT_CHANNEL]; - } - boundingHeights.available = true; + if (goodTile && hastileMetaData) { + auto tileMetaData = chunkTile.tile.metaData; + + if (!boundingHeights.available) { + if (tileMetaData->hasMissingData[HEIGHT_CHANNEL]) { + boundingHeights.min = std::min( + DEFAULT_HEIGHT, + tileMetaData->minValues[HEIGHT_CHANNEL] + ); + boundingHeights.max = std::max( + DEFAULT_HEIGHT, + tileMetaData->maxValues[HEIGHT_CHANNEL] + ); } else { - boundingHeights.min = std::min(boundingHeights.min, preprocessData->minValues[HEIGHT_CHANNEL]); - boundingHeights.max = std::max(boundingHeights.max, preprocessData->maxValues[HEIGHT_CHANNEL]); + boundingHeights.min = tileMetaData->minValues[HEIGHT_CHANNEL]; + boundingHeights.max = tileMetaData->maxValues[HEIGHT_CHANNEL]; } - lastHadMissingData = preprocessData->hasMissingData[HEIGHT_CHANNEL]; + boundingHeights.available = true; } - - // Allow for early termination - if (!lastHadMissingData) { - break; + else { + boundingHeights.min = std::min( + boundingHeights.min, + tileMetaData->minValues[HEIGHT_CHANNEL] + ); + boundingHeights.max = std::max( + boundingHeights.max, + tileMetaData->maxValues[HEIGHT_CHANNEL] + ); } + lastHadMissingData = tileMetaData->hasMissingData[HEIGHT_CHANNEL]; + } + + // Allow for early termination + if (!lastHadMissingData) { + break; } - - return boundingHeights; } - - std::vector Chunk::getBoundingPolyhedronCorners() const { - const Ellipsoid& ellipsoid = owner()->ellipsoid(); - const GeodeticPatch& patch = surfacePatch(); - - BoundingHeights boundingHeight = getBoundingHeights(); - - // assume worst case - double patchCenterRadius = ellipsoid.maximumRadius(); - - double maxCenterRadius = patchCenterRadius + boundingHeight.max; - Geodetic2 halfSize = patch.halfSize(); - - // As the patch is curved, the maximum height offsets at the corners must be long - // enough to cover large enough to cover a boundingHeight.max at the center of the - // patch. - // Approximating scaleToCoverCenter by assuming the latitude and longitude angles - // of "halfSize" are equal to the angles they create from the center of the - // globe to the patch corners. This is true for the longitude direction when - // the ellipsoid can be approximated as a sphere and for the latitude for patches - // close to the equator. Close to the pole this will lead to a bigger than needed - // value for scaleToCoverCenter. However, this is a simple calculation and a good - // Approximation. - double y1 = tan(halfSize.lat); - double y2 = tan(halfSize.lon); - double scaleToCoverCenter = sqrt(1 + pow(y1, 2) + pow(y2, 2)); - double maxCornerHeight = maxCenterRadius * scaleToCoverCenter - patchCenterRadius; + return boundingHeights; +} - bool chunkIsNorthOfEquator = patch.isNorthern(); +std::vector Chunk::getBoundingPolyhedronCorners() const { + const Ellipsoid& ellipsoid = owner().ellipsoid(); + const GeodeticPatch& patch = surfacePatch(); - // The minimum height offset, however, we can simply - double minCornerHeight = boundingHeight.min; - std::vector corners(8); + BoundingHeights boundingHeight = getBoundingHeights(); + + // assume worst case + double patchCenterRadius = ellipsoid.maximumRadius(); + + double maxCenterRadius = patchCenterRadius + boundingHeight.max; + Geodetic2 halfSize = patch.halfSize(); + + // As the patch is curved, the maximum height offsets at the corners must be long + // enough to cover large enough to cover a boundingHeight.max at the center of the + // patch. + // Approximating scaleToCoverCenter by assuming the latitude and longitude angles + // of "halfSize" are equal to the angles they create from the center of the + // globe to the patch corners. This is true for the longitude direction when + // the ellipsoid can be approximated as a sphere and for the latitude for patches + // close to the equator. Close to the pole this will lead to a bigger than needed + // value for scaleToCoverCenter. However, this is a simple calculation and a good + // Approximation. + double y1 = tan(halfSize.lat); + double y2 = tan(halfSize.lon); + double scaleToCoverCenter = sqrt(1 + pow(y1, 2) + pow(y2, 2)); - Scalar latCloseToEquator = patch.edgeLatitudeNearestEquator(); - Geodetic3 p1Geodetic = { { latCloseToEquator, patch.minLon() }, maxCornerHeight }; - Geodetic3 p2Geodetic = { { latCloseToEquator, patch.maxLon() }, maxCornerHeight }; - - glm::vec3 p1 = ellipsoid.cartesianPosition(p1Geodetic); - glm::vec3 p2 = ellipsoid.cartesianPosition(p2Geodetic); - glm::vec3 p = 0.5f * (p1 + p2); - Geodetic2 pGeodetic = ellipsoid.cartesianToGeodetic2(p); - Scalar latDiff = latCloseToEquator - pGeodetic.lat; + double maxCornerHeight = maxCenterRadius * scaleToCoverCenter - patchCenterRadius; - for (size_t i = 0; i < 8; i++) { - Quad q = (Quad)(i % 4); - double cornerHeight = i < 4 ? minCornerHeight : maxCornerHeight; - Geodetic3 cornerGeodetic = { patch.getCorner(q), cornerHeight }; + bool chunkIsNorthOfEquator = patch.isNorthern(); + + // The minimum height offset, however, we can simply + double minCornerHeight = boundingHeight.min; + std::vector corners(8); + + double latCloseToEquator = patch.edgeLatitudeNearestEquator(); + Geodetic3 p1Geodetic = { { latCloseToEquator, patch.minLon() }, maxCornerHeight }; + Geodetic3 p2Geodetic = { { latCloseToEquator, patch.maxLon() }, maxCornerHeight }; + + glm::vec3 p1 = ellipsoid.cartesianPosition(p1Geodetic); + glm::vec3 p2 = ellipsoid.cartesianPosition(p2Geodetic); + glm::vec3 p = 0.5f * (p1 + p2); + Geodetic2 pGeodetic = ellipsoid.cartesianToGeodetic2(p); + double latDiff = latCloseToEquator - pGeodetic.lat; + + for (size_t i = 0; i < 8; ++i) { + Quad q = (Quad)(i % 4); + double cornerHeight = i < 4 ? minCornerHeight : maxCornerHeight; + Geodetic3 cornerGeodetic = { patch.getCorner(q), cornerHeight }; - bool cornerIsNorthern = !((i / 2) % 2); - bool cornerCloseToEquator = chunkIsNorthOfEquator ^ cornerIsNorthern; - if (cornerCloseToEquator) { - cornerGeodetic.geodetic2.lat += latDiff; - } - - corners[i] = dvec4(ellipsoid.cartesianPosition(cornerGeodetic), 1); + bool cornerIsNorthern = !((i / 2) % 2); + bool cornerCloseToEquator = chunkIsNorthOfEquator ^ cornerIsNorthern; + if (cornerCloseToEquator) { + cornerGeodetic.geodetic2.lat += latDiff; } - return corners; + + corners[i] = glm::dvec4(ellipsoid.cartesianPosition(cornerGeodetic), 1); } + return corners; +} - +} // namespace globebrowsing } // namespace openspace diff --git a/modules/globebrowsing/chunk/chunk.h b/modules/globebrowsing/chunk/chunk.h index 8d0aafcbe5..d32955adf7 100644 --- a/modules/globebrowsing/chunk/chunk.h +++ b/modules/globebrowsing/chunk/chunk.h @@ -22,72 +22,86 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __CHUNK_H__ -#define __CHUNK_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___CHUNK___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___CHUNK___H__ + +#include +#include #include #include -#include -#include - -#include -#include -#include - - -#include -#include - namespace openspace { - class ChunkedLodGlobe; +struct RenderData; - class Chunk { - public: +namespace globebrowsing { - const static float DEFAULT_HEIGHT; +class GeodeticPatch; +class RenderableGlobe; +struct TileIndex; - struct BoundingHeights { - float min, max; - bool available; - }; - - enum class Status { - DO_NOTHING, - WANT_MERGE, - WANT_SPLIT, - }; - - Chunk(ChunkedLodGlobe* owner, const ChunkIndex& chunkIndex, bool initVisible = true); - - /// Updates chunk internally and returns a desired level - Status update(const RenderData& data); - - std::vector getBoundingPolyhedronCorners() const; - - const GeodeticPatch& surfacePatch() const; - ChunkedLodGlobe* const owner() const; - const ChunkIndex index() const; - bool isVisible() const; - BoundingHeights getBoundingHeights() const; - - void setIndex(const ChunkIndex& index); - void setOwner(ChunkedLodGlobe* newOwner); - - - private: - - ChunkedLodGlobe* _owner; - ChunkIndex _index; - bool _isVisible; - GeodeticPatch _surfacePatch; +class Chunk { +public: + const static float DEFAULT_HEIGHT; + struct BoundingHeights { + float min, max; + bool available; }; + enum class Status { + DO_NOTHING, + WANT_MERGE, + WANT_SPLIT, + }; + + Chunk(const RenderableGlobe& owner, const TileIndex& tileIndex, + bool initVisible = true); -} + /** + * Updates the Chunk internally and returns the Status of the Chunk. + * + * Tests if the Chunk is cullable and gets the desired level of the Chunk. If the + * Chunk is cullable it will be set to invisible and return Status::WANT_MERGE. + * If the desired level is smaller than the current level of the chunk it will + * return Status::WANT_MERGE, if it is larger it will return Status::WANT_SPLIT, + * otherwise Status::DO_NOTHING. + * + * \returns The Status of the chunk. + */ + Status update(const RenderData& data); + /** + * Returns a convex polyhedron of eight vertices tightly bounding the volume of + * the Chunk. + */ + std::vector getBoundingPolyhedronCorners() const; + const GeodeticPatch& surfacePatch() const; + const RenderableGlobe& owner() const; + const TileIndex tileIndex() const; + bool isVisible() const; + + /** + * Returns BoundingHeights that fits the Chunk as tightly as possible. + * + * If the Chunk uses more than one HightLayer, the BoundingHeights will be set + * to cover all HightLayers. If the Chunk has a higher level than its highest + * resolution HightLayer Tile, it will base its BoundingHeights on that Tile. + * This means that high level Chunks can have BoundingHeights that are not + * tightly fitting. + */ + BoundingHeights getBoundingHeights() const; -#endif // __CHUNK_H__ +private: + const RenderableGlobe& _owner; + const TileIndex _tileIndex; + bool _isVisible; + const GeodeticPatch _surfacePatch; +}; + +} // namespace globebrowsing +} // namespace openspace + +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___CHUNK___H__ diff --git a/modules/globebrowsing/chunk/chunkedlodglobe.cpp b/modules/globebrowsing/chunk/chunkedlodglobe.cpp deleted file mode 100644 index 83378d7d6b..0000000000 --- a/modules/globebrowsing/chunk/chunkedlodglobe.cpp +++ /dev/null @@ -1,260 +0,0 @@ -/***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ - -#include - -#include -#include -#include - -#include - - -// open space includes -#include -#include -#include -#include - -#include - -// ghoul includes -#include - -#define _USE_MATH_DEFINES -#include - -#include -#include -namespace { - const std::string _loggerCat = "ChunkLodGlobe"; -} - -namespace openspace { - - const ChunkIndex ChunkedLodGlobe::LEFT_HEMISPHERE_INDEX = ChunkIndex(0, 0, 1); - const ChunkIndex ChunkedLodGlobe::RIGHT_HEMISPHERE_INDEX = ChunkIndex(1, 0, 1); - - const GeodeticPatch ChunkedLodGlobe::COVERAGE = GeodeticPatch(0, 0, 90, 180); - - - ChunkedLodGlobe::ChunkedLodGlobe( - const Ellipsoid& ellipsoid, - size_t segmentsPerPatch, - std::shared_ptr tileProviderManager) - : _ellipsoid(ellipsoid) - , _leftRoot(std::make_unique(Chunk(this, LEFT_HEMISPHERE_INDEX))) - , _rightRoot(std::make_unique(Chunk(this, RIGHT_HEMISPHERE_INDEX))) - , minSplitDepth(2) - , maxSplitDepth(22) - , _savedCamera(nullptr) - , _tileProviderManager(tileProviderManager) - , stats(StatsCollector(absPath("test_stats"), 1, StatsCollector::Enabled::No)) - { - - auto geometry = std::make_shared( - (unsigned int) segmentsPerPatch, - (unsigned int) segmentsPerPatch, - TriangleSoup::Positions::No, - TriangleSoup::TextureCoordinates::Yes, - TriangleSoup::Normals::No); - - _chunkCullers.push_back(std::make_unique()); - _chunkCullers.push_back(std::make_unique(AABB3(vec3(-1, -1, 0), vec3(1, 1, 1e35)))); - - - _chunkEvaluatorByAvailableTiles = std::make_unique(); - _chunkEvaluatorByProjectedArea = std::make_unique(); - _chunkEvaluatorByDistance = std::make_unique(); - - _renderer = std::make_unique(geometry, tileProviderManager); - - } - - ChunkedLodGlobe::~ChunkedLodGlobe() { - - } - - bool ChunkedLodGlobe::initialize() { - return isReady(); - } - - bool ChunkedLodGlobe::deinitialize() { - return true; - } - - bool ChunkedLodGlobe::isReady() const { - bool ready = true; - return ready; - } - - std::shared_ptr ChunkedLodGlobe::getTileProviderManager() const { - return _tileProviderManager; - } - - bool ChunkedLodGlobe::testIfCullable(const Chunk& chunk, const RenderData& renderData) const { - if (debugOptions.doHorizonCulling && _chunkCullers[0]->isCullable(chunk, renderData)) { - return true; - } - if (debugOptions.doFrustumCulling && _chunkCullers[1]->isCullable(chunk, renderData)) { - return true; - } - return false; - } - - const ChunkNode& ChunkedLodGlobe::findChunkNode(const Geodetic2 p) const { - ghoul_assert(COVERAGE.contains(p), "Point must be in lat [-90, 90] and lon [-180, 180]"); - return p.lon < COVERAGE.center().lon ? _leftRoot->find(p) : _rightRoot->find(p); - } - - ChunkNode& ChunkedLodGlobe::findChunkNode(const Geodetic2 p) { - ghoul_assert(COVERAGE.contains(p), "Point must be in lat [-90, 90] and lon [-180, 180]"); - return p.lon < COVERAGE.center().lon ? _leftRoot->find(p) : _rightRoot->find(p); - } - - int ChunkedLodGlobe::getDesiredLevel(const Chunk& chunk, const RenderData& renderData) const { - int desiredLevel = 0; - if (debugOptions.levelByProjAreaElseDistance) { - desiredLevel = _chunkEvaluatorByProjectedArea->getDesiredLevel(chunk, renderData); - } - else { - desiredLevel = _chunkEvaluatorByDistance->getDesiredLevel(chunk, renderData); - } - - - int desiredLevelByAvailableData = _chunkEvaluatorByAvailableTiles->getDesiredLevel(chunk, renderData); - if (desiredLevelByAvailableData != ChunkLevelEvaluator::UNKNOWN_DESIRED_LEVEL) { - desiredLevel = min(desiredLevel, desiredLevelByAvailableData); - } - - desiredLevel = glm::clamp(desiredLevel, minSplitDepth, maxSplitDepth); - return desiredLevel; - } - - void ChunkedLodGlobe::render(const RenderData& data){ - - stats.startNewRecord(); - - int j2000s = Time::now().j2000Seconds(); - - auto duration = std::chrono::system_clock::now().time_since_epoch(); - auto millis = std::chrono::duration_cast(duration).count(); - stats.i["time"] = millis; - - minDistToCamera = INFINITY; - - _leftRoot->updateChunkTree(data); - _rightRoot->updateChunkTree(data); - - // Calculate the MVP matrix - dmat4 viewTransform = dmat4(data.camera.combinedViewMatrix()); - dmat4 vp = dmat4(data.camera.projectionMatrix()) * viewTransform; - dmat4 mvp = vp * _modelTransform; - - // Render function - std::function renderJob = [this, &data, &mvp](const ChunkNode& chunkNode) { - stats.i["chunks"]++; - const Chunk& chunk = chunkNode.getChunk(); - if (chunkNode.isLeaf()){ - stats.i["chunks leafs"]++; - if (chunk.isVisible()) { - stats.i["rendered chunks"]++; - double t0 = Time::now().j2000Seconds(); - _renderer->renderChunk(chunkNode.getChunk(), data); - debugRenderChunk(chunk, mvp); - } - } - }; - - _leftRoot->reverseBreadthFirst(renderJob); - _rightRoot->reverseBreadthFirst(renderJob); - - if (_savedCamera != nullptr) { - DebugRenderer::ref().renderCameraFrustum(data, *_savedCamera); - } - - //LDEBUG("min distnace to camera: " << minDistToCamera); - - Vec3 cameraPos = data.camera.position().dvec3(); - //LDEBUG("cam pos x: " << cameraPos.x << " y: " << cameraPos.y << " z: " << cameraPos.z); - - //LDEBUG("ChunkNode count: " << ChunkNode::chunkNodeCount); - //LDEBUG("RenderedPatches count: " << ChunkNode::renderedChunks); - //LDEBUG(ChunkNode::renderedChunks << " / " << ChunkNode::chunkNodeCount << " chunks rendered"); - } - - - void ChunkedLodGlobe::debugRenderChunk(const Chunk& chunk, const glm::dmat4& mvp) const { - if (debugOptions.showChunkBounds || debugOptions.showChunkAABB) { - const std::vector modelSpaceCorners = chunk.getBoundingPolyhedronCorners(); - std::vector clippingSpaceCorners(8); - AABB3 screenSpaceBounds; - for (size_t i = 0; i < 8; i++) { - const vec4& clippingSpaceCorner = mvp * modelSpaceCorners[i]; - clippingSpaceCorners[i] = clippingSpaceCorner; - - vec3 screenSpaceCorner = (1.0f / clippingSpaceCorner.w) * clippingSpaceCorner; - screenSpaceBounds.expand(screenSpaceCorner); - } - - unsigned int colorBits = 1 + chunk.index().level % 6; - vec4 color = vec4(colorBits & 1, colorBits & 2, colorBits & 4, 0.3); - - if (debugOptions.showChunkBounds) { - DebugRenderer::ref().renderNiceBox(clippingSpaceCorners, color); - } - - if (debugOptions.showChunkAABB) { - auto& screenSpacePoints = DebugRenderer::ref().verticesFor(screenSpaceBounds); - DebugRenderer::ref().renderNiceBox(screenSpacePoints, color); - } - } - } - - void ChunkedLodGlobe::update(const UpdateData& data) { - glm::dmat4 translation = glm::translate(glm::dmat4(1.0), data.modelTransform.translation); - glm::dmat4 rotation = glm::dmat4(data.modelTransform.rotation); - glm::dmat4 scaling = glm::scale(glm::dmat4(1.0), - glm::dvec3(data.modelTransform.scale, data.modelTransform.scale, data.modelTransform.scale)); - - _modelTransform = translation * rotation * scaling; - _inverseModelTransform = glm::inverse(_modelTransform); - - _renderer->update(); - } - - const glm::dmat4& ChunkedLodGlobe::modelTransform() { - return _modelTransform; - } - - const glm::dmat4& ChunkedLodGlobe::inverseModelTransform() { - return _inverseModelTransform; - } - - const Ellipsoid& ChunkedLodGlobe::ellipsoid() const - { - return _ellipsoid; - } - -} // namespace openspace diff --git a/modules/globebrowsing/chunk/chunkedlodglobe.h b/modules/globebrowsing/chunk/chunkedlodglobe.h deleted file mode 100644 index 3d30d01f3b..0000000000 --- a/modules/globebrowsing/chunk/chunkedlodglobe.h +++ /dev/null @@ -1,154 +0,0 @@ -/***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ - -#ifndef __CHUNK_LOD_GLOBE__ -#define __CHUNK_LOD_GLOBE__ - -#include - - -#include - - -// open space includes -#include -#include -#include -#include - -#include - -#include -#include - -#include -#include - - -namespace ghoul { - namespace opengl { - class ProgramObject; - } -} - -namespace openspace { - class ChunkLevelEvaluator; -} - -namespace openspace { - - class ChunkedLodGlobe : public Renderable { - public: - ChunkedLodGlobe( - const Ellipsoid& ellipsoid, - size_t segmentsPerPatch, - std::shared_ptr tileProviderManager); - virtual ~ChunkedLodGlobe(); - - bool initialize() override; - bool deinitialize() override; - bool isReady() const override; - - void render(const RenderData& data) override; - void update(const UpdateData& data) override; - - const ChunkNode& findChunkNode(const Geodetic2 location) const; - ChunkNode& findChunkNode(const Geodetic2 location); - - bool testIfCullable(const Chunk& chunk, const RenderData& renderData) const; - int getDesiredLevel(const Chunk& chunk, const RenderData& renderData) const; - - double minDistToCamera; - - const Ellipsoid& ellipsoid() const; - const glm::dmat4& modelTransform(); - const glm::dmat4& inverseModelTransform(); - - const int minSplitDepth; - const int maxSplitDepth; - - - std::shared_ptr getTileProviderManager() const; - - - const std::shared_ptr getSavedCamera() const { return _savedCamera; } - void setSaveCamera(std::shared_ptr c) { - _savedCamera = c; - } - - - float lodScaleFactor; - - bool atmosphereEnabled; - - struct DebugOptions { - bool showChunkEdges = false; - bool showChunkBounds = false; - bool showChunkAABB = false; - bool showHeightResolution = false; - bool showHeightIntensities = false; - - bool doHorizonCulling = true; - bool doFrustumCulling = true; - bool levelByProjAreaElseDistance = true; - } debugOptions; - - StatsCollector stats; - - private: - - void debugRenderChunk(const Chunk& chunk, const glm::dmat4& data) const; - - static const GeodeticPatch COVERAGE; - - // Covers all negative longitudes - std::unique_ptr _leftRoot; - - // Covers all positive longitudes - std::unique_ptr _rightRoot; - - // the patch used for actual rendering - std::unique_ptr _renderer; - - static const ChunkIndex LEFT_HEMISPHERE_INDEX; - static const ChunkIndex RIGHT_HEMISPHERE_INDEX; - - std::vector> _chunkCullers; - - std::unique_ptr _chunkEvaluatorByAvailableTiles; - std::unique_ptr _chunkEvaluatorByProjectedArea; - std::unique_ptr _chunkEvaluatorByDistance; - - const Ellipsoid& _ellipsoid; - glm::dmat4 _modelTransform; - glm::dmat4 _inverseModelTransform; - - std::shared_ptr _savedCamera; - - std::shared_ptr _tileProviderManager; - }; - -} // namespace openspace - -#endif // __CHUNK_LOD_GLOBE__ \ No newline at end of file diff --git a/modules/globebrowsing/chunk/chunkindex.cpp b/modules/globebrowsing/chunk/chunkindex.cpp deleted file mode 100644 index 1964a8f6c3..0000000000 --- a/modules/globebrowsing/chunk/chunkindex.cpp +++ /dev/null @@ -1,143 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#include -#include - -#include - -namespace { - const std::string _loggerCat = "ChunkIndex"; -} - -namespace openspace { - - /** - Creates the geodetic tile index for the Geodetic patch that covers the - point p at the specified level - */ - ChunkIndex::ChunkIndex(const Geodetic2& point, int level) - : level(level) { - int numIndicesAtLevel = 1 << level; - double u = 0.5 + point.lon / (2 * M_PI); - double v = 0.25 - point.lat / (2 * M_PI); - double xIndexSpace = u * numIndicesAtLevel; - double yIndexSpace = v * numIndicesAtLevel; - - x = floor(xIndexSpace); - y = floor(yIndexSpace); - } - - ChunkIndex ChunkIndex::child(Quad q) const { - return ChunkIndex(2 * x + q % 2, 2 * y + q / 2, level + 1); - } - - ChunkIndex ChunkIndex::parent() const { - //ghoul_assert(level > 0, "tile at level 0 has no parent!"); - return ChunkIndex(x / 2, y / 2, level - 1); - } - - ChunkIndex& ChunkIndex::operator--() { - x /= 2; - y /= 2; - level--; - return *this; - } - - ChunkIndex ChunkIndex::operator--(int) { - ChunkIndex tmp(*this); - --(*this); - return tmp; - } - - ChunkIndex& ChunkIndex::operator-=(unsigned int levels) { - x <<= levels; - y <<= levels; - level -= levels; - return *this; - } - - - /** - Gets the tile at a specified offset from this tile. - Accepts delta indices ranging from [-2^level, Infinity[ - */ - ChunkIndex ChunkIndex::getRelatedTile(int deltaX, int deltaY) const { - int indicesAtThisLevel = 1 << level; - int newX = (indicesAtThisLevel + x + deltaX) % indicesAtThisLevel; - int newY = (indicesAtThisLevel + y + deltaY) % indicesAtThisLevel; - return ChunkIndex(newX, newY, level); - } - - int ChunkIndex::manhattan(const ChunkIndex& other) const { - ghoul_assert(level == other.level, "makes no sense if not on same level"); - return std::abs(x - other.x) + std::abs(y - other.y); - } - - - /** - Creates a hash which can be used as key in hash maps - BITS | USAGE - 0-6 | level - 6-26 | x - 26-46 | y - 46-64 | reserved for future use, e.g. time key - */ - ChunkHashKey ChunkIndex::hashKey() const { - ChunkHashKey key = 0LL; - key |= level; - key |= x << 6; - key |= ((ChunkHashKey)y) << 26; - return key; - } - - - std::string ChunkIndex::toString() const { - std::stringstream ss; - for (int i = level; i > 0; i--){ - char digit = '0'; - int mask = 1 << (i - 1); - if ((x & mask) != 0) { - digit++; - } - if ((y & mask) != 0) { - digit++; - digit++; - } - ss << digit; - } - return ss.str(); - } - - bool ChunkIndex::operator==(const ChunkIndex& other) const { - return x == other.x && y == other.y && level == other.level; - } - - std::ostream& operator<<(std::ostream& os, const ChunkIndex& ci) { - os << "{ x = " << ci.x << ", y = " << ci.y << ", level = " << ci.level << " }"; - return os; - } - - -} // namespace openspace diff --git a/modules/globebrowsing/chunk/chunklevelevaluator.cpp b/modules/globebrowsing/chunk/chunklevelevaluator.cpp index b0c761649f..b536df2dfa 100644 --- a/modules/globebrowsing/chunk/chunklevelevaluator.cpp +++ b/modules/globebrowsing/chunk/chunklevelevaluator.cpp @@ -22,161 +22,166 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ - -#include - -#include - #include + #include -#include -#include - - -#include - -namespace { - const std::string _loggerCat = "ChunkLevelEvaluator"; -} +#include +#include +#include +#include namespace openspace { - +namespace globebrowsing { - int EvaluateChunkLevelByDistance::getDesiredLevel(const Chunk& chunk, const RenderData& data) const { - // Calculations are done in the reference frame of the globe. Hence, the camera - // position needs to be transformed with the inverse model matrix - glm::dmat4 inverseModelTransform = chunk.owner()->inverseModelTransform(); - ChunkedLodGlobe const * globe = chunk.owner(); - const Ellipsoid& ellipsoid = globe->ellipsoid(); +int EvaluateChunkLevelByDistance::getDesiredLevel(const Chunk& chunk, + const RenderData& data) const +{ + // Calculations are done in the reference frame of the globe + // (model space). Hence, the camera position needs to be transformed + // with the inverse model matrix + glm::dmat4 inverseModelTransform = chunk.owner().inverseModelTransform(); + const RenderableGlobe& globe = chunk.owner(); + const Ellipsoid& ellipsoid = globe.ellipsoid(); - Vec3 cameraPosition = - glm::dvec3(inverseModelTransform * glm::dvec4(data.camera.positionVec3(), 1)); - Geodetic2 pointOnPatch = chunk.surfacePatch().closestPoint( - ellipsoid.cartesianToGeodetic2(cameraPosition)); + glm::dvec3 cameraPosition = + glm::dvec3(inverseModelTransform * glm::dvec4(data.camera.positionVec3(), 1)); - Chunk::BoundingHeights heights = chunk.getBoundingHeights(); - - Vec3 patchPosition = ellipsoid.cartesianSurfacePosition(pointOnPatch); - Vec3 cameraToChunk = patchPosition - cameraPosition; - - - // Calculate desired level based on distance - Scalar distanceToPatch = glm::length(cameraToChunk); - Scalar distance = distanceToPatch -heights.min; // distance to actual minimum heights - - Scalar scaleFactor = globe->lodScaleFactor * ellipsoid.minimumRadius(); - Scalar projectedScaleFactor = scaleFactor / distance; - int desiredLevel = ceil(log2(projectedScaleFactor)); - return desiredLevel; - } - - int EvaluateChunkLevelByProjectedArea::getDesiredLevel(const Chunk& chunk, const RenderData& data) const { - // Calculations are done in the reference frame of the globe. Hence, the camera - // position needs to be transformed with the inverse model matrix - glm::dmat4 inverseModelTransform = chunk.owner()->inverseModelTransform(); - - ChunkedLodGlobe const * globe = chunk.owner(); - const Ellipsoid& ellipsoid = globe->ellipsoid(); - glm::dvec4 cameraPositionModelSpace = glm::dvec4(data.camera.positionVec3(), 1); - Vec3 cameraPosition = glm::dvec3(inverseModelTransform * cameraPositionModelSpace); - Vec3 cameraToEllipsoidCenter = -cameraPosition; - - Geodetic2 cameraGeodeticPos = ellipsoid.cartesianToGeodetic2(cameraPosition); + Geodetic2 pointOnPatch = chunk.surfacePatch().closestPoint( + ellipsoid.cartesianToGeodetic2(cameraPosition) + ); + glm::dvec3 patchNormal = ellipsoid.geodeticSurfaceNormal(pointOnPatch); + glm::dvec3 patchPosition = ellipsoid.cartesianSurfacePosition(pointOnPatch); - // Approach: - // The projected area of the chunk will be calculated based on a small area that - // is close to the camera, and the scaled up to represent the full area. - // The advantage of doing this is that it will better handle the cases where the - // full patch is very curved (e.g. stretches from latitude 0 to 90 deg). + Chunk::BoundingHeights heights = chunk.getBoundingHeights(); + double heightToChunk = heights.min; + + // Offset position according to height + patchPosition += patchNormal * heightToChunk; + + glm::dvec3 cameraToChunk = patchPosition - cameraPosition; + + // Calculate desired level based on distance + double distanceToPatch = glm::length(cameraToChunk); + double distance = distanceToPatch; + + double scaleFactor = + globe.generalProperties().lodScaleFactor * ellipsoid.minimumRadius(); + double projectedScaleFactor = scaleFactor / distance; + int desiredLevel = ceil(log2(projectedScaleFactor)); + return desiredLevel; +} + +int EvaluateChunkLevelByProjectedArea::getDesiredLevel(const Chunk& chunk, + const RenderData& data) const +{ + // Calculations are done in the reference frame of the globe + // (model space). Hence, the camera position needs to be transformed + // with the inverse model matrix + glm::dmat4 inverseModelTransform = chunk.owner().inverseModelTransform(); + + const RenderableGlobe& globe = chunk.owner(); + const Ellipsoid& ellipsoid = globe.ellipsoid(); + glm::dvec4 cameraPositionModelSpace = glm::dvec4(data.camera.positionVec3(), 1); + glm::dvec3 cameraPosition = + glm::dvec3(inverseModelTransform * cameraPositionModelSpace); + glm::dvec3 cameraToEllipsoidCenter = -cameraPosition; + + Geodetic2 cameraGeodeticPos = ellipsoid.cartesianToGeodetic2(cameraPosition); - const Geodetic2 center = chunk.surfacePatch().center(); - const Geodetic2 closestCorner = chunk.surfacePatch().closestCorner(cameraGeodeticPos); - - - // Camera - // | - // V - // - // oo - // [ ]< - // *geodetic space* - // - // closestCorner - // +-----------------+ <-- north east corner - // | | - // | center | - // | | - // +-----------------+ <-- south east corner - - + // Approach: + // The projected area of the chunk will be calculated based on a small area that + // is close to the camera, and the scaled up to represent the full area. + // The advantage of doing this is that it will better handle the cases where the + // full patch is very curved (e.g. stretches from latitude 0 to 90 deg). - Chunk::BoundingHeights heights = chunk.getBoundingHeights(); - const Geodetic3 c = { center, heights.min }; - const Geodetic3 c1 = { Geodetic2(center.lat, closestCorner.lon), heights.min }; - const Geodetic3 c2 = { Geodetic2(closestCorner.lat, center.lon), heights.min }; + const Geodetic2 center = chunk.surfacePatch().center(); + const Geodetic2 closestCorner = chunk.surfacePatch().closestCorner(cameraGeodeticPos); + + // Camera + // | + // V + // + // oo + // [ ]< + // *geodetic space* + // + // closestCorner + // +-----------------+ <-- north east corner + // | | + // | center | + // | | + // +-----------------+ <-- south east corner - // Camera - // | - // V - // - // oo - // [ ]< - // *geodetic space* - // - // +--------c2-------+ <-- north east corner - // | | - // c1 c | - // | | - // +-----------------+ <-- south east corner + Chunk::BoundingHeights heights = chunk.getBoundingHeights(); + const Geodetic3 c = { center, heights.min }; + const Geodetic3 c1 = { Geodetic2(center.lat, closestCorner.lon), heights.min }; + const Geodetic3 c2 = { Geodetic2(closestCorner.lat, center.lon), heights.min }; + + // Camera + // | + // V + // + // oo + // [ ]< + // *geodetic space* + // + // +--------c2-------+ <-- north east corner + // | | + // c1 c | + // | | + // +-----------------+ <-- south east corner - // Go from geodetic to cartesian space - Vec3 A = cameraToEllipsoidCenter + ellipsoid.cartesianPosition(c); - Vec3 B = cameraToEllipsoidCenter + ellipsoid.cartesianPosition(c1); - Vec3 C = cameraToEllipsoidCenter + ellipsoid.cartesianPosition(c2); + // Go from geodetic to cartesian space + glm::dvec3 A = cameraToEllipsoidCenter + ellipsoid.cartesianPosition(c); + glm::dvec3 B = cameraToEllipsoidCenter + ellipsoid.cartesianPosition(c1); + glm::dvec3 C = cameraToEllipsoidCenter + ellipsoid.cartesianPosition(c2); - // Project onto unit sphere - A = glm::normalize(A); - B = glm::normalize(B); - C = glm::normalize(C); + // Project onto unit sphere + A = glm::normalize(A); + B = glm::normalize(B); + C = glm::normalize(C); - // Camera *cartesian space* - // | +--------+---+ - // V __--'' __--'' / - // C-------A--------- + - // oo / / / - //[ ]< +-------B----------+ - // + // Camera *cartesian space* + // | +--------+---+ + // V __--'' __--'' / + // C-------A--------- + + // oo / / / + //[ ]< +-------B----------+ + // - // If the geodetic patch is small (i.e. has small width), that means the patch in - // cartesian space will be almost flat, and in turn, the triangle ABC will roughly - // correspond to 1/8 of the full area - const Vec3 AB = B - A; - const Vec3 AC = C - A; - double areaABC = 0.5 * glm::length(glm::cross(AC, AB)); - double projectedChunkAreaApprox = 8 * areaABC; + // If the geodetic patch is small (i.e. has small width), that means the patch in + // cartesian space will be almost flat, and in turn, the triangle ABC will roughly + // correspond to 1/8 of the full area + const glm::dvec3 AB = B - A; + const glm::dvec3 AC = C - A; + double areaABC = 0.5 * glm::length(glm::cross(AC, AB)); + double projectedChunkAreaApprox = 8 * areaABC; - double scaledArea = globe->lodScaleFactor * projectedChunkAreaApprox; - return chunk.index().level + round(scaledArea - 1); - } + double scaledArea = + globe.generalProperties().lodScaleFactor * projectedChunkAreaApprox; + return chunk.tileIndex().level + round(scaledArea - 1); +} - int EvaluateChunkLevelByAvailableTileData::getDesiredLevel(const Chunk& chunk, const RenderData& data) const { - auto tileProvidermanager = chunk.owner()->getTileProviderManager(); - auto heightMapProviders = tileProvidermanager->getTileProviderGroup(LayeredTextures::HeightMaps).getActiveTileProviders(); - int currLevel = chunk.index().level; - - for (size_t i = 0; i < LayeredTextures::NUM_TEXTURE_CATEGORIES; i++) { - auto tileProviderGroup = tileProvidermanager->getTileProviderGroup(i); - for (auto tileProvider : tileProviderGroup.getActiveTileProviders()) { - Tile::Status tileStatus = tileProvider->getTileStatus(chunk.index()); - - if (tileStatus == Tile::Status::OK) { - return UNKNOWN_DESIRED_LEVEL; - } +int EvaluateChunkLevelByAvailableTileData::getDesiredLevel(const Chunk& chunk, + const RenderData& data) const +{ + auto layerManager = chunk.owner().chunkedLodGlobe()->layerManager(); + auto heightLayers = layerManager->layerGroup(LayerManager::HeightLayers).activeLayers(); + int currLevel = chunk.tileIndex().level; + + for (size_t i = 0; i < LayerManager::NUM_LAYER_GROUPS; ++i) { + for (auto& layer : layerManager->layerGroup(i).activeLayers()) { + Tile::Status tileStatus = + layer->tileProvider()->getTileStatus(chunk.tileIndex()); + if (tileStatus == Tile::Status::OK) { + return UNKNOWN_DESIRED_LEVEL; } } - - return currLevel - 1;; } + return currLevel - 1; +} + +} // namespace globebrowsing } // namespace openspace diff --git a/modules/globebrowsing/chunk/chunklevelevaluator.h b/modules/globebrowsing/chunk/chunklevelevaluator.h index 6d74782127..f8998a0cbf 100644 --- a/modules/globebrowsing/chunk/chunklevelevaluator.h +++ b/modules/globebrowsing/chunk/chunklevelevaluator.h @@ -22,44 +22,61 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __CHUNK_LEVEL_EVALUATOR_H__ -#define __CHUNK_LEVEL_EVALUATOR_H__ - -#include -#include -#include -#include - -#include - +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___CHUNKLEVELEVALUATOR___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___CHUNKLEVELEVALUATOR___H__ namespace openspace { - class ChunkLevelEvaluator { - public: - virtual int getDesiredLevel(const Chunk& chunk, const RenderData& data) const = 0; - static const int UNKNOWN_DESIRED_LEVEL = -1; - }; +struct RenderData; +namespace globebrowsing { +class Chunk; - class EvaluateChunkLevelByDistance : public ChunkLevelEvaluator { - public: - virtual int getDesiredLevel(const Chunk& chunk, const RenderData& data) const; - }; +/** + * Abstract class defining an interface for accessing a desired level of a Chunk. + * The desired level can be used in the process of determining whether a Chunk should + * want to split, merge or do nothing. +*/ +class ChunkLevelEvaluator { +public: + virtual int getDesiredLevel(const Chunk& chunk, const RenderData& data) const = 0; + static const int UNKNOWN_DESIRED_LEVEL = -1; +}; - class EvaluateChunkLevelByProjectedArea : public ChunkLevelEvaluator { - public: - virtual int getDesiredLevel(const Chunk& chunk, const RenderData& data) const; - }; +/** + * Evaluate the Chunk level depending on the distance from the Camera to the Chunk. + * This evaluation method aims to keep the screen size (horizontal length and not + * area) of all chunks constant. +*/ +class EvaluateChunkLevelByDistance : public ChunkLevelEvaluator { +public: + virtual int getDesiredLevel(const Chunk& chunk, const RenderData& data) const; +}; - class EvaluateChunkLevelByAvailableTileData : public ChunkLevelEvaluator { - public: - virtual int getDesiredLevel(const Chunk& chunk, const RenderData& data) const; - }; +/** + * Evaluate the chunk level using the area of the non-heightmapped Chunk projected + * on a sphere with the center in the position of the camera. A Chunk near the + * horizon will have a small projected area and hence a lower desired level. This + * evaluation is more forgiving than EvaluateChunkLevelByDistance, meaning it results + * in lower desired levels. +*/ +class EvaluateChunkLevelByProjectedArea : public ChunkLevelEvaluator { +public: + virtual int getDesiredLevel(const Chunk& chunk, const RenderData& data) const; +}; -} +/** + * If this chunk has available tile data for any LayerGroup on any of its active + * Layers it will return an UNKNOWN_DESIRED_LEVEL. If no data is available it will + * evaluate to a level that is current level -1. +*/ +class EvaluateChunkLevelByAvailableTileData : public ChunkLevelEvaluator { +public: + virtual int getDesiredLevel(const Chunk& chunk, const RenderData& data) const; +}; +} // namespace globebrowsing +} // namespace openspace - -#endif // __CHUNK_LEVEL_EVALUATOR_H__ +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___CHUNKLEVELEVALUATOR___H__ diff --git a/modules/globebrowsing/chunk/chunknode.cpp b/modules/globebrowsing/chunk/chunknode.cpp index 2198fc4276..9d67ebcbe8 100644 --- a/modules/globebrowsing/chunk/chunknode.cpp +++ b/modules/globebrowsing/chunk/chunknode.cpp @@ -22,34 +22,23 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include +#include #include -#include -#include - -#include -#include -#include - - -namespace { - const std::string _loggerCat = "ChunkNode"; -} +#include +#include namespace openspace { +namespace globebrowsing { int ChunkNode::chunkNodeCount = 0; ChunkNode::ChunkNode(const Chunk& chunk, ChunkNode* parent) -: _chunk(chunk) -, _parent(parent) + : _chunk(chunk) + , _parent(parent) + , _children({ nullptr, nullptr, nullptr, nullptr }) { - _children[0] = nullptr; - _children[1] = nullptr; - _children[2] = nullptr; - _children[3] = nullptr; chunkNodeCount++; } @@ -65,12 +54,7 @@ bool ChunkNode::isLeaf() const { return _children[0] == nullptr; } - -// Returns true or false wether this node can be merge or not bool ChunkNode::updateChunkTree(const RenderData& data) { - //Geodetic2 center = _chunk.surfacePatch.center(); - //LDEBUG("x: " << patch.x << " y: " << patch.y << " level: " << patch.level << " lat: " << center.lat << " lon: " << center.lon); - if (isLeaf()) { Chunk::Status status = _chunk.update(data); if (status == Chunk::Status::WANT_SPLIT) { @@ -126,7 +110,8 @@ void ChunkNode::breadthFirst(const std::function& f) con } } -void ChunkNode::reverseBreadthFirst(const std::function& f) const { +void ChunkNode::reverseBreadthFirst(const std::function& f) const +{ std::stack S; std::queue Q; @@ -141,9 +126,12 @@ void ChunkNode::reverseBreadthFirst(const std::function& // Add children to queue, if any if (!node->isLeaf()) { - for (int i = 0; i < 4; ++i) { - Q.push(node->_children[i].get()); + for (const auto& c : node->_children) { + Q.push(c.get()); } + //for (int i = 0; i < 4; ++i) { + // Q.push(node->_children[i].get()); + //} } } @@ -154,29 +142,21 @@ void ChunkNode::reverseBreadthFirst(const std::function& } } -#define CHUNK_NODE_FIND(node, p) \ - while (!node->isLeaf()) { \ - const Geodetic2 center = node->_chunk.surfacePatch().center();\ - int index = 0;\ - if (center.lon < p.lon) {\ - ++index;\ - }\ - if (p.lat < center.lat) {\ - ++index;\ - ++index;\ - }\ - node = &(node->getChild((Quad)index));\ - } - const ChunkNode& ChunkNode::find(const Geodetic2& location) const { const ChunkNode* node = this; - CHUNK_NODE_FIND(node, location); - return *node; -} -ChunkNode& ChunkNode::find(const Geodetic2& location) { - ChunkNode* node = this; - CHUNK_NODE_FIND(node, location); + while (!node->isLeaf()) { + const Geodetic2 center = node->_chunk.surfacePatch().center(); + int index = 0; + if (center.lon < location.lon) { + ++index; + } + if (location.lat < center.lat) { + ++index; + ++index; + } + node = &(node->getChild((Quad)index)); + } return *node; } @@ -184,27 +164,23 @@ const ChunkNode& ChunkNode::getChild(Quad quad) const { return *_children[quad]; } -ChunkNode& ChunkNode::getChild(Quad quad) { - return *_children[quad]; -} - void ChunkNode::split(int depth) { if (depth > 0 && isLeaf()) { - for (size_t i = 0; i < 4; i++) { - Chunk chunk(_chunk.owner(), _chunk.index().child((Quad)i)); - _children[i] = std::unique_ptr(new ChunkNode(chunk, this)); + for (size_t i = 0; i < _children.size(); i++) { + Chunk chunk(_chunk.owner(), _chunk.tileIndex().child((Quad)i)); + _children[i] = std::make_unique(chunk, this); } } if (depth - 1 > 0) { - for (int i = 0; i < 4; ++i) { + for (int i = 0; i < _children.size(); ++i) { _children[i]->split(depth - 1); } } } void ChunkNode::merge() { - for (int i = 0; i < 4; ++i) { + for (int i = 0; i < _children.size(); ++i) { if (_children[i] != nullptr) { _children[i]->merge(); } @@ -214,11 +190,9 @@ void ChunkNode::merge() { ghoul_assert(isLeaf(), "ChunkNode must be leaf after merge"); } - const Chunk& ChunkNode::getChunk() const { return _chunk; } - - +} // namespace globebrowsing } // namespace openspace diff --git a/modules/globebrowsing/chunk/chunknode.h b/modules/globebrowsing/chunk/chunknode.h index 3968559cee..8f4d59f023 100644 --- a/modules/globebrowsing/chunk/chunknode.h +++ b/modules/globebrowsing/chunk/chunknode.h @@ -22,41 +22,36 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __QUADTREE_H__ -#define __QUADTREE_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___CHUNKNODE___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___CHUNKNODE___H__ -#include -#include -#include -#include -#include - -#include #include -#include - -#include +#include #include - - - -// forward declaration -namespace openspace { - class ChunkedLodGlobe; -} - +#include namespace openspace { +namespace globebrowsing { +class ChunkedLodGlobe; class ChunkNode { public: ChunkNode(const Chunk& chunk, ChunkNode* parent = nullptr); ~ChunkNode(); - + /** + * Recursively split the ChunkNode. + * + * \param depth defines how deep the recursion should go. If depth == 1 (default), + * the ChunkNode will only split once. + */ void split(int depth = 1); + + /** + * Deletes all children of the ChunkNode recursively. + */ void merge(); bool isRoot() const; @@ -67,28 +62,28 @@ public: void reverseBreadthFirst(const std::function& f) const; const ChunkNode& find(const Geodetic2& location) const; - ChunkNode& find(const Geodetic2& location); - const ChunkNode& getChild(Quad quad) const; - ChunkNode& getChild(Quad quad); - const Chunk& getChunk() const; + /** + * Updates all children recursively. If this ChunkNode wants to split it will, + * otherwise check if the children wants to merge. If all children wants to merge + * and the Status of this Chunk is not Status::WANT_SPLIT it will merge. + * + * \returns true if the ChunkNode can merge and false if it can not merge. + */ bool updateChunkTree(const RenderData& data); static int chunkNodeCount; - -private: - +private: ChunkNode* _parent; - std::unique_ptr _children[4]; + std::array, 4> _children; Chunk _chunk; }; +} // namespace globebrowsing } // namespace openspace - - -#endif // __QUADTREE_H__ +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___CHUNKNODE___H__ diff --git a/modules/globebrowsing/chunk/chunkrenderer.cpp b/modules/globebrowsing/chunk/chunkrenderer.cpp deleted file mode 100644 index 7d7cc560fe..0000000000 --- a/modules/globebrowsing/chunk/chunkrenderer.cpp +++ /dev/null @@ -1,471 +0,0 @@ -/***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ - - -#include -#include -#include -#include - -// open space includes -#include -#include -#include - -// ghoul includes -#include -#include -#include - -// STL includes -#include - -#define _USE_MATH_DEFINES -#include - -namespace { - const std::string _loggerCat = "PatchRenderer"; - - const std::string keyFrame = "Frame"; - const std::string keyGeometry = "Geometry"; - const std::string keyShading = "PerformShading"; - - const std::string keyBody = "Body"; -} - -namespace openspace { - - - ChunkRenderer::ChunkRenderer( - std::shared_ptr grid, - std::shared_ptr tileProviderManager) - : _tileProviderManager(tileProviderManager) - , _grid(grid) - { - _globalRenderingShaderProvider = std::make_shared( - "GlobalChunkedLodPatch", - "${MODULE_GLOBEBROWSING}/shaders/globalchunkedlodpatch_vs.glsl", - "${MODULE_GLOBEBROWSING}/shaders/globalchunkedlodpatch_fs.glsl"); - - _localRenderingShaderProvider = std::make_shared( - "LocalChunkedLodPatch", - "${MODULE_GLOBEBROWSING}/shaders/localchunkedlodpatch_vs.glsl", - "${MODULE_GLOBEBROWSING}/shaders/localchunkedlodpatch_fs.glsl"); - - _globalProgramUniformHandler = std::make_shared(); - _localProgramUniformHandler = std::make_shared(); - - } - - void ChunkRenderer::renderChunk(const Chunk& chunk, const RenderData& data) { - if (chunk.index().level < 10) { - renderChunkGlobally(chunk, data); - } - else { - renderChunkLocally(chunk, data); - } - } - - void ChunkRenderer::update() { - // unued atm. Could be used for caching or precalculating - } - - - void ChunkRenderer::setDepthTransformUniforms( - std::shared_ptr uniformIdHandler, - LayeredTextures::TextureCategory textureCategory, - LayeredTextureShaderUniformIdHandler::BlendLayerSuffixes blendLayerSuffix, - size_t layerIndex, - const TileDepthTransform& tileDepthTransform) - { - uniformIdHandler->programObject().setUniform( - uniformIdHandler->getId( - textureCategory, - blendLayerSuffix, - layerIndex, - LayeredTextureShaderUniformIdHandler::GlslTileDataId::depthTransform_depthScale), - tileDepthTransform.depthScale); - - uniformIdHandler->programObject().setUniform( - uniformIdHandler->getId( - textureCategory, - blendLayerSuffix, - layerIndex, - LayeredTextureShaderUniformIdHandler::GlslTileDataId::depthTransform_depthOffset), - tileDepthTransform.depthOffset); - - } - - void ChunkRenderer::activateTileAndSetTileUniforms( - std::shared_ptr uniformIdHandler, - LayeredTextures::TextureCategory textureCategory, - LayeredTextureShaderUniformIdHandler::BlendLayerSuffixes blendLayerSuffix, - size_t layerIndex, - ghoul::opengl::TextureUnit& texUnit, - const TileAndTransform& tileAndTransform) - { - - // Blend tile with two parents - // The texture needs a unit to sample from - texUnit.activate(); - tileAndTransform.tile.texture->bind(); - - uniformIdHandler->programObject().setUniform( - uniformIdHandler->getId( - textureCategory, - blendLayerSuffix, - layerIndex, - LayeredTextureShaderUniformIdHandler::GlslTileDataId::textureSampler), - texUnit); - uniformIdHandler->programObject().setUniform( - uniformIdHandler->getId( - textureCategory, - blendLayerSuffix, - layerIndex, - LayeredTextureShaderUniformIdHandler::GlslTileDataId::uvTransform_uvScale), - tileAndTransform.uvTransform.uvScale); - uniformIdHandler->programObject().setUniform( - uniformIdHandler->getId( - textureCategory, - blendLayerSuffix, - layerIndex, - LayeredTextureShaderUniformIdHandler::GlslTileDataId::uvTransform_uvOffset), - tileAndTransform.uvTransform.uvOffset); - } - - - ProgramObject* ChunkRenderer::getActivatedProgramWithTileData( - LayeredTextureShaderProvider* layeredTextureShaderProvider, - std::shared_ptr programUniformHandler, - const Chunk& chunk) - { - const ChunkIndex& chunkIndex = chunk.index(); - - std::array >, - LayeredTextures::NUM_TEXTURE_CATEGORIES> tileProviders; - LayeredTexturePreprocessingData layeredTexturePreprocessingData; - - for (size_t category = 0; category < LayeredTextures::NUM_TEXTURE_CATEGORIES; category++) { - tileProviders[category] = _tileProviderManager->getTileProviderGroup(category).getActiveTileProviders(); - - LayeredTextureInfo layeredTextureInfo; - layeredTextureInfo.lastLayerIdx = tileProviders[category].size() - 1; - layeredTextureInfo.layerBlendingEnabled = _tileProviderManager->getTileProviderGroup(category).levelBlendingEnabled; - - layeredTexturePreprocessingData.layeredTextureInfo[category] = layeredTextureInfo; - } - - layeredTexturePreprocessingData.keyValuePairs.push_back( - std::pair( - "useAtmosphere", - std::to_string(chunk.owner()->atmosphereEnabled))); - - layeredTexturePreprocessingData.keyValuePairs.push_back( - std::pair( - "showChunkEdges", - std::to_string(chunk.owner()->debugOptions.showChunkEdges))); - - - layeredTexturePreprocessingData.keyValuePairs.push_back( - std::pair( - "showHeightResolution", - std::to_string(chunk.owner()->debugOptions.showHeightResolution))); - - layeredTexturePreprocessingData.keyValuePairs.push_back( - std::pair( - "showHeightIntensities", - std::to_string(chunk.owner()->debugOptions.showHeightIntensities))); - - layeredTexturePreprocessingData.keyValuePairs.push_back( - std::pair( - "defaultHeight", - std::to_string(Chunk::DEFAULT_HEIGHT))); - - - - - // Now the shader program can be accessed - ProgramObject* programObject = - layeredTextureShaderProvider->getUpdatedShaderProgram( - layeredTexturePreprocessingData); - - programUniformHandler->updateIdsIfNecessary(layeredTextureShaderProvider); - - // Activate the shader program - programObject->activate(); - - // Initialize all texture units - struct BlendTexUnits { - ghoul::opengl::TextureUnit blendTexture0; - ghoul::opengl::TextureUnit blendTexture1; - ghoul::opengl::TextureUnit blendTexture2; - }; - std::array, LayeredTextures::NUM_TEXTURE_CATEGORIES> texUnits; - for (size_t category = 0; category < LayeredTextures::NUM_TEXTURE_CATEGORIES; category++) { - texUnits[category].resize(tileProviders[category].size()); - } - - // Go through all the categories - for (size_t category = 0; category < LayeredTextures::NUM_TEXTURE_CATEGORIES; category++) { - // Go through all the providers in this category - int i = 0; - for (auto it = tileProviders[category].begin(); it != tileProviders[category].end(); it++) { - auto tileProvider = it->get(); - - // Get the texture that should be used for rendering - TileAndTransform tileAndTransform = TileSelector::getHighestResolutionTile(tileProvider, chunkIndex); - if (tileAndTransform.tile.status == Tile::Status::Unavailable) { - tileAndTransform.tile = tileProvider->getDefaultTile(); - tileAndTransform.uvTransform.uvOffset = { 0, 0 }; - tileAndTransform.uvTransform.uvScale = { 1, 1 }; - } - - activateTileAndSetTileUniforms( - programUniformHandler, - LayeredTextures::TextureCategory(category), - LayeredTextureShaderUniformIdHandler::BlendLayerSuffixes::none, - i, - texUnits[category][i].blendTexture0, - tileAndTransform); - - // If blending is enabled, two more textures are needed - if (layeredTexturePreprocessingData.layeredTextureInfo[category].layerBlendingEnabled) { - TileAndTransform tileAndTransformParent1 = TileSelector::getHighestResolutionTile(tileProvider, chunkIndex, 1); - if (tileAndTransformParent1.tile.status == Tile::Status::Unavailable) { - tileAndTransformParent1 = tileAndTransform; - } - activateTileAndSetTileUniforms( - programUniformHandler, - LayeredTextures::TextureCategory(category), - LayeredTextureShaderUniformIdHandler::BlendLayerSuffixes::Parent1, - i, - texUnits[category][i].blendTexture1, - tileAndTransformParent1); - - TileAndTransform tileAndTransformParent2 = TileSelector::getHighestResolutionTile(tileProvider, chunkIndex, 2); - if (tileAndTransformParent2.tile.status == Tile::Status::Unavailable) { - tileAndTransformParent2 = tileAndTransformParent1; - } - activateTileAndSetTileUniforms( - programUniformHandler, - LayeredTextures::TextureCategory(category), - LayeredTextureShaderUniformIdHandler::BlendLayerSuffixes::Parent2, - i, - texUnits[category][i].blendTexture2, - tileAndTransformParent2); - } - - /* - if (category == LayeredTextures::HeightMaps && tileAndTransform.tile.preprocessData) { - //auto preprocessingData = tileAndTransform.tile.preprocessData; - //float noDataValue = preprocessingData->noDataValues[0]; - programObject->setUniform( - "minimumValidHeight[" + std::to_string(i) + "]", - -100000); - } - */ - i++; - } - } - - // Go through all the height maps and set depth tranforms - int i = 0; - auto it = tileProviders[LayeredTextures::HeightMaps].begin(); - auto end = tileProviders[LayeredTextures::HeightMaps].end(); - for (; it != end; it++) { - auto tileProvider = *it; - - TileDepthTransform depthTransform = tileProvider->depthTransform(); - setDepthTransformUniforms( - programUniformHandler, - LayeredTextures::TextureCategory::HeightMaps, - LayeredTextureShaderUniformIdHandler::BlendLayerSuffixes::none, - i, - depthTransform); - i++; - } - - // The length of the skirts is proportional to its size - programObject->setUniform("skirtLength", min(static_cast(chunk.surfacePatch().halfSize().lat * 1000000), 8700.0f)); - programObject->setUniform("xSegments", _grid->xSegments()); - - if (chunk.owner()->debugOptions.showHeightResolution) { - programObject->setUniform("vertexResolution", glm::vec2(_grid->xSegments(), _grid->ySegments())); - } - - return programObject; - } - - void ChunkRenderer::renderChunkGlobally(const Chunk& chunk, const RenderData& data){ - - ProgramObject* programObject = getActivatedProgramWithTileData( - _globalRenderingShaderProvider.get(), - _globalProgramUniformHandler, - chunk); - if (programObject == nullptr) { - return; - } - - const Ellipsoid& ellipsoid = chunk.owner()->ellipsoid(); - - bool performAnyBlending = false; - - for (int i = 0; i < LayeredTextures::NUM_TEXTURE_CATEGORIES; ++i) { - LayeredTextures::TextureCategory category = (LayeredTextures::TextureCategory)i; - if(_tileProviderManager->getTileProviderGroup(i).levelBlendingEnabled && _tileProviderManager->getTileProviderGroup(category).getActiveTileProviders().size() > 0){ - performAnyBlending = true; - break; - } - } - if (performAnyBlending) { - // Calculations are done in the reference frame of the globe. Hence, the camera - // position needs to be transformed with the inverse model matrix - glm::dmat4 inverseModelTransform = chunk.owner()->inverseModelTransform(); - glm::dvec3 cameraPosition = - glm::dvec3(inverseModelTransform * glm::dvec4(data.camera.positionVec3(), 1)); - float distanceScaleFactor = chunk.owner()->lodScaleFactor * ellipsoid.minimumRadius(); - programObject->setUniform("cameraPosition", vec3(cameraPosition)); - programObject->setUniform("distanceScaleFactor", distanceScaleFactor); - programObject->setUniform("chunkLevel", chunk.index().level); - } - - // Calculate other uniform variables needed for rendering - Geodetic2 swCorner = chunk.surfacePatch().getCorner(Quad::SOUTH_WEST); - auto patchSize = chunk.surfacePatch().size(); - - dmat4 modelTransform = chunk.owner()->modelTransform(); - dmat4 viewTransform = data.camera.combinedViewMatrix(); - mat4 modelViewTransform = mat4(viewTransform * modelTransform); - mat4 modelViewProjectionTransform = data.camera.projectionMatrix() * modelViewTransform; - - // Upload the uniform variables - programObject->setUniform("modelViewProjectionTransform", modelViewProjectionTransform); - programObject->setUniform("minLatLon", vec2(swCorner.toLonLatVec2())); - programObject->setUniform("lonLatScalingFactor", vec2(patchSize.toLonLatVec2())); - programObject->setUniform("radiiSquared", vec3(ellipsoid.radiiSquared())); - - if (_tileProviderManager->getTileProviderGroup( - LayeredTextures::NightTextures).getActiveTileProviders().size() > 0 || - _tileProviderManager->getTileProviderGroup( - LayeredTextures::WaterMasks).getActiveTileProviders().size() > 0) { - glm::vec3 directionToSunWorldSpace = - glm::normalize(-data.modelTransform.translation); - glm::vec3 directionToSunCameraSpace = - (viewTransform * glm::dvec4(directionToSunWorldSpace, 0)); - data.modelTransform.translation; - programObject->setUniform("modelViewTransform", modelViewTransform); - programObject->setUniform("lightDirectionCameraSpace", -directionToSunCameraSpace); - } - - // OpenGL rendering settings - glEnable(GL_DEPTH_TEST); - glEnable(GL_CULL_FACE); - glCullFace(GL_BACK); - - // render - _grid->geometry().drawUsingActiveProgram(); - - // disable shader - programObject->deactivate(); - } - - - - void ChunkRenderer::renderChunkLocally(const Chunk& chunk, const RenderData& data) { - - ProgramObject* programObject = getActivatedProgramWithTileData( - _localRenderingShaderProvider.get(), - _localProgramUniformHandler, - chunk); - if (programObject == nullptr) { - return; - } - - using namespace glm; - - const Ellipsoid& ellipsoid = chunk.owner()->ellipsoid(); - - - bool performAnyBlending = false; - for (int i = 0; i < LayeredTextures::NUM_TEXTURE_CATEGORIES; ++i) { - LayeredTextures::TextureCategory category = (LayeredTextures::TextureCategory)i; - if (_tileProviderManager->getTileProviderGroup(i).levelBlendingEnabled && _tileProviderManager->getTileProviderGroup(category).getActiveTileProviders().size() > 0) { - performAnyBlending = true; - break; - } - } - if (performAnyBlending) { - float distanceScaleFactor = chunk.owner()->lodScaleFactor * chunk.owner()->ellipsoid().minimumRadius(); - programObject->setUniform("distanceScaleFactor", distanceScaleFactor); - programObject->setUniform("chunkLevel", chunk.index().level); - } - - // Calculate other uniform variables needed for rendering - dmat4 modelTransform = chunk.owner()->modelTransform(); - dmat4 viewTransform = data.camera.combinedViewMatrix(); - dmat4 modelViewTransform = viewTransform * modelTransform; - - std::vector cornerNames = { "p01", "p11", "p00", "p10" }; - std::vector cornersCameraSpace(4); - for (int i = 0; i < 4; ++i) { - Quad q = (Quad)i; - Geodetic2 corner = chunk.surfacePatch().getCorner(q); - Vec3 cornerModelSpace = ellipsoid.cartesianSurfacePosition(corner); - Vec3 cornerCameraSpace = Vec3(dmat4(modelViewTransform) * glm::dvec4(cornerModelSpace, 1)); - cornersCameraSpace[i] = cornerCameraSpace; - programObject->setUniform(cornerNames[i], vec3(cornerCameraSpace)); - } - - vec3 patchNormalCameraSpace = normalize( - cross(cornersCameraSpace[Quad::SOUTH_EAST] - cornersCameraSpace[Quad::SOUTH_WEST], - cornersCameraSpace[Quad::NORTH_EAST] - cornersCameraSpace[Quad::SOUTH_WEST])); - - programObject->setUniform("patchNormalCameraSpace", patchNormalCameraSpace); - programObject->setUniform("projectionTransform", data.camera.projectionMatrix()); - - if (_tileProviderManager->getTileProviderGroup( - LayeredTextures::NightTextures).getActiveTileProviders().size() > 0 || - _tileProviderManager->getTileProviderGroup( - LayeredTextures::WaterMasks).getActiveTileProviders().size() > 0) { - glm::vec3 directionToSunWorldSpace = - glm::normalize(-data.modelTransform.translation); - glm::vec3 directionToSunCameraSpace = - (viewTransform * glm::dvec4(directionToSunWorldSpace, 0)); - data.modelTransform.translation; - programObject->setUniform("lightDirectionCameraSpace", -directionToSunCameraSpace); - } - - - // OpenGL rendering settings - glEnable(GL_DEPTH_TEST); - glEnable(GL_CULL_FACE); - glCullFace(GL_BACK); - - // render - _grid->geometry().drawUsingActiveProgram(); - - // disable shader - programObject->deactivate(); - } -} // namespace openspace diff --git a/modules/globebrowsing/chunk/chunkrenderer.h b/modules/globebrowsing/chunk/chunkrenderer.h deleted file mode 100644 index cd45c41d2d..0000000000 --- a/modules/globebrowsing/chunk/chunkrenderer.h +++ /dev/null @@ -1,105 +0,0 @@ -/***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ - -#ifndef __CHUNK_RENDERER_H__ -#define __CHUNK_RENDERER_H__ - -#include -#include - -// open space includes -#include - -#include -#include - -#include - -#include -#include - -#include - -#include - - -namespace ghoul { -namespace opengl { - class ProgramObject; -} -} - -namespace openspace { - - class ChunkRenderer { - public: - ChunkRenderer(std::shared_ptr grid, - std::shared_ptr tileProviderManager); - - void renderChunk(const Chunk& chunk, const RenderData& data); - void update(); - - private: - - void renderChunkGlobally(const Chunk& chunk, const RenderData& data); - void renderChunkLocally(const Chunk& chunk, const RenderData& data); - - void setDepthTransformUniforms( - std::shared_ptr uniformIdHandler, - LayeredTextures::TextureCategory textureCategory, - LayeredTextureShaderUniformIdHandler::BlendLayerSuffixes blendLayerSuffix, - size_t layerIndex, - const TileDepthTransform& tileDepthTransform); - - void activateTileAndSetTileUniforms( - std::shared_ptr uniformIdHandler, - LayeredTextures::TextureCategory textureCategory, - LayeredTextureShaderUniformIdHandler::BlendLayerSuffixes blendLayerSuffix, - size_t layerIndex, - ghoul::opengl::TextureUnit& texUnit, - const TileAndTransform& tileAndTransform); - - ProgramObject* getActivatedProgramWithTileData( - LayeredTextureShaderProvider* layeredTextureShaderProvider, - std::shared_ptr programUniformHandler, - const Chunk& chunk); - - ////////////////////////////////////////////////////////////////////////////////// - // Member variables // - ////////////////////////////////////////////////////////////////////////////////// - - std::shared_ptr _grid; - std::shared_ptr _tileProviderManager; - - std::shared_ptr _globalRenderingShaderProvider; - std::shared_ptr _localRenderingShaderProvider; - - std::shared_ptr _globalProgramUniformHandler; - std::shared_ptr _localProgramUniformHandler; - - }; - -} // namespace openspace - -#endif // __CHUNK_RENDERER_H__ \ No newline at end of file diff --git a/modules/globebrowsing/chunk/culling.cpp b/modules/globebrowsing/chunk/culling.cpp index c281f6d7cb..cac47f264b 100644 --- a/modules/globebrowsing/chunk/culling.cpp +++ b/modules/globebrowsing/chunk/culling.cpp @@ -1,141 +1,125 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ - - - - + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ #include -#include + #include - -#include -#include - -#include - -#include - -namespace { - const std::string _loggerCat = "FrustrumCuller"; -} +#include namespace openspace { +namespace globebrowsing { - ////////////////////////////////////////////////////////////////////////////////////// - // FRUSTUM CULLER // - ////////////////////////////////////////////////////////////////////////////////////// - FrustumCuller::FrustumCuller(const AABB3 viewFrustum) - : _viewFrustum(viewFrustum){ +FrustumCuller::FrustumCuller(const AABB3 viewFrustum) : _viewFrustum(viewFrustum) {} - } +bool FrustumCuller::isCullable(const Chunk& chunk, const RenderData& data) { + // Calculate the MVP matrix + glm::dmat4 modelTransform = chunk.owner().modelTransform(); + glm::dmat4 viewTransform = glm::dmat4(data.camera.combinedViewMatrix()); + glm::dmat4 modelViewProjectionTransform = glm::dmat4(data.camera.projectionMatrix()) + * viewTransform * modelTransform; - FrustumCuller::~FrustumCuller() { - - } - - bool FrustumCuller::isCullable(const Chunk& chunk, const RenderData& data) { - // Calculate the MVP matrix - dmat4 modelTransform = chunk.owner()->modelTransform(); - dmat4 viewTransform = dmat4(data.camera.combinedViewMatrix()); - dmat4 modelViewProjectionTransform = dmat4(data.camera.projectionMatrix()) - * viewTransform * modelTransform; - - const std::vector& corners = chunk.getBoundingPolyhedronCorners(); + const std::vector& corners = chunk.getBoundingPolyhedronCorners(); + // Create a bounding box that fits the patch corners + AABB3 bounds; // in screen space + std::vector clippingSpaceCorners(8); + for (size_t i = 0; i < 8; i++) { + glm::dvec4 cornerClippingSpace = modelViewProjectionTransform * corners[i]; + clippingSpaceCorners[i] = cornerClippingSpace; - // Create a bounding box that fits the patch corners - AABB3 bounds; // in screen space - std::vector clippingSpaceCorners(8); - for (size_t i = 0; i < 8; i++) { - dvec4 cornerClippingSpace = modelViewProjectionTransform * corners[i]; - clippingSpaceCorners[i] = cornerClippingSpace; + glm::dvec3 cornerNDC = + (1.0f / glm::abs(cornerClippingSpace.w)) * cornerClippingSpace; + bounds.expand(cornerNDC); + } + + return !_viewFrustum.intersects(bounds); +} - dvec3 cornerScreenSpace = (1.0f / glm::abs(cornerClippingSpace.w)) * cornerClippingSpace; - bounds.expand(cornerScreenSpace); +bool HorizonCuller::isCullable(const Chunk& chunk, const RenderData& data) { + // Calculations are done in the reference frame of the globe. Hence, the camera + // position needs to be transformed with the inverse model matrix + glm::dmat4 inverseModelTransform = chunk.owner().inverseModelTransform(); + + const Ellipsoid& ellipsoid = chunk.owner().ellipsoid(); + const GeodeticPatch& patch = chunk.surfacePatch(); + float maxHeight = chunk.getBoundingHeights().max; + glm::dvec3 globePosition = glm::dvec3(0,0,0); // In model space it is 0 + double minimumGlobeRadius = ellipsoid.minimumRadius(); + + glm::dvec3 cameraPosition = + glm::dvec3(inverseModelTransform * glm::dvec4(data.camera.positionVec3(), 1)); + + glm::dvec3 globeToCamera = cameraPosition; + + Geodetic2 cameraPositionOnGlobe = + ellipsoid.cartesianToGeodetic2(globeToCamera); + Geodetic2 closestPatchPoint = patch.closestPoint(cameraPositionOnGlobe); + glm::dvec3 objectPosition = ellipsoid.cartesianSurfacePosition(closestPatchPoint); + + // objectPosition is closest in latlon space but not guaranteed to be closest in + // castesian coordinates. Therefore we compare it to the corners and pick the + // real closest point, + glm::dvec3 corners[4]; + corners[0] = ellipsoid.cartesianSurfacePosition( + chunk.surfacePatch().getCorner(NORTH_WEST)); + corners[1] = ellipsoid.cartesianSurfacePosition( + chunk.surfacePatch().getCorner(NORTH_EAST)); + corners[2] = ellipsoid.cartesianSurfacePosition( + chunk.surfacePatch().getCorner(SOUTH_WEST)); + corners[3] = ellipsoid.cartesianSurfacePosition( + chunk.surfacePatch().getCorner(SOUTH_EAST)); + + for (int i = 0; i < 4; ++i) { + float distance = glm::length(cameraPosition - corners[i]); + if (distance < glm::length(cameraPosition - objectPosition)) { + objectPosition = corners[i]; } + } - return !_viewFrustum.intersects(bounds); - } + return isCullable(cameraPosition, globePosition, objectPosition, + maxHeight, minimumGlobeRadius); +} +bool HorizonCuller::isCullable(const glm::dvec3& cameraPosition, + const glm::dvec3& globePosition, + const glm::dvec3& objectPosition, + double objectBoundingSphereRadius, + double minimumGlobeRadius) +{ + double distanceToHorizon = + sqrt(pow(length(cameraPosition - globePosition), 2) - + pow(minimumGlobeRadius, 2)); + double minimumAllowedDistanceToObjectFromHorizon = sqrt( + pow(length(objectPosition - globePosition), 2) - + pow(minimumGlobeRadius - objectBoundingSphereRadius, 2)); + // Minimum allowed for the object to be occluded + double minimumAllowedDistanceToObjectSquared = + pow(distanceToHorizon + minimumAllowedDistanceToObjectFromHorizon, 2) + + pow(objectBoundingSphereRadius, 2); + double distanceToObjectSquared = pow(length(objectPosition - cameraPosition), 2); + return distanceToObjectSquared > minimumAllowedDistanceToObjectSquared; +} - ////////////////////////////////////////////////////////////////////////////////////// - // HORIZON CULLER // - ////////////////////////////////////////////////////////////////////////////////////// - HorizonCuller::HorizonCuller() { - - } - - HorizonCuller::~HorizonCuller() { - - } - - bool HorizonCuller::isCullable(const Chunk& chunk, const RenderData& data) { - //return !isVisible(data, chunk.surfacePatch(), chunk.owner()->ellipsoid(), chunk.owner()->chunkHeight); - - // Calculations are done in the reference frame of the globe. Hence, the camera - // position needs to be transformed with the inverse model matrix - glm::dmat4 inverseModelTransform = chunk.owner()->inverseModelTransform(); - - const Ellipsoid& ellipsoid = chunk.owner()->ellipsoid(); - const GeodeticPatch& patch = chunk.surfacePatch(); - float maxHeight = chunk.getBoundingHeights().max; - Vec3 globePosition = glm::dvec3(0,0,0); // In model space it is 0 - Scalar minimumGlobeRadius = ellipsoid.minimumRadius(); - - Vec3 cameraPosition = - glm::dvec3(inverseModelTransform * glm::dvec4(data.camera.positionVec3(), 1)); - - Vec3 globeToCamera = cameraPosition; - - Geodetic2 cameraPositionOnGlobe = - ellipsoid.cartesianToGeodetic2(globeToCamera); - Geodetic2 closestPatchPoint = patch.closestPoint(cameraPositionOnGlobe); - const Vec3& objectPosition = ellipsoid.cartesianSurfacePosition(closestPatchPoint); - - return isCullable(cameraPosition, globePosition, objectPosition, - maxHeight, minimumGlobeRadius); - } - - bool HorizonCuller::isCullable( - const Vec3& cameraPosition, - const Vec3& globePosition, - const Vec3& objectPosition, - Scalar objectBoundingSphereRadius, - Scalar minimumGlobeRadius) - { - Scalar distanceToHorizon = - sqrt(pow(length(cameraPosition - globePosition), 2) - pow(minimumGlobeRadius, 2)); - Scalar minimumAllowedDistanceToObjectFromHorizon = sqrt( - pow(length(objectPosition - globePosition), 2) - - pow(minimumGlobeRadius - objectBoundingSphereRadius, 2)); - // Minimum allowed for the object to be occluded - Scalar minimumAllowedDistanceToObjectSquared = - pow(distanceToHorizon + minimumAllowedDistanceToObjectFromHorizon, 2) - + pow(objectBoundingSphereRadius, 2); - Scalar distanceToObjectSquared = pow(length(objectPosition - cameraPosition), 2); - return distanceToObjectSquared > minimumAllowedDistanceToObjectSquared; - } - -} // namespace openspace +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/chunk/culling.h b/modules/globebrowsing/chunk/culling.h index 3ed58b422d..36105980ef 100644 --- a/modules/globebrowsing/chunk/culling.h +++ b/modules/globebrowsing/chunk/culling.h @@ -1,91 +1,88 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __CULLING_H__ -#define __CULLING_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___CULLING___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___CULLING___H__ -#include -#include - -// open space includes - -#include -#include -#include #include - - namespace openspace { - using namespace glm; +struct RenderData; +namespace globebrowsing { - class Chunk; +class Chunk; +class ChunkCuller { +public: + /** + * Determine if the Chunk is cullable. That is return true if removing the + * Chunk 'culling it' will not have any result on the final rendering. Culling + * it will make the rendering faster. + */ + virtual bool isCullable(const Chunk& chunk, const RenderData& renderData) = 0; +}; - class ChunkCuller { - public: - virtual void update() { } - virtual bool isCullable(const Chunk& chunk, const RenderData& renderData) = 0; - }; + /** + * Culls all chunks that are completely outside the view frustum. + * + * The frustum culling uses a 2D axis aligned bounding box for the Chunk in + * screen space. This is calculated from a bounding polyhedron bounding the + * Chunk. Hence the culling will not be 'perfect' but fast and good enough for + * culling chunks outside the frustum with some margin. + */ +class FrustumCuller : public ChunkCuller { +public: + /** + * \param viewFrustum is the view space in normalized device coordinates space. + * Hence it is an axis aligned bounding box and not a real frustum. + */ + FrustumCuller(const AABB3 viewFrustum); + bool isCullable(const Chunk& chunk, const RenderData& renderData) override; - class FrustumCuller : public ChunkCuller { - public: +private: + const AABB3 _viewFrustum; +}; - FrustumCuller(const AABB3 viewFrustum); - ~FrustumCuller(); +/** + * In this implementation of the horizon culling, the closer the ellipsoid is to a + * sphere, the better this will make the culling. Using the minimum radius to + * be safe. This means that if the ellipsoid has high difference between radii, + * splitting might accur even though it may not be needed. + */ +class HorizonCuller : public ChunkCuller { +public: + bool isCullable(const Chunk& chunk, const RenderData& renderData) override; - virtual bool isCullable(const Chunk& chunk, const RenderData& renderData); + bool isCullable(const glm::dvec3& cameraPosition, const glm::dvec3& globePosition, + const glm::dvec3& objectPosition, double objectBoundingSphereRadius, + double minimumGlobeRadius); +}; - private: - const AABB3 _viewFrustum; +} // namespace globebrowsing +} // namespace openspace - }; - - - //In the current implementation of the horizon culling and the distance to the - //camera, the closer the ellipsoid is to a - //sphere, the better this will make the splitting. Using the minimum radius to - //be safe. This means that if the ellipsoid has high difference between radii, - //splitting might accur even though it is not needed. - - class HorizonCuller : public ChunkCuller { - public: - HorizonCuller(); - ~HorizonCuller(); - - virtual bool isCullable(const Chunk& chunk, const RenderData& renderData); - - bool isCullable(const Vec3& cameraPosition, const Vec3& globePosition, - const Vec3& objectPosition, Scalar objectBoundingSphereRadius, - Scalar minimumGlobeRadius); - - }; - - -} // namespace openspace - -#endif // __CULLING_H__ \ No newline at end of file +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___CULLING___H__ diff --git a/modules/globebrowsing/gdal_log b/modules/globebrowsing/gdal_log deleted file mode 100644 index c8428e11dd..0000000000 --- a/modules/globebrowsing/gdal_log +++ /dev/null @@ -1,534 +0,0 @@ -GDAL: GDALOpen(map_service_configs/MODIS_Terra_CorrectedReflectance_TrueColor.xml, this=00000065C7511DA0) succeeds as WMS. -GDAL: GDALOpen(map_service_configs/ESRI_Imagery_World_2D.wms, this=00000065C75120C0) succeeds as WMS. -HTTP: Fetch(http://192.168.1.167/OnMars/wms.cgi?request=GetTileService) -GDAL: GDALOpen(map_service_configs/CTX_Mosaic.xml, this=00000065C7512A20) succeeds as WMS. -GDAL: GDALOpen(map_service_configs/VIIRS_CityLights_2012.xml, this=00000065C75123E0) succeeds as WMS. -HTTP: Fetch(http://198.102.45.23/arcgis/rest/services/worldelevation3d/terrain3d?request=GetTileService) -GDAL: GDALOpen(map_service_configs/TERRAIN.wms, this=00000065C7512700) succeeds as WMS. -HTTP: Fetch(http://192.168.1.167/OnMars/wms.cgi?request=GetTileService) -GDAL: GDALOpen(map_service_configs/Mola_Elevation.xml, this=00000065C7511120) succeeds as WMS. -GDAL: GDALOpen(map_service_configs/MODIS_Water_Mask.xml, this=00000065C7511440) succeeds as WMS. -GDAL: GDALOpen(map_service_configs/Coastlines.xml, this=00000065C7809EF0) succeeds as WMS. -GDAL: GDALOpen(map_service_configs/Reference_Features.xml, this=00000065C780AB70) succeeds as WMS. -GDAL: GDALOpen(map_service_configs/Reference_Labels.xml, this=00000065C78098B0) succeeds as WMS. -GDAL: GDAL_CACHEMAX = 2453 MB -HTTP: Requesting [1/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-090.00000000,-022.50000000,-067.50000000,0000.00000000 -HTTP: Requesting [2/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-067.50000000,-022.50000000,-045.00000000,0000.00000000 -HTTP: Requesting [3/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-045.00000000,-022.50000000,-022.50000000,0000.00000000 -HTTP: Requesting [4/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-022.50000000,-022.50000000,0000.00000000,0000.00000000 -HTTP: Requesting [5/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-090.00000000,-045.00000000,-067.50000000,-022.50000000 -HTTP: Requesting [6/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-067.50000000,-045.00000000,-045.00000000,-022.50000000 -HTTP: Requesting [7/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-045.00000000,-045.00000000,-022.50000000,-022.50000000 -HTTP: Requesting [8/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-022.50000000,-045.00000000,0000.00000000,-022.50000000 -HTTP: Requesting [9/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-090.00000000,-067.50000000,-067.50000000,-045.00000000 -HTTP: Requesting [10/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-067.50000000,-067.50000000,-045.00000000,-045.00000000 -HTTP: Requesting [11/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-045.00000000,-067.50000000,-022.50000000,-045.00000000 -HTTP: Requesting [12/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-022.50000000,-067.50000000,0000.00000000,-045.00000000 -HTTP: Requesting [13/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-090.00000000,-090.00000000,-067.50000000,-067.50000000 -HTTP: Requesting [14/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-067.50000000,-090.00000000,-045.00000000,-067.50000000 -HTTP: Requesting [15/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-045.00000000,-090.00000000,-022.50000000,-067.50000000 -HTTP: Requesting [16/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-022.50000000,-090.00000000,0000.00000000,-067.50000000 -HTTP: Request [0] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-090.00000000,-022.50000000,-067.50000000,0000.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [1] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-067.50000000,-022.50000000,-045.00000000,0000.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [2] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-045.00000000,-022.50000000,-022.50000000,0000.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [3] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-022.50000000,-022.50000000,0000.00000000,0000.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [4] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-090.00000000,-045.00000000,-067.50000000,-022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [5] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-067.50000000,-045.00000000,-045.00000000,-022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [6] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-045.00000000,-045.00000000,-022.50000000,-022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [7] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-022.50000000,-045.00000000,0000.00000000,-022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [8] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-090.00000000,-067.50000000,-067.50000000,-045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [9] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-067.50000000,-067.50000000,-045.00000000,-045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [10] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-045.00000000,-067.50000000,-022.50000000,-045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [11] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-022.50000000,-067.50000000,0000.00000000,-045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [12] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-090.00000000,-090.00000000,-067.50000000,-067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [13] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-067.50000000,-090.00000000,-045.00000000,-067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [14] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-045.00000000,-090.00000000,-022.50000000,-067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [15] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-022.50000000,-090.00000000,0000.00000000,-067.50000000 : status = 200, content type = image/png, error = (null) -GDAL: GDALOpen(/vsimem/wms/00000065C7B41DA0/wmsresult.dat, this=00000065C53E5840) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7B41DA0/wmsresult.dat, this=00000065C53E5840) -GDAL: GDALOpen(/vsimem/wms/00000065C7B5FEA0/wmsresult.dat, this=00000065C53E52C0) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7B5FEA0/wmsresult.dat, this=00000065C53E52C0) -GDAL: GDALOpen(/vsimem/wms/00000065C7B89D50/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7B89D50/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065C7BA95E0/wmsresult.dat, this=00000065C53E4500) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7BA95E0/wmsresult.dat, this=00000065C53E4500) -GDAL: GDALOpen(/vsimem/wms/00000065C7B7AEF0/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7B7AEF0/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065C7BBBD50/wmsresult.dat, this=00000065C53E52C0) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7BBBD50/wmsresult.dat, this=00000065C53E52C0) -GDAL: GDALOpen(/vsimem/wms/00000065C7BDC6A0/wmsresult.dat, this=00000065C53E4500) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7BDC6A0/wmsresult.dat, this=00000065C53E4500) -GDAL: GDALOpen(/vsimem/wms/00000065C7BF3280/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7BF3280/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065C7BCB720/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7BCB720/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065C7C25A00/wmsresult.dat, this=00000065C53E52C0) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7C25A00/wmsresult.dat, this=00000065C53E52C0) -GDAL: GDALOpen(/vsimem/wms/00000065C7C32630/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7C32630/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065C7C40930/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7C40930/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065C7C6EC40/wmsresult.dat, this=00000065C53E5840) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7C6EC40/wmsresult.dat, this=00000065C53E5840) -GDAL: GDALOpen(/vsimem/wms/00000065C7C7CF40/wmsresult.dat, this=00000065C53E5000) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7C7CF40/wmsresult.dat, this=00000065C53E5000) -GDAL: GDALOpen(/vsimem/wms/00000065C7C8B240/wmsresult.dat, this=00000065C53E5840) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7C8B240/wmsresult.dat, this=00000065C53E5840) -GDAL: GDALOpen(/vsimem/wms/00000065C7C9A0A0/wmsresult.dat, this=00000065C53E5000) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7C9A0A0/wmsresult.dat, this=00000065C53E5000) -HTTP: Requesting [1/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-180.00000000,-022.50000000,-157.50000000,0000.00000000 -HTTP: Requesting [2/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-157.50000000,-022.50000000,-135.00000000,0000.00000000 -HTTP: Requesting [3/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-135.00000000,-022.50000000,-112.50000000,0000.00000000 -HTTP: Requesting [4/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-112.50000000,-022.50000000,-090.00000000,0000.00000000 -HTTP: Requesting [5/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-180.00000000,-045.00000000,-157.50000000,-022.50000000 -HTTP: Requesting [6/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-157.50000000,-045.00000000,-135.00000000,-022.50000000 -HTTP: Requesting [7/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-135.00000000,-045.00000000,-112.50000000,-022.50000000 -HTTP: Requesting [8/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-112.50000000,-045.00000000,-090.00000000,-022.50000000 -HTTP: Requesting [9/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-180.00000000,-067.50000000,-157.50000000,-045.00000000 -HTTP: Requesting [10/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-157.50000000,-067.50000000,-135.00000000,-045.00000000 -HTTP: Requesting [11/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-135.00000000,-067.50000000,-112.50000000,-045.00000000 -HTTP: Requesting [12/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-112.50000000,-067.50000000,-090.00000000,-045.00000000 -HTTP: Requesting [13/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-180.00000000,-090.00000000,-157.50000000,-067.50000000 -HTTP: Requesting [14/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-157.50000000,-090.00000000,-135.00000000,-067.50000000 -HTTP: Requesting [15/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-135.00000000,-090.00000000,-112.50000000,-067.50000000 -HTTP: Requesting [16/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-112.50000000,-090.00000000,-090.00000000,-067.50000000 -HTTP: Request [0] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-180.00000000,-022.50000000,-157.50000000,0000.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [1] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-157.50000000,-022.50000000,-135.00000000,0000.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [2] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-135.00000000,-022.50000000,-112.50000000,0000.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [3] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-112.50000000,-022.50000000,-090.00000000,0000.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [4] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-180.00000000,-045.00000000,-157.50000000,-022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [5] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-157.50000000,-045.00000000,-135.00000000,-022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [6] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-135.00000000,-045.00000000,-112.50000000,-022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [7] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-112.50000000,-045.00000000,-090.00000000,-022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [8] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-180.00000000,-067.50000000,-157.50000000,-045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [9] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-157.50000000,-067.50000000,-135.00000000,-045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [10] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-135.00000000,-067.50000000,-112.50000000,-045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [11] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-112.50000000,-067.50000000,-090.00000000,-045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [12] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-180.00000000,-090.00000000,-157.50000000,-067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [13] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-157.50000000,-090.00000000,-135.00000000,-067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [14] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-135.00000000,-090.00000000,-112.50000000,-067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [15] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-112.50000000,-090.00000000,-090.00000000,-067.50000000 : status = 200, content type = image/png, error = (null) -GDAL: GDALOpen(/vsimem/wms/00000065C7DD7AA0/wmsresult.dat, this=00000065C53E5840) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7DD7AA0/wmsresult.dat, this=00000065C53E5840) -GDAL: GDALOpen(/vsimem/wms/00000065C7DF0790/wmsresult.dat, this=00000065C53E5B00) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7DF0790/wmsresult.dat, this=00000065C53E5B00) -GDAL: GDALOpen(/vsimem/wms/00000065C7E33A80/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7E33A80/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065C7E43450/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7E43450/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065C7E68D70/wmsresult.dat, this=00000065C53E4500) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7E68D70/wmsresult.dat, this=00000065C53E4500) -GDAL: GDALOpen(/vsimem/wms/00000065C7E87760/wmsresult.dat, this=00000065C53E5840) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7E87760/wmsresult.dat, this=00000065C53E5840) -GDAL: GDALOpen(/vsimem/wms/00000065C7E544F0/wmsresult.dat, this=00000065C53E5000) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7E544F0/wmsresult.dat, this=00000065C53E5000) -GDAL: GDALOpen(/vsimem/wms/00000065C7E9E340/wmsresult.dat, this=00000065C53E4500) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7E9E340/wmsresult.dat, this=00000065C53E4500) -GDAL: GDALOpen(/vsimem/wms/00000065C7EAE380/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7EAE380/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065C7EBD1E0/wmsresult.dat, this=00000065C53E4D40) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7EBD1E0/wmsresult.dat, this=00000065C53E4D40) -GDAL: GDALOpen(/vsimem/wms/00000065C7EC8740/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7EC8740/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065C7ED75A0/wmsresult.dat, this=00000065C53E4500) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7ED75A0/wmsresult.dat, this=00000065C53E4500) -GDAL: GDALOpen(/vsimem/wms/00000065C7EE6400/wmsresult.dat, this=00000065C53E4D40) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7EE6400/wmsresult.dat, this=00000065C53E4D40) -GDAL: GDALOpen(/vsimem/wms/00000065C7EF5260/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7EF5260/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065C7F040C0/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7F040C0/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065C7F123C0/wmsresult.dat, this=00000065C53E4D40) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7F123C0/wmsresult.dat, this=00000065C53E4D40) -HTTP: Requesting [1/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-090.00000000,0067.50000000,-067.50000000,0090.00000000 -HTTP: Requesting [2/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-067.50000000,0067.50000000,-045.00000000,0090.00000000 -HTTP: Requesting [3/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-045.00000000,0067.50000000,-022.50000000,0090.00000000 -HTTP: Requesting [4/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-022.50000000,0067.50000000,0000.00000000,0090.00000000 -HTTP: Requesting [5/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-090.00000000,0045.00000000,-067.50000000,0067.50000000 -HTTP: Requesting [6/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-067.50000000,0045.00000000,-045.00000000,0067.50000000 -HTTP: Requesting [7/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-045.00000000,0045.00000000,-022.50000000,0067.50000000 -HTTP: Requesting [8/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-022.50000000,0045.00000000,0000.00000000,0067.50000000 -HTTP: Requesting [9/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-090.00000000,0022.50000000,-067.50000000,0045.00000000 -HTTP: Requesting [10/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-067.50000000,0022.50000000,-045.00000000,0045.00000000 -HTTP: Requesting [11/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-045.00000000,0022.50000000,-022.50000000,0045.00000000 -HTTP: Requesting [12/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-022.50000000,0022.50000000,0000.00000000,0045.00000000 -HTTP: Requesting [13/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-090.00000000,0000.00000000,-067.50000000,0022.50000000 -HTTP: Requesting [14/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-067.50000000,0000.00000000,-045.00000000,0022.50000000 -HTTP: Requesting [15/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-045.00000000,0000.00000000,-022.50000000,0022.50000000 -HTTP: Requesting [16/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-022.50000000,0000.00000000,0000.00000000,0022.50000000 -HTTP: Request [0] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-090.00000000,0067.50000000,-067.50000000,0090.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [1] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-067.50000000,0067.50000000,-045.00000000,0090.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [2] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-045.00000000,0067.50000000,-022.50000000,0090.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [3] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-022.50000000,0067.50000000,0000.00000000,0090.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [4] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-090.00000000,0045.00000000,-067.50000000,0067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [5] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-067.50000000,0045.00000000,-045.00000000,0067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [6] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-045.00000000,0045.00000000,-022.50000000,0067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [7] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-022.50000000,0045.00000000,0000.00000000,0067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [8] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-090.00000000,0022.50000000,-067.50000000,0045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [9] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-067.50000000,0022.50000000,-045.00000000,0045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [10] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-045.00000000,0022.50000000,-022.50000000,0045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [11] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-022.50000000,0022.50000000,0000.00000000,0045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [12] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-090.00000000,0000.00000000,-067.50000000,0022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [13] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-067.50000000,0000.00000000,-045.00000000,0022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [14] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-045.00000000,0000.00000000,-022.50000000,0022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [15] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-022.50000000,0000.00000000,0000.00000000,0022.50000000 : status = 200, content type = image/png, error = (null) -GDAL: GDALOpen(/vsimem/wms/00000065C7E13A70/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7E13A70/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065C7C043A0/wmsresult.dat, this=00000065C53E5840) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7C043A0/wmsresult.dat, this=00000065C53E5840) -GDAL: GDALOpen(/vsimem/wms/00000065C7C15440/wmsresult.dat, this=00000065C53E5B00) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7C15440/wmsresult.dat, this=00000065C53E5B00) -GDAL: GDALOpen(/vsimem/wms/00000065C7E23440/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7E23440/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065C805A4E0/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C805A4E0/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065C8069340/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C8069340/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065C8077640/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C8077640/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065C808F7D0/wmsresult.dat, this=00000065C53E4500) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C808F7D0/wmsresult.dat, this=00000065C53E4500) -GDAL: GDALOpen(/vsimem/wms/00000065C80B0240/wmsresult.dat, this=00000065C53E4500) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C80B0240/wmsresult.dat, this=00000065C53E4500) -GDAL: GDALOpen(/vsimem/wms/00000065C80D5C80/wmsresult.dat, this=00000065C53E5000) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C80D5C80/wmsresult.dat, this=00000065C53E5000) -GDAL: GDALOpen(/vsimem/wms/00000065C80C6E20/wmsresult.dat, this=00000065C53E52C0) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C80C6E20/wmsresult.dat, this=00000065C53E52C0) -GDAL: GDALOpen(/vsimem/wms/00000065C80F45D0/wmsresult.dat, this=00000065C53E4500) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C80F45D0/wmsresult.dat, this=00000065C53E4500) -GDAL: GDALOpen(/vsimem/wms/00000065C81028D0/wmsresult.dat, this=00000065C53E5B00) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C81028D0/wmsresult.dat, this=00000065C53E5B00) -GDAL: GDALOpen(/vsimem/wms/00000065C811BF10/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C811BF10/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065C8140280/wmsresult.dat, this=00000065C53E4500) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C8140280/wmsresult.dat, this=00000065C53E4500) -GDAL: GDALOpen(/vsimem/wms/00000065C816ACA0/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C816ACA0/wmsresult.dat, this=00000065C53E4A80) -HTTP: Requesting [1/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-180.00000000,0067.50000000,-157.50000000,0090.00000000 -HTTP: Requesting [2/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-157.50000000,0067.50000000,-135.00000000,0090.00000000 -HTTP: Requesting [3/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-135.00000000,0067.50000000,-112.50000000,0090.00000000 -HTTP: Requesting [4/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-112.50000000,0067.50000000,-090.00000000,0090.00000000 -HTTP: Requesting [5/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-180.00000000,0045.00000000,-157.50000000,0067.50000000 -HTTP: Requesting [6/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-157.50000000,0045.00000000,-135.00000000,0067.50000000 -HTTP: Requesting [7/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-135.00000000,0045.00000000,-112.50000000,0067.50000000 -HTTP: Requesting [8/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-112.50000000,0045.00000000,-090.00000000,0067.50000000 -HTTP: Requesting [9/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-180.00000000,0022.50000000,-157.50000000,0045.00000000 -HTTP: Requesting [10/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-157.50000000,0022.50000000,-135.00000000,0045.00000000 -HTTP: Requesting [11/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-135.00000000,0022.50000000,-112.50000000,0045.00000000 -HTTP: Requesting [12/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-112.50000000,0022.50000000,-090.00000000,0045.00000000 -HTTP: Requesting [13/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-180.00000000,0000.00000000,-157.50000000,0022.50000000 -HTTP: Requesting [14/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-157.50000000,0000.00000000,-135.00000000,0022.50000000 -HTTP: Requesting [15/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-135.00000000,0000.00000000,-112.50000000,0022.50000000 -HTTP: Requesting [16/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-112.50000000,0000.00000000,-090.00000000,0022.50000000 -HTTP: Request [0] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-180.00000000,0067.50000000,-157.50000000,0090.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [1] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-157.50000000,0067.50000000,-135.00000000,0090.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [2] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-135.00000000,0067.50000000,-112.50000000,0090.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [3] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-112.50000000,0067.50000000,-090.00000000,0090.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [4] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-180.00000000,0045.00000000,-157.50000000,0067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [5] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-157.50000000,0045.00000000,-135.00000000,0067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [6] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-135.00000000,0045.00000000,-112.50000000,0067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [7] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-112.50000000,0045.00000000,-090.00000000,0067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [8] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-180.00000000,0022.50000000,-157.50000000,0045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [9] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-157.50000000,0022.50000000,-135.00000000,0045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [10] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-135.00000000,0022.50000000,-112.50000000,0045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [11] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-112.50000000,0022.50000000,-090.00000000,0045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [12] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-180.00000000,0000.00000000,-157.50000000,0022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [13] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-157.50000000,0000.00000000,-135.00000000,0022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [14] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-135.00000000,0000.00000000,-112.50000000,0022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [15] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=-112.50000000,0000.00000000,-090.00000000,0022.50000000 : status = 200, content type = image/png, error = (null) -GDAL: GDALOpen(/vsimem/wms/00000065C80437F0/wmsresult.dat, this=00000065C53E5840) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C80437F0/wmsresult.dat, this=00000065C53E5840) -GDAL: GDALOpen(/vsimem/wms/00000065C803A4D0/wmsresult.dat, this=00000065C53E4D40) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C803A4D0/wmsresult.dat, this=00000065C53E4D40) -GDAL: GDALOpen(/vsimem/wms/00000065C7C4DA30/wmsresult.dat, this=00000065C53E5000) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7C4DA30/wmsresult.dat, this=00000065C53E5000) -GDAL: GDALOpen(/vsimem/wms/00000065C9F829D0/wmsresult.dat, this=00000065C53E5B00) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C9F829D0/wmsresult.dat, this=00000065C53E5B00) -GDAL: GDALOpen(/vsimem/wms/00000065C7C5D400/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C7C5D400/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065C9FB5880/wmsresult.dat, this=00000065C53E5840) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C9FB5880/wmsresult.dat, this=00000065C53E5840) -GDAL: GDALOpen(/vsimem/wms/00000065C9FCCEA0/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C9FCCEA0/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065C9FDC870/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C9FDC870/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065C9FFDE40/wmsresult.dat, this=00000065C53E4500) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C9FFDE40/wmsresult.dat, this=00000065C53E4500) -GDAL: GDALOpen(/vsimem/wms/00000065CA01C310/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA01C310/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065CA03A310/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA03A310/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065CA04F820/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA04F820/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065CA0691A0/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA0691A0/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065CA07E6B0/wmsresult.dat, this=00000065C53E5B00) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA07E6B0/wmsresult.dat, this=00000065C53E5B00) -GDAL: GDALOpen(/vsimem/wms/00000065CA0C05E0/wmsresult.dat, this=00000065C53E5840) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA0C05E0/wmsresult.dat, this=00000065C53E5840) -GDAL: GDALOpen(/vsimem/wms/00000065CA0DCD00/wmsresult.dat, this=00000065C53E4D40) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA0DCD00/wmsresult.dat, this=00000065C53E4D40) -HTTP: Requesting [1/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0090.00000000,-022.50000000,0112.50000000,0000.00000000 -HTTP: Requesting [2/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0112.50000000,-022.50000000,0135.00000000,0000.00000000 -HTTP: Requesting [3/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0135.00000000,-022.50000000,0157.50000000,0000.00000000 -HTTP: Requesting [4/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0157.50000000,-022.50000000,0180.00000000,0000.00000000 -HTTP: Requesting [5/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0090.00000000,-045.00000000,0112.50000000,-022.50000000 -HTTP: Requesting [6/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0112.50000000,-045.00000000,0135.00000000,-022.50000000 -HTTP: Requesting [7/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0135.00000000,-045.00000000,0157.50000000,-022.50000000 -HTTP: Requesting [8/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0157.50000000,-045.00000000,0180.00000000,-022.50000000 -HTTP: Requesting [9/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0090.00000000,-067.50000000,0112.50000000,-045.00000000 -HTTP: Requesting [10/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0112.50000000,-067.50000000,0135.00000000,-045.00000000 -HTTP: Requesting [11/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0135.00000000,-067.50000000,0157.50000000,-045.00000000 -HTTP: Requesting [12/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0157.50000000,-067.50000000,0180.00000000,-045.00000000 -HTTP: Requesting [13/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0090.00000000,-090.00000000,0112.50000000,-067.50000000 -HTTP: Requesting [14/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0112.50000000,-090.00000000,0135.00000000,-067.50000000 -HTTP: Requesting [15/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0135.00000000,-090.00000000,0157.50000000,-067.50000000 -HTTP: Requesting [16/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0157.50000000,-090.00000000,0180.00000000,-067.50000000 -HTTP: Request [0] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0090.00000000,-022.50000000,0112.50000000,0000.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [1] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0112.50000000,-022.50000000,0135.00000000,0000.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [2] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0135.00000000,-022.50000000,0157.50000000,0000.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [3] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0157.50000000,-022.50000000,0180.00000000,0000.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [4] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0090.00000000,-045.00000000,0112.50000000,-022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [5] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0112.50000000,-045.00000000,0135.00000000,-022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [6] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0135.00000000,-045.00000000,0157.50000000,-022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [7] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0157.50000000,-045.00000000,0180.00000000,-022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [8] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0090.00000000,-067.50000000,0112.50000000,-045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [9] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0112.50000000,-067.50000000,0135.00000000,-045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [10] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0135.00000000,-067.50000000,0157.50000000,-045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [11] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0157.50000000,-067.50000000,0180.00000000,-045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [12] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0090.00000000,-090.00000000,0112.50000000,-067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [13] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0112.50000000,-090.00000000,0135.00000000,-067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [14] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0135.00000000,-090.00000000,0157.50000000,-067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [15] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0157.50000000,-090.00000000,0180.00000000,-067.50000000 : status = 200, content type = image/png, error = (null) -GDAL: GDALOpen(/vsimem/wms/00000065C8019A80/wmsresult.dat, this=00000065C53E5000) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C8019A80/wmsresult.dat, this=00000065C53E5000) -GDAL: GDALOpen(/vsimem/wms/00000065C9F929E0/wmsresult.dat, this=00000065C53E5B00) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C9F929E0/wmsresult.dat, this=00000065C53E5B00) -GDAL: GDALOpen(/vsimem/wms/00000065C8029450/wmsresult.dat, this=00000065C53E52C0) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C8029450/wmsresult.dat, this=00000065C53E52C0) -GDAL: GDALOpen(/vsimem/wms/00000065C9FA3A80/wmsresult.dat, this=00000065C53E5B00) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C9FA3A80/wmsresult.dat, this=00000065C53E5B00) -GDAL: GDALOpen(/vsimem/wms/00000065CA20DC10/wmsresult.dat, this=00000065C53E52C0) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA20DC10/wmsresult.dat, this=00000065C53E52C0) -GDAL: GDALOpen(/vsimem/wms/00000065CA1FCB70/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA1FCB70/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065CA1E49E0/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA1E49E0/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065CA23B600/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA23B600/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065CA24F440/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA24F440/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065CA22D420/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA22D420/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065CA25D740/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA25D740/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065CA271460/wmsresult.dat, this=00000065C53E52C0) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA271460/wmsresult.dat, this=00000065C53E52C0) -GDAL: GDALOpen(/vsimem/wms/00000065CA286130/wmsresult.dat, this=00000065C53E5000) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA286130/wmsresult.dat, this=00000065C53E5000) -GDAL: GDALOpen(/vsimem/wms/00000065CA294430/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA294430/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065CA2A2730/wmsresult.dat, this=00000065C53E4D40) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA2A2730/wmsresult.dat, this=00000065C53E4D40) -GDAL: GDALOpen(/vsimem/wms/00000065CA2B1590/wmsresult.dat, this=00000065C53E4D40) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA2B1590/wmsresult.dat, this=00000065C53E4D40) -HTTP: Requesting [1/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0000.00000000,-022.50000000,0022.50000000,0000.00000000 -HTTP: Requesting [2/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0022.50000000,-022.50000000,0045.00000000,0000.00000000 -HTTP: Requesting [3/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0045.00000000,-022.50000000,0067.50000000,0000.00000000 -HTTP: Requesting [4/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0067.50000000,-022.50000000,0090.00000000,0000.00000000 -HTTP: Requesting [5/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0000.00000000,-045.00000000,0022.50000000,-022.50000000 -HTTP: Requesting [6/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0022.50000000,-045.00000000,0045.00000000,-022.50000000 -HTTP: Requesting [7/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0045.00000000,-045.00000000,0067.50000000,-022.50000000 -HTTP: Requesting [8/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0067.50000000,-045.00000000,0090.00000000,-022.50000000 -HTTP: Requesting [9/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0000.00000000,-067.50000000,0022.50000000,-045.00000000 -HTTP: Requesting [10/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0022.50000000,-067.50000000,0045.00000000,-045.00000000 -HTTP: Requesting [11/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0045.00000000,-067.50000000,0067.50000000,-045.00000000 -HTTP: Requesting [12/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0067.50000000,-067.50000000,0090.00000000,-045.00000000 -HTTP: Requesting [13/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0000.00000000,-090.00000000,0022.50000000,-067.50000000 -HTTP: Requesting [14/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0022.50000000,-090.00000000,0045.00000000,-067.50000000 -HTTP: Requesting [15/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0045.00000000,-090.00000000,0067.50000000,-067.50000000 -HTTP: Requesting [16/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0067.50000000,-090.00000000,0090.00000000,-067.50000000 -HTTP: Request [0] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0000.00000000,-022.50000000,0022.50000000,0000.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [1] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0022.50000000,-022.50000000,0045.00000000,0000.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [2] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0045.00000000,-022.50000000,0067.50000000,0000.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [3] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0067.50000000,-022.50000000,0090.00000000,0000.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [4] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0000.00000000,-045.00000000,0022.50000000,-022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [5] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0022.50000000,-045.00000000,0045.00000000,-022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [6] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0045.00000000,-045.00000000,0067.50000000,-022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [7] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0067.50000000,-045.00000000,0090.00000000,-022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [8] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0000.00000000,-067.50000000,0022.50000000,-045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [9] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0022.50000000,-067.50000000,0045.00000000,-045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [10] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0045.00000000,-067.50000000,0067.50000000,-045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [11] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0067.50000000,-067.50000000,0090.00000000,-045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [12] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0000.00000000,-090.00000000,0022.50000000,-067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [13] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0022.50000000,-090.00000000,0045.00000000,-067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [14] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0045.00000000,-090.00000000,0067.50000000,-067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [15] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0067.50000000,-090.00000000,0090.00000000,-067.50000000 : status = 200, content type = image/png, error = (null) -GDAL: GDALOpen(/vsimem/wms/00000065CA3CC320/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA3CC320/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065CA3E0160/wmsresult.dat, this=00000065C53E5000) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA3E0160/wmsresult.dat, this=00000065C53E5000) -GDAL: GDALOpen(/vsimem/wms/00000065CA3B4E20/wmsresult.dat, this=00000065C53E4D40) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA3B4E20/wmsresult.dat, this=00000065C53E4D40) -GDAL: GDALOpen(/vsimem/wms/00000065CA1C3540/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA1C3540/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065CA418E60/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA418E60/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065CA428830/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA428830/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065CA45A340/wmsresult.dat, this=00000065C53E4500) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA45A340/wmsresult.dat, this=00000065C53E4500) -GDAL: GDALOpen(/vsimem/wms/00000065CA4492A0/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA4492A0/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065CA4398D0/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA4398D0/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065CA47A360/wmsresult.dat, this=00000065C53E52C0) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA47A360/wmsresult.dat, this=00000065C53E52C0) -GDAL: GDALOpen(/vsimem/wms/00000065CA48BF60/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA48BF60/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065CA49B930/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA49B930/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065CA4AFFD0/wmsresult.dat, this=00000065C53E52C0) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA4AFFD0/wmsresult.dat, this=00000065C53E52C0) -GDAL: GDALOpen(/vsimem/wms/00000065CA1D7380/wmsresult.dat, this=00000065C53E52C0) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA1D7380/wmsresult.dat, this=00000065C53E52C0) -GDAL: GDALOpen(/vsimem/wms/00000065CA4BEE30/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA4BEE30/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065CA4CD130/wmsresult.dat, this=00000065C53E4500) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA4CD130/wmsresult.dat, this=00000065C53E4500) -HTTP: Requesting [1/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0090.00000000,0067.50000000,0112.50000000,0090.00000000 -HTTP: Requesting [2/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0112.50000000,0067.50000000,0135.00000000,0090.00000000 -HTTP: Requesting [3/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0135.00000000,0067.50000000,0157.50000000,0090.00000000 -HTTP: Requesting [4/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0157.50000000,0067.50000000,0180.00000000,0090.00000000 -HTTP: Requesting [5/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0090.00000000,0045.00000000,0112.50000000,0067.50000000 -HTTP: Requesting [6/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0112.50000000,0045.00000000,0135.00000000,0067.50000000 -HTTP: Requesting [7/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0135.00000000,0045.00000000,0157.50000000,0067.50000000 -HTTP: Requesting [8/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0157.50000000,0045.00000000,0180.00000000,0067.50000000 -HTTP: Requesting [9/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0090.00000000,0022.50000000,0112.50000000,0045.00000000 -HTTP: Requesting [10/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0112.50000000,0022.50000000,0135.00000000,0045.00000000 -HTTP: Requesting [11/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0135.00000000,0022.50000000,0157.50000000,0045.00000000 -HTTP: Requesting [12/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0157.50000000,0022.50000000,0180.00000000,0045.00000000 -HTTP: Requesting [13/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0090.00000000,0000.00000000,0112.50000000,0022.50000000 -HTTP: Requesting [14/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0112.50000000,0000.00000000,0135.00000000,0022.50000000 -HTTP: Requesting [15/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0135.00000000,0000.00000000,0157.50000000,0022.50000000 -HTTP: Requesting [16/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0157.50000000,0000.00000000,0180.00000000,0022.50000000 -HTTP: Request [0] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0090.00000000,0067.50000000,0112.50000000,0090.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [1] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0112.50000000,0067.50000000,0135.00000000,0090.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [2] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0135.00000000,0067.50000000,0157.50000000,0090.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [3] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0157.50000000,0067.50000000,0180.00000000,0090.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [4] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0090.00000000,0045.00000000,0112.50000000,0067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [5] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0112.50000000,0045.00000000,0135.00000000,0067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [6] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0135.00000000,0045.00000000,0157.50000000,0067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [7] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0157.50000000,0045.00000000,0180.00000000,0067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [8] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0090.00000000,0022.50000000,0112.50000000,0045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [9] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0112.50000000,0022.50000000,0135.00000000,0045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [10] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0135.00000000,0022.50000000,0157.50000000,0045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [11] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0157.50000000,0022.50000000,0180.00000000,0045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [12] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0090.00000000,0000.00000000,0112.50000000,0022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [13] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0112.50000000,0000.00000000,0135.00000000,0022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [14] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0135.00000000,0000.00000000,0157.50000000,0022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [15] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0157.50000000,0000.00000000,0180.00000000,0022.50000000 : status = 200, content type = image/png, error = (null) -GDAL: GDALOpen(/vsimem/wms/00000065CA09CC30/wmsresult.dat, this=00000065C53E5B00) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA09CC30/wmsresult.dat, this=00000065C53E5B00) -GDAL: GDALOpen(/vsimem/wms/00000065CA3F4820/wmsresult.dat, this=00000065C53E5000) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA3F4820/wmsresult.dat, this=00000065C53E5000) -GDAL: GDALOpen(/vsimem/wms/00000065CA0B0300/wmsresult.dat, this=00000065C53E5840) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA0B0300/wmsresult.dat, this=00000065C53E5840) -GDAL: GDALOpen(/vsimem/wms/00000065CA4041F0/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA4041F0/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065CA5E5530/wmsresult.dat, this=00000065C53E5B00) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA5E5530/wmsresult.dat, this=00000065C53E5B00) -GDAL: GDALOpen(/vsimem/wms/00000065CA5F4F00/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA5F4F00/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065CA5FED90/wmsresult.dat, this=00000065C53E5840) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA5FED90/wmsresult.dat, this=00000065C53E5840) -GDAL: GDALOpen(/vsimem/wms/00000065CA617A80/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA617A80/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065CA62AD50/wmsresult.dat, this=00000065C53E4D40) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA62AD50/wmsresult.dat, this=00000065C53E4D40) -GDAL: GDALOpen(/vsimem/wms/00000065CA63A720/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA63A720/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065CA653F80/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA653F80/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065CA66E340/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA66E340/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065CA6B3230/wmsresult.dat, this=00000065C53E5840) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA6B3230/wmsresult.dat, this=00000065C53E5840) -GDAL: GDALOpen(/vsimem/wms/00000065CA6A4F30/wmsresult.dat, this=00000065C53E4D40) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA6A4F30/wmsresult.dat, this=00000065C53E4D40) -GDAL: GDALOpen(/vsimem/wms/00000065CA6CFC40/wmsresult.dat, this=00000065C53E4500) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA6CFC40/wmsresult.dat, this=00000065C53E4500) -GDAL: GDALOpen(/vsimem/wms/00000065CA6DEAA0/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA6DEAA0/wmsresult.dat, this=00000065C53E4A80) -HTTP: Requesting [1/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0000.00000000,0067.50000000,0022.50000000,0090.00000000 -HTTP: Requesting [2/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0022.50000000,0067.50000000,0045.00000000,0090.00000000 -HTTP: Requesting [3/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0045.00000000,0067.50000000,0067.50000000,0090.00000000 -HTTP: Requesting [4/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0067.50000000,0067.50000000,0090.00000000,0090.00000000 -HTTP: Requesting [5/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0000.00000000,0045.00000000,0022.50000000,0067.50000000 -HTTP: Requesting [6/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0022.50000000,0045.00000000,0045.00000000,0067.50000000 -HTTP: Requesting [7/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0045.00000000,0045.00000000,0067.50000000,0067.50000000 -HTTP: Requesting [8/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0067.50000000,0045.00000000,0090.00000000,0067.50000000 -HTTP: Requesting [9/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0000.00000000,0022.50000000,0022.50000000,0045.00000000 -HTTP: Requesting [10/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0022.50000000,0022.50000000,0045.00000000,0045.00000000 -HTTP: Requesting [11/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0045.00000000,0022.50000000,0067.50000000,0045.00000000 -HTTP: Requesting [12/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0067.50000000,0022.50000000,0090.00000000,0045.00000000 -HTTP: Requesting [13/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0000.00000000,0000.00000000,0022.50000000,0022.50000000 -HTTP: Requesting [14/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0022.50000000,0000.00000000,0045.00000000,0022.50000000 -HTTP: Requesting [15/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0045.00000000,0000.00000000,0067.50000000,0022.50000000 -HTTP: Requesting [16/16] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0067.50000000,0000.00000000,0090.00000000,0022.50000000 -HTTP: Request [0] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0000.00000000,0067.50000000,0022.50000000,0090.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [1] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0022.50000000,0067.50000000,0045.00000000,0090.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [2] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0045.00000000,0067.50000000,0067.50000000,0090.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [3] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0067.50000000,0067.50000000,0090.00000000,0090.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [4] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0000.00000000,0045.00000000,0022.50000000,0067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [5] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0022.50000000,0045.00000000,0045.00000000,0067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [6] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0045.00000000,0045.00000000,0067.50000000,0067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [7] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0067.50000000,0045.00000000,0090.00000000,0067.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [8] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0000.00000000,0022.50000000,0022.50000000,0045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [9] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0022.50000000,0022.50000000,0045.00000000,0045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [10] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0045.00000000,0022.50000000,0067.50000000,0045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [11] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0067.50000000,0022.50000000,0090.00000000,0045.00000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [12] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0000.00000000,0000.00000000,0022.50000000,0022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [13] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0022.50000000,0000.00000000,0045.00000000,0022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [14] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0045.00000000,0000.00000000,0067.50000000,0022.50000000 : status = 200, content type = image/png, error = (null) -HTTP: Request [15] http://192.168.1.167/OnMars/wms.cgi?request=GetMap&layers=CTX&srs=IAU2000:49900&format=image/png&styles=&width=256&height=256&bbox=0067.50000000,0000.00000000,0090.00000000,0022.50000000 : status = 200, content type = image/png, error = (null) -GDAL: GDALOpen(/vsimem/wms/00000065CA7F97F0/wmsresult.dat, this=00000065C53E52C0) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA7F97F0/wmsresult.dat, this=00000065C53E52C0) -GDAL: GDALOpen(/vsimem/wms/00000065CA7E9E20/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA7E9E20/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065CA80BF60/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA80BF60/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065CA81ADC0/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA81ADC0/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065CA829C20/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA829C20/wmsresult.dat, this=00000065C53E4A80) -GDAL: GDALOpen(/vsimem/wms/00000065CA843FE0/wmsresult.dat, this=00000065C53E4D40) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA843FE0/wmsresult.dat, this=00000065C53E4D40) -GDAL: GDALOpen(/vsimem/wms/00000065CA1A3530/wmsresult.dat, this=00000065C53E4D40) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA1A3530/wmsresult.dat, this=00000065C53E4D40) -GDAL: GDALOpen(/vsimem/wms/00000065CA838A80/wmsresult.dat, this=00000065C53E5000) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA838A80/wmsresult.dat, this=00000065C53E5000) -GDAL: GDALOpen(/vsimem/wms/00000065CA87ABD0/wmsresult.dat, this=00000065C53E4D40) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA87ABD0/wmsresult.dat, this=00000065C53E4D40) -GDAL: GDALOpen(/vsimem/wms/00000065CA8972F0/wmsresult.dat, this=00000065C53E5840) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA8972F0/wmsresult.dat, this=00000065C53E5840) -GDAL: GDALOpen(/vsimem/wms/00000065CA8C15D0/wmsresult.dat, this=00000065C53E5000) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA8C15D0/wmsresult.dat, this=00000065C53E5000) -GDAL: GDALOpen(/vsimem/wms/00000065CA8D6AE0/wmsresult.dat, this=00000065C53E4240) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA8D6AE0/wmsresult.dat, this=00000065C53E4240) -GDAL: GDALOpen(/vsimem/wms/00000065CA1B1830/wmsresult.dat, this=00000065C53E52C0) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA1B1830/wmsresult.dat, this=00000065C53E52C0) -GDAL: GDALOpen(/vsimem/wms/00000065CA8FE760/wmsresult.dat, this=00000065C53E5000) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA8FE760/wmsresult.dat, this=00000065C53E5000) -GDAL: GDALOpen(/vsimem/wms/00000065CA8F0460/wmsresult.dat, this=00000065C53E4500) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA8F0460/wmsresult.dat, this=00000065C53E4500) -GDAL: GDALOpen(/vsimem/wms/00000065CA91C550/wmsresult.dat, this=00000065C53E4A80) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA91C550/wmsresult.dat, this=00000065C53E4A80) -HTTP: Requesting [1/1] http://198.102.45.23/arcgis/rest/services/gcs_terrain3d/twms?request=GetMap&layers=GCS_Elevation&srs=EPSG:4326&format=image/png&styles=short_int&width=256&height=256&bbox=-180.00000000,-090.00000000,0000.00000000,0090.00000000 -HTTP: Request [0] http://198.102.45.23/arcgis/rest/services/gcs_terrain3d/twms?request=GetMap&layers=GCS_Elevation&srs=EPSG:4326&format=image/png&styles=short_int&width=256&height=256&bbox=-180.00000000,-090.00000000,0000.00000000,0090.00000000 : status = 200, content type = image/png, error = (null) -GDAL: GDALOpen(/vsimem/wms/00000065C81FFFA0/wmsresult.dat, this=00000065C53E5B00) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065C81FFFA0/wmsresult.dat, this=00000065C53E5B00) -HTTP: Requesting [1/1] http://198.102.45.23/arcgis/rest/services/gcs_terrain3d/twms?request=GetMap&layers=GCS_Elevation&srs=EPSG:4326&format=image/png&styles=short_int&width=256&height=256&bbox=0000.00000000,-090.00000000,0180.00000000,0090.00000000 -HTTP: Request [0] http://198.102.45.23/arcgis/rest/services/gcs_terrain3d/twms?request=GetMap&layers=GCS_Elevation&srs=EPSG:4326&format=image/png&styles=short_int&width=256&height=256&bbox=0000.00000000,-090.00000000,0180.00000000,0090.00000000 : status = 200, content type = image/png, error = (null) -GDAL: GDALOpen(/vsimem/wms/00000065CA1B3540/wmsresult.dat, this=00000065C53E4500) succeeds as PNG. -GDAL: GDALClose(/vsimem/wms/00000065CA1B3540/wmsresult.dat, this=00000065C53E4500) diff --git a/modules/globebrowsing/geometry/aabb.cpp b/modules/globebrowsing/geometry/aabb.cpp index 43fe4154fd..0eab00c376 100644 --- a/modules/globebrowsing/geometry/aabb.cpp +++ b/modules/globebrowsing/geometry/aabb.cpp @@ -1,171 +1,189 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ - + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ #include -#include - -namespace { - const std::string _loggerCat = "AABB"; -} +#include namespace openspace { - AABB1::AABB1() : min(1e35), max(-1e35) { } - AABB1::AABB1(float min, float max) : min(min), max(max) { } +namespace globebrowsing { - void AABB1::expand(float p) { - min = glm::min(min, p); - max = glm::max(max, p); - } +AABB1::AABB1() + : AABB1(std::numeric_limits::max(), -std::numeric_limits::max()) +{} - float AABB1::center() const { - return 0.5f * (min + max); - } +AABB1::AABB1(float min, float max) + : min(min) + , max(max) +{} - float AABB1::size() const { - return max - min; - } +void AABB1::expand(float p) { + min = glm::min(min, p); + max = glm::max(max, p); +} - bool AABB1::contains(float p) const { - return (min <= p) && (p <= max); - } +float AABB1::center() const { + return 0.5f * (min + max); +} - bool AABB1::contains(const AABB1& o) const { - return (min <= o.min) && (o.max <= max); - } +float AABB1::size() const { + return max - min; +} - bool AABB1::intersects(const AABB1& o) const { - return (min <= o.max) && (o.min <= max); - } +bool AABB1::contains(float p) const { + return (min <= p) && (p <= max); +} - AABBSpatialRelation AABB1::relationTo(const AABB1& o) const { - if (intersects(o)) { - if (contains(o)) return AABBSpatialRelation::Containing; - if (o.contains(*this)) return AABBSpatialRelation::Contained; - return AABBSpatialRelation::Intersecting; +bool AABB1::contains(const AABB1& o) const { + return (min <= o.min) && (o.max <= max); +} + +bool AABB1::intersects(const AABB1& o) const { + return (min <= o.max) && (o.min <= max); +} + +AABBSpatialRelation AABB1::relationTo(const AABB1& o) const { + if (intersects(o)) { + if (contains(o)) { + return AABBSpatialRelation::Containing; } - return AABBSpatialRelation::None; - } - - - - - - - AABB2::AABB2() : min(1e35), max(-1e35) { } - AABB2::AABB2(const vec2& min, const vec2& max) : min(min), max(max) { } - - void AABB2::expand(const vec2& p) { - min.x = glm::min(min.x, p.x); - min.y = glm::min(min.y, p.y); - max.x = glm::max(max.x, p.x); - max.y = glm::max(max.y, p.y); - } - - vec2 AABB2::center() const { - return 0.5f * (min + max); - } - - vec2 AABB2::size() const { - return max - min; - } - - bool AABB2::contains(const vec2& p) const { - return (min.x <= p.x) && (p.x <= max.x) - && (min.y <= p.y) && (p.y <= max.y); - } - - bool AABB2::contains(const AABB2& o) const { - return (min.x <= o.min.x) && (o.max.x <= max.x) - && (min.y <= o.min.y) && (o.max.y <= max.y); - } - - bool AABB2::intersects(const AABB2& o) const { - return (min.x <= o.max.x) && (o.min.x <= max.x) - && (min.y <= o.max.y) && (o.min.y <= max.y); - } - - AABBSpatialRelation AABB2::relationTo(const AABB2& o) const { - if (intersects(o)) { - if (contains(o)) return AABBSpatialRelation::Containing; - if (o.contains(*this)) return AABBSpatialRelation::Contained; - return AABBSpatialRelation::Intersecting; + if (o.contains(*this)) { + return AABBSpatialRelation::Contained; } - return AABBSpatialRelation::None; + return AABBSpatialRelation::Intersecting; } + return AABBSpatialRelation::None; +} +AABB2::AABB2() + : AABB2( + glm::vec2(std::numeric_limits::max()), + glm::vec2(-std::numeric_limits::max()) + ) +{} +AABB2::AABB2(const glm::vec2& min, const glm::vec2& max) + : min(min) + , max(max) +{} +void AABB2::expand(const glm::vec2& p) { + min = glm::min(min, p); + max = glm::max(max, p); +} - AABB3::AABB3() : min(1e35), max(-1e35) { } - AABB3::AABB3(const vec3& min, const vec3& max) : min(min), max(max) { } +glm::vec2 AABB2::center() const { + return 0.5f * (min + max); +} - void AABB3::expand(const vec3 p) { - min.x = glm::min(min.x, p.x); - min.y = glm::min(min.y, p.y); - min.z = glm::min(min.z, p.z); - max.x = glm::max(max.x, p.x); - max.y = glm::max(max.y, p.y); - max.z = glm::max(max.z, p.z); - } +glm::vec2 AABB2::size() const { + return max - min; +} - vec3 AABB3::center() const { - return 0.5f * (min + max); - } +bool AABB2::contains(const glm::vec2& p) const { + return (min.x <= p.x) && (p.x <= max.x) + && (min.y <= p.y) && (p.y <= max.y); +} - vec3 AABB3::size() const { - return max - min; - } +bool AABB2::contains(const AABB2& o) const { + return (min.x <= o.min.x) && (o.max.x <= max.x) + && (min.y <= o.min.y) && (o.max.y <= max.y); +} - bool AABB3::contains(const vec3& p) const { - return (min.x <= p.x) && (p.x <= max.x) - && (min.y <= p.y) && (p.y <= max.y) - && (min.z <= p.z) && (p.z <= max.z); - } +bool AABB2::intersects(const AABB2& o) const { + return (min.x <= o.max.x) && (o.min.x <= max.x) + && (min.y <= o.max.y) && (o.min.y <= max.y); +} - bool AABB3::contains(const AABB3& o) const { - return (min.x <= o.min.x) && (o.max.x <= max.x) - && (min.y <= o.min.y) && (o.max.y <= max.y) - && (min.z <= o.min.z) && (o.max.z <= max.z); - } - - bool AABB3::intersects(const AABB3& o) const { - return (min.x <= o.max.x) && (o.min.x <= max.x) - && (min.y <= o.max.y) && (o.min.y <= max.y) - && (min.z <= o.max.z) && (o.min.z <= max.z); - } - - AABBSpatialRelation AABB3::relationTo(const AABB3& o) const { - if (intersects(o)) { - if (contains(o)) return AABBSpatialRelation::Containing; - if (o.contains(*this)) return AABBSpatialRelation::Contained; - return AABBSpatialRelation::Intersecting; +AABBSpatialRelation AABB2::relationTo(const AABB2& o) const { + if (intersects(o)) { + if (contains(o)) { + return AABBSpatialRelation::Containing; } - return AABBSpatialRelation::None; + if (o.contains(*this)) { + return AABBSpatialRelation::Contained; + } + return AABBSpatialRelation::Intersecting; } + return AABBSpatialRelation::None; +} +AABB3::AABB3() + : AABB3( + glm::vec3(std::numeric_limits::max()), + glm::vec3(-std::numeric_limits::max()) + ) +{} +AABB3::AABB3(const glm::vec3& min, const glm::vec3& max) + : min(min), + max(max) +{} -} // namespace openspace +void AABB3::expand(const glm::vec3 p) { + min = glm::min(min, p); + max = glm::max(max, p); +} + +glm::vec3 AABB3::center() const { + return 0.5f * (min + max); +} + +glm::vec3 AABB3::size() const { + return max - min; +} + +bool AABB3::contains(const glm::vec3& p) const { + return (min.x <= p.x) && (p.x <= max.x) + && (min.y <= p.y) && (p.y <= max.y) + && (min.z <= p.z) && (p.z <= max.z); +} + +bool AABB3::contains(const AABB3& o) const { + return (min.x <= o.min.x) && (o.max.x <= max.x) + && (min.y <= o.min.y) && (o.max.y <= max.y) + && (min.z <= o.min.z) && (o.max.z <= max.z); +} + +bool AABB3::intersects(const AABB3& o) const { + return (min.x <= o.max.x) && (o.min.x <= max.x) + && (min.y <= o.max.y) && (o.min.y <= max.y) + && (min.z <= o.max.z) && (o.min.z <= max.z); +} + +AABBSpatialRelation AABB3::relationTo(const AABB3& o) const { + if (intersects(o)) { + if (contains(o)) { + return AABBSpatialRelation::Containing; + } + if (o.contains(*this)) { + return AABBSpatialRelation::Contained; + } + return AABBSpatialRelation::Intersecting; + } + return AABBSpatialRelation::None; +} + +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/geometry/aabb.h b/modules/globebrowsing/geometry/aabb.h index d153c5bd7e..a50ea6a6c1 100644 --- a/modules/globebrowsing/geometry/aabb.h +++ b/modules/globebrowsing/geometry/aabb.h @@ -1,99 +1,91 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __AABB_H__ -#define __AABB_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___AABB___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___AABB___H__ -#include #include -// open space includes - - - namespace openspace { +namespace globebrowsing { - using namespace glm; +enum class AABBSpatialRelation { + None, + Intersecting, + Contained, + Containing +}; - enum class AABBSpatialRelation { - None, - Intersecting, - Contained, - Containing - }; +struct AABB1 { + AABB1(); + AABB1(float min, float max); - struct AABB1 { - AABB1(); - AABB1(float min, float max); + void expand(float p); + float center() const; + float size() const; + bool contains(float p) const; + bool contains(const AABB1& o) const; + bool intersects(const AABB1& o) const; + AABBSpatialRelation relationTo(const AABB1& o) const; - void expand(float p); - float center() const; - float size() const; - bool contains(float p) const; - bool contains(const AABB1& o) const; - bool intersects(const AABB1& o) const; - AABBSpatialRelation relationTo(const AABB1& o) const; + float min; + float max; +}; - float min; - float max; - }; +struct AABB2 { + AABB2(); + AABB2(const glm::vec2& min, const glm::vec2& max); + void expand(const glm::vec2& p); + glm::vec2 center() const; + glm::vec2 size() const; + bool contains(const glm::vec2& p) const; + bool contains(const AABB2& o) const; + bool intersects(const AABB2& o) const; + AABBSpatialRelation relationTo(const AABB2& o) const; - struct AABB2 { - AABB2(); - AABB2(const vec2& min, const vec2& max); + glm::vec2 min; + glm::vec2 max; +}; - void expand(const vec2& p); - vec2 center() const; - vec2 size() const; - bool contains(const vec2& p) const; - bool contains(const AABB2& o) const; - bool intersects(const AABB2& o) const; - AABBSpatialRelation relationTo(const AABB2& o) const; +struct AABB3 { + AABB3(); + AABB3(const glm::vec3& min, const glm::vec3& max); - vec2 min; - vec2 max; - }; + void expand(const glm::vec3 p); + glm::vec3 center() const; + glm::vec3 size() const; + bool contains(const glm::vec3& p) const; + bool contains(const AABB3& o) const; + bool intersects(const AABB3& o) const; + AABBSpatialRelation relationTo(const AABB3& o) const; + glm::vec3 min; + glm::vec3 max; +}; - struct AABB3 { - AABB3(); - AABB3(const vec3& min, const vec3& max); +} // namespace globebrowsing +} // namespace openspace - void expand(const vec3 p); - vec3 center() const; - vec3 size() const; - bool contains(const vec3& p) const; - bool contains(const AABB3& o) const; - bool intersects(const AABB3& o) const; - AABBSpatialRelation relationTo(const AABB3& o) const; - - - vec3 min; - vec3 max; - }; - -} // namespace openspace - -#endif // __AABB_H__ +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___AABB___H__ diff --git a/modules/globebrowsing/geometry/angle.h b/modules/globebrowsing/geometry/angle.h index 18996b0abf..3af8e78cde 100644 --- a/modules/globebrowsing/geometry/angle.h +++ b/modules/globebrowsing/geometry/angle.h @@ -22,28 +22,22 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __ANGLE_H__ -#define __ANGLE_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___ANGLE___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___ANGLE___H__ #include #include #include namespace openspace { - +namespace globebrowsing { template class Angle { public: - - ////////////////////////////////////////////////////////////////////////////////////// - // STATIC CONSTANTS // - ////////////////////////////////////////////////////////////////////////////////////// - static const T PI; static const T EPSILON; - /** = 0 radians = 0 degrees = no revolution */ static const Angle ZERO; @@ -56,18 +50,10 @@ public: /** = 2PI radians = 360 degrees = a full revolution */ static const Angle FULL; - - - - ////////////////////////////////////////////////////////////////////////////////////// - // Factory Methods // - ////////////////////////////////////////////////////////////////////////////////////// - static Angle fromRadians(T radians); static Angle fromDegrees(T degrees); static Angle fromRevolutions(T revs); - public: /** Copy constructor */ Angle(const Angle& other); @@ -76,20 +62,11 @@ private: /** Private constructor. Use factory methods to avoid unit confusion */ Angle(T rad); - - ////////////////////////////////////////////////////////////////////////////////////// - // Conversions // - ////////////////////////////////////////////////////////////////////////////////////// public: inline T asRadians() const; inline T asDegrees() const; inline T asRevolutions() const; - - ////////////////////////////////////////////////////////////////////////////////////// - // Operators (boilerplate, I know.. /eb) // - ////////////////////////////////////////////////////////////////////////////////////// - Angle operator+(const Angle& rhs) const; Angle operator-(const Angle& rhs) const; Angle operator*(T rhs) const; @@ -109,14 +86,6 @@ public: bool operator==(const Angle& rhs) const; bool operator!=(const Angle& rhs) const; - - - - - ////////////////////////////////////////////////////////////////////////////////////// - // Chainable Relative Mutators // - ////////////////////////////////////////////////////////////////////////////////////// - /** * Normalizes the angle to the interval [0, 2pi[ */ @@ -133,16 +102,8 @@ public: */ Angle& clamp(const Angle& min = ZERO, const Angle& max = FULL); - Angle& abs(); - - - - ////////////////////////////////////////////////////////////////////////////////////// - // Chainable Relative Factory Methods // - ////////////////////////////////////////////////////////////////////////////////////// - /** * Returns a new angle normalized to the interval [0, 2pi[ */ @@ -159,28 +120,18 @@ public: */ Angle getClamped(const Angle& min = ZERO, const Angle& max = FULL) const; - Angle getAbs() const; - - private: - T _radians; - }; using dAngle = Angle; using fAngle = Angle; +} // namespace globebrowsing } // namespace openspace - - #include - - - - -#endif // __ANGLE_H__ +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___ANGLE___H__ diff --git a/modules/globebrowsing/geometry/angle.inl b/modules/globebrowsing/geometry/angle.inl index 0478f94257..341b35893b 100644 --- a/modules/globebrowsing/geometry/angle.inl +++ b/modules/globebrowsing/geometry/angle.inl @@ -24,11 +24,8 @@ #include - - - namespace openspace { - +namespace globebrowsing { template const T Angle::PI = 3.14159265358979323846264338327950; @@ -36,8 +33,6 @@ const T Angle::PI = 3.14159265358979323846264338327950; template const T Angle::EPSILON = 1e-10; // Should depend on the typedef /eb - - ////////////////////////////////////////////////////////////////////////////////////////// // STATIC CONSTANTS // ////////////////////////////////////////////////////////////////////////////////////////// @@ -54,8 +49,6 @@ const Angle Angle::HALF = Angle::fromRadians(PI); template const Angle Angle::FULL = Angle::fromRadians(2*PI); - - ////////////////////////////////////////////////////////////////////////////////////////// // Constructors // ////////////////////////////////////////////////////////////////////////////////////////// @@ -66,9 +59,6 @@ template Angle::Angle(const Angle& other) template Angle::Angle(T radians) : _radians(radians) { } - - - ////////////////////////////////////////////////////////////////////////////////////////// // Factory Methods // ////////////////////////////////////////////////////////////////////////////////////////// @@ -88,8 +78,6 @@ Angle Angle::fromRevolutions(T revs) { return Angle(revs * 2 * PI); } - - ////////////////////////////////////////////////////////////////////////////////////////// // Conversions // ////////////////////////////////////////////////////////////////////////////////////////// @@ -109,12 +97,10 @@ T Angle::asRevolutions() const { return _radians / (2 * PI); } - ////////////////////////////////////////////////////////////////////////////////////////// // Operators // ////////////////////////////////////////////////////////////////////////////////////////// - template Angle Angle::operator+(const Angle& rhs) const{ return Angle(_radians + rhs._radians); @@ -135,13 +121,11 @@ Angle Angle::operator/(T divisor) const{ return Angle(_radians / divisor); } - template Angle Angle::operator-() const { return Angle(-_radians); } - template void Angle::operator+=(const Angle& rhs){ _radians += rhs._radians; @@ -162,9 +146,6 @@ void Angle::operator/=(T divisor){ _radians /= divisor; } - - - template bool Angle::operator<(const Angle& rhs) const{ return _radians < rhs._radians; @@ -195,8 +176,6 @@ bool Angle::operator!=(const Angle& rhs) const{ return _radians != rhs._radians; } - - ////////////////////////////////////////////////////////////////////////////////////////// // Chainable Relative Mutators // ////////////////////////////////////////////////////////////////////////////////////////// @@ -237,8 +216,6 @@ Angle& Angle::abs(){ return *this; } - - ////////////////////////////////////////////////////////////////////////////////////////// // Chainable Relative Factory Methods // ////////////////////////////////////////////////////////////////////////////////////////// @@ -258,11 +235,10 @@ Angle Angle::getClamped(const Angle& min, const Angle& max) const { return Angle(*this).clamp(min, max); } - - template Angle Angle::getAbs() const { return Angle(*this).abs(); } +} // namespace globebrowsing } // namespace openspace diff --git a/modules/globebrowsing/geometry/convexhull.cpp b/modules/globebrowsing/geometry/convexhull.cpp index c154402e09..48411c55ec 100644 --- a/modules/globebrowsing/geometry/convexhull.cpp +++ b/modules/globebrowsing/geometry/convexhull.cpp @@ -1,183 +1,170 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ - + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ #include -#include -#include -#include -#include +namespace openspace { +namespace globebrowsing { +glm::vec2 ConvexHull2::p0(0,0); -namespace { - const std::string _loggerCat = "ConvexHull"; +ConvexHull2 ConvexHull2::grahamScan_NOT_THREAD_SAFE(std::vector& points, + int yMinIndex) +{ + ConvexHull2 hull; + + if (yMinIndex == -1) { + yMinIndex = 0; + float ymin = points[0].y; + for (int i = 1; i < points.size(); i++) { + float y = points[i].y; + // Pick the bottom-most or chose the left most point in case of tie + if ((y < ymin) || (ymin == y && points[i].x < points[yMinIndex].x)) { + ymin = points[i].y; + yMinIndex = i; + } + } + } + + // Place the bottom-most point at first position + swap(points[0], points[yMinIndex]); + + // Sort n-1 points with respect to the first point. A point p1 comes + // before p2 in sorted ouput if p2 has larger polar angle (in + // counterclockwise direction) than p1 + hull.p0 = points[0]; + + // Replace with std::sort + qsort(&(points.data()[1]), points.size()-1, sizeof(glm::vec2), &(hull.compare)); + + // Create an empty stack and push first three points to it. + std::stack S; + S.push(points[0]); + S.push(points[1]); + S.push(points[2]); + + // Process remaining n-3 points + for (int i = 3; i < points.size(); i++) { + // Keep removing top while the angle formed by points next-to-top, + // top, and points[i] makes a non-left turn + while (orientation(oneBelowTop(S), S.top(), points[i]) == 1) + S.pop(); + S.push(points[i]); + } + + // Now stack has the output points, print contents of stack + while (!S.empty()) { + glm::vec2 p = S.top(); + hull._points.push_back(p); + S.pop(); + } + + return hull; } -namespace openspace { - - Point2 ConvexHull2::p0(0,0); +bool ConvexHull2::intersects(const ConvexHull2& other) const { + // uses Separating Axis Theorem + // ref: http://stackoverflow.com/questions/753140/how-do-i-determine-if-two-convex-polygons-intersect + return this->hasPerpendicularLineWhereProjectedPointsOverlap(other) || + other.hasPerpendicularLineWhereProjectedPointsOverlap(*this); +} - ConvexHull2::ConvexHull2(){ } - - ConvexHull2 ConvexHull2::grahamScan_NOT_THREAD_SAFE(std::vector& points, int yMinIndex){ - ConvexHull2 hull; - - if (yMinIndex == -1){ - yMinIndex = 0; - float ymin = points[0].y; - for (int i = 1; i < points.size(); i++) { - float y = points[i].y; - // Pick the bottom-most or chose the left most point in case of tie - if ((y < ymin) || (ymin == y && points[i].x < points[yMinIndex].x)) { - ymin = points[i].y; - yMinIndex = i; - } - } - } - - // Place the bottom-most point at first position - swap(points[0], points[yMinIndex]); - - // Sort n-1 points with respect to the first point. A point p1 comes - // before p2 in sorted ouput if p2 has larger polar angle (in - // counterclockwise direction) than p1 - hull.p0 = points[0]; - - qsort(&(points.data()[1]), points.size()-1, sizeof(Point2), &(hull.compare)); - - - - // Create an empty stack and push first three points to it. - std::stack S; - S.push(points[0]); - S.push(points[1]); - S.push(points[2]); - - // Process remaining n-3 points - for (int i = 3; i < points.size(); i++) - { - // Keep removing top while the angle formed by points next-to-top, - // top, and points[i] makes a non-left turn - while (orientation(oneBelowTop(S), S.top(), points[i]) == 1) - S.pop(); - S.push(points[i]); - } - - // Now stack has the output points, print contents of stack - while (!S.empty()) - { - Point2 p = S.top(); - hull._points.push_back(p); - S.pop(); - } - - return hull; - } - - bool ConvexHull2::intersects(const ConvexHull2& other) const { - // uses Separating Axis Theorem - // ref: http://stackoverflow.com/questions/753140/how-do-i-determine-if-two-convex-polygons-intersect - return this->hasPerpendicularLineWhereProjectedPointsOverlap(other) || - other.hasPerpendicularLineWhereProjectedPointsOverlap(*this); - } - - - bool ConvexHull2::hasPerpendicularLineWhereProjectedPointsOverlap(const ConvexHull2& other) const { - for (size_t i = 1; i < _points.size(); i++) { - glm::vec2 dividingAxis = _points[i] - _points[i - 1]; - // project all points onto the vector perpendicular to the dividing axis - glm::vec2 projAxis(glm::normalize(glm::vec2(-dividingAxis.y, dividingAxis.x))); - const AABB1& myBounds = projectedRegion(projAxis); - const AABB1& otherBounds = other.projectedRegion(projAxis); - if (!myBounds.intersects(otherBounds)) { - return false; - } - } - - // test line defined by last-to-first point - glm::vec2 dividingAxis = _points[0] - _points.back(); +bool ConvexHull2::hasPerpendicularLineWhereProjectedPointsOverlap(const ConvexHull2& other) const { + for (size_t i = 1; i < _points.size(); i++) { + glm::vec2 dividingAxis = _points[i] - _points[i - 1]; + // project all points onto the vector perpendicular to the dividing axis glm::vec2 projAxis(glm::normalize(glm::vec2(-dividingAxis.y, dividingAxis.x))); const AABB1& myBounds = projectedRegion(projAxis); const AABB1& otherBounds = other.projectedRegion(projAxis); if (!myBounds.intersects(otherBounds)) { return false; } - - return true; } - - AABB1 ConvexHull2::projectedRegion(glm::vec2 direction) const { - AABB1 projectedRegion; - for (size_t i = 0; i < _points.size(); i++) { - projectedRegion.expand(glm::dot(_points[i], direction)); - } - return projectedRegion; + // test line defined by last-to-first point + glm::vec2 dividingAxis = _points[0] - _points.back(); + glm::vec2 projAxis(glm::normalize(glm::vec2(-dividingAxis.y, dividingAxis.x))); + const AABB1& myBounds = projectedRegion(projAxis); + const AABB1& otherBounds = other.projectedRegion(projAxis); + if (!myBounds.intersects(otherBounds)) { + return false; } + return true; +} +AABB1 ConvexHull2::projectedRegion(glm::vec2 direction) const { + AABB1 projectedRegion; + for (const glm::vec2& p : _points) { + projectedRegion.expand(glm::dot(p, direction)); + } + //for (size_t i = 0; i < _points.size(); i++) { + // projectedRegion.expand(glm::dot(_points[i], direction)); + //} + return projectedRegion; +} - Point2 ConvexHull2::oneBelowTop(std::stack& S) { - Point2 p = S.top(); - S.pop(); - Point2 res = S.top(); - S.push(p); - return res; +glm::vec2 ConvexHull2::oneBelowTop(std::stack& S) { + glm::vec2 p = S.top(); + S.pop(); + glm::vec2 res = S.top(); + S.push(p); + return res; +} + +void ConvexHull2::swap(glm::vec2& p1, glm::vec2& p2) { + glm::vec2 temp = p1; + p1 = p2; + p2 = temp; +} + +const std::vector ConvexHull2::points() const { + return _points; +} + +int ConvexHull2::orientation(const glm::vec2& p, const glm::vec2& q, const glm::vec2& r) { + float val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); + return (val == 0) ? 0 : (val > 0) ? 1 : 2; +} + +float ConvexHull2::dist(const glm::vec2& p1, const glm::vec2& p2) { + return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y); +} + +int ConvexHull2::compare(const void *vp1, const void *vp2) { + glm::vec2* p1 = (glm::vec2 *)vp1; + glm::vec2* p2 = (glm::vec2 *)vp2; + + // Find orientation + int o = orientation(p0, *p1, *p2); + if (o == 0) { + return (dist(p0, *p2) >= dist(p0, *p1)) ? -1 : 1; } - void ConvexHull2::swap(Point2& p1, Point2& p2) { - Point2 temp = p1; - p1 = p2; - p2 = temp; - } + return (o == 2) ? -1 : 1; +} - const std::vector ConvexHull2::points() const { - return _points; - } - - - int ConvexHull2::orientation(const Point2& p, const Point2& q, const Point2& r) { - float val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); - return (val == 0) ? 0 : (val > 0) ? 1 : 2; - } - - float ConvexHull2::dist(const Point2& p1, const Point2& p2) { - return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y); - } - - int ConvexHull2::compare(const void *vp1, const void *vp2) { - Point2 *p1 = (Point2 *)vp1; - Point2 *p2 = (Point2 *)vp2; - - // Find orientation - int o = orientation(p0, *p1, *p2); - if (o == 0) - return (dist(p0, *p2) >= dist(p0, *p1)) ? -1 : 1; - - return (o == 2) ? -1 : 1; - } - -} // namespace openspace +} // namespace globebrowsing +} // namespace openspace \ No newline at end of file diff --git a/modules/globebrowsing/geometry/convexhull.h b/modules/globebrowsing/geometry/convexhull.h index 093d3f8403..7fc1da2c86 100644 --- a/modules/globebrowsing/geometry/convexhull.h +++ b/modules/globebrowsing/geometry/convexhull.h @@ -1,84 +1,72 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __CONVEX_HULL_H__ -#define __CONVEX_HULL_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___CONVEX_HULL___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___CONVEX_HULL___H__ #include - -#include #include +#include -#include #include -// open space includes - - - namespace openspace { +namespace globebrowsing { - using namespace glm; +// Implementation based on +// http://www.sanfoundry.com/cpp-program-implement-graham-scan-algorithm-find-convex-hull/ + +class ConvexHull2 { +public: + static ConvexHull2 grahamScan_NOT_THREAD_SAFE(std::vector& points, + int yMinIndex = -1); + + const std::vector points() const; + + bool intersects(const ConvexHull2& o) const; + + AABB1 projectedRegion(glm::vec2 direction) const; - // Implementation based on - // http://www.sanfoundry.com/cpp-program-implement-graham-scan-algorithm-find-convex-hull/ +private: + bool hasPerpendicularLineWhereProjectedPointsOverlap(const ConvexHull2& other) const; - typedef glm::vec2 Point2; + static int compare(const void* vp1, const void* vp2); - class ConvexHull2 { - public: - ConvexHull2(); + static glm::vec2 oneBelowTop(std::stack&); + static void swap(glm::vec2& p1, glm::vec2& p2); - static ConvexHull2 grahamScan_NOT_THREAD_SAFE(std::vector& points, int yMinIndex = -1); + // returns 0 = colinear, 1 = clockwise, 2 = counterclockwise + static int orientation(const glm::vec2& p, const glm::vec2& q, const glm::vec2& r); + static float dist(const glm::vec2& p1, const glm::vec2& p2); - const std::vector points() const; +private: + static glm::vec2 p0; + std::vector _points; +}; - bool intersects(const ConvexHull2& o) const; +} // namespace globebrowsing +} // namespace openspace - AABB1 projectedRegion(glm::vec2 direction) const; - - - private: - bool hasPerpendicularLineWhereProjectedPointsOverlap(const ConvexHull2& other) const; - - static int compare(const void *vp1, const void *vp2); - - static Point2 oneBelowTop(std::stack&); - static void swap(Point2& p1, Point2& p2); - - // returns 0 = colinear, 1 = clockwise, 2 = counterclockwise - static int orientation(const Point2& p, const Point2& q, const Point2& r); - static float dist(const Point2& p1, const Point2& p2); - - - private: - static Point2 p0; - std::vector _points; - }; - - -} // namespace openspace - -#endif // __CONVEX_HULL_H__ \ No newline at end of file +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___CONVEX_HULL___H__ diff --git a/modules/globebrowsing/geometry/ellipsoid.cpp b/modules/globebrowsing/geometry/ellipsoid.cpp index b77bd1c9aa..f89f15e84a 100644 --- a/modules/globebrowsing/geometry/ellipsoid.cpp +++ b/modules/globebrowsing/geometry/ellipsoid.cpp @@ -24,168 +24,150 @@ #include -#define _USE_MATH_DEFINES -#include #include - -namespace { - const std::string _loggerCat = "Ellipsoid"; -} +#include namespace openspace { +namespace globebrowsing { - Ellipsoid::Ellipsoid() : Ellipsoid(1,1,1) { +Ellipsoid::Ellipsoid(glm::dvec3 radii) : _radii(radii) { + updateInternalCache(); +} - } +void Ellipsoid::updateInternalCache() { + _cached._radiiSquared = glm::dvec3( + (_radii.x * _radii.x), + (_radii.y * _radii.y), + (_radii.z * _radii.z)); - Ellipsoid::Ellipsoid(Vec3 radii) : _radii(radii) { - updateInternalCache(); - } - - Ellipsoid::Ellipsoid(Scalar x, Scalar y, Scalar z) : _radii(x, y, z) { - updateInternalCache(); - } - - Ellipsoid::~Ellipsoid(){ - - } - - void Ellipsoid::updateInternalCache() { - _cached._radiiSquared = Vec3( - (_radii.x * _radii.x), - (_radii.y * _radii.y), - (_radii.z * _radii.z)); - - _cached._oneOverRadiiSquared = Vec3(1) / _cached._radiiSquared; - _cached._radiiToTheFourth = _cached._radiiSquared * _cached._radiiSquared; + _cached._oneOverRadiiSquared = glm::dvec3(1) / _cached._radiiSquared; + _cached._radiiToTheFourth = _cached._radiiSquared * _cached._radiiSquared; - std::vector radii = { _radii.x, _radii.y, _radii.z }; - std::sort(radii.begin(), radii.end()); - _cached._minimumRadius = radii[0]; - _cached._medianRadius = radii[1]; - _cached._maximumRadius = radii[2]; - } + std::vector radii = { _radii.x, _radii.y, _radii.z }; + std::sort(radii.begin(), radii.end()); + _cached._minimumRadius = radii[0]; + _cached._medianRadius = radii[1]; + _cached._maximumRadius = radii[2]; +} - +glm::dvec3 Ellipsoid::geocentricSurfaceProjection(const glm::dvec3& p) const { + double beta = 1.0 / sqrt(dot(p * p, _cached._oneOverRadiiSquared)); + return beta * p; +} - - Vec3 Ellipsoid::geocentricSurfaceProjection(const Vec3& p) const { - Scalar beta = 1.0 / sqrt(dot(p * p, _cached._oneOverRadiiSquared)); - return beta * p; - } - - Vec3 Ellipsoid::geodeticSurfaceProjection(const Vec3& p) const { - Scalar beta = 1.0 / sqrt(dot(p * p, _cached._oneOverRadiiSquared)); - Scalar n = glm::length(beta * p * _cached._oneOverRadiiSquared); - Scalar alpha = (1.0 - beta) * (glm::length(p) / n); +glm::dvec3 Ellipsoid::geodeticSurfaceProjection(const glm::dvec3& p) const { + double beta = 1.0 / sqrt(dot(p * p, _cached._oneOverRadiiSquared)); + double n = glm::length(beta * p * _cached._oneOverRadiiSquared); + double alpha = (1.0 - beta) * (glm::length(p) / n); - Vec3 p2 = p * p; - Vec3 d, d2, d3; + glm::dvec3 p2 = p * p; + glm::dvec3 d, d2, d3; - Scalar s = 0.0; - Scalar dSdA = 1.0; + double s = 0.0; + double dSdA = 1.0; - Scalar epsilon = 1e-10; - do { - alpha -= (s / dSdA); + double epsilon = 1e-10; + do { + alpha -= (s / dSdA); - d = Vec3(1.0) + alpha * _cached._oneOverRadiiSquared; - d2 = d * d; - d3 = d * d2; + d = glm::dvec3(1.0) + alpha * _cached._oneOverRadiiSquared; + d2 = d * d; + d3 = d * d2; - s = glm::dot(p2 / (_cached._radiiSquared * d2), Vec3(1.0)) - 1.0; + s = glm::dot(p2 / (_cached._radiiSquared * d2), glm::dvec3(1.0)) - 1.0; - dSdA = -2.0 * glm::dot(p2 / (_cached._radiiToTheFourth * d3), Vec3(1.0)); - } - while (abs(s) > epsilon); - return p / d; + dSdA = -2.0 * glm::dot(p2 / (_cached._radiiToTheFourth * d3), glm::dvec3(1.0)); } + while (abs(s) > epsilon); + return p / d; +} - Vec3 Ellipsoid::geodeticSurfaceNormalForGeocentricallyProjectedPoint(const Vec3& p) const { - Vec3 normal = p * _cached._oneOverRadiiSquared; - return glm::normalize(normal); - } +glm::dvec3 Ellipsoid::geodeticSurfaceNormalForGeocentricallyProjectedPoint(const glm::dvec3& p) const { + glm::dvec3 normal = p * _cached._oneOverRadiiSquared; + return glm::normalize(normal); +} - Vec3 Ellipsoid::geodeticSurfaceNormal(Geodetic2 geodetic2) const { - Scalar cosLat = glm::cos(geodetic2.lat); - //geodetic2.lon = geodetic2.lon > M_PI ? geodetic2.lon - M_PI * 2 : geodetic2.lon; - return Vec3( - cosLat * cos(geodetic2.lon), - cosLat * sin(geodetic2.lon), - sin(geodetic2.lat)); - } +glm::dvec3 Ellipsoid::geodeticSurfaceNormal(Geodetic2 geodetic2) const { + double cosLat = glm::cos(geodetic2.lat); + //geodetic2.lon = geodetic2.lon > M_PI ? geodetic2.lon - M_PI * 2 : geodetic2.lon; + return glm::dvec3( + cosLat * cos(geodetic2.lon), + cosLat * sin(geodetic2.lon), + sin(geodetic2.lat)); +} - const Vec3& Ellipsoid::radii() const { - return _radii; - } +const glm::dvec3& Ellipsoid::radii() const { + return _radii; +} - const Vec3& Ellipsoid::radiiSquared() const { - return _cached._radiiSquared; - } +const glm::dvec3& Ellipsoid::radiiSquared() const { + return _cached._radiiSquared; +} - const Vec3& Ellipsoid::oneOverRadiiSquared() const { - return _cached._oneOverRadiiSquared; - } +const glm::dvec3& Ellipsoid::oneOverRadiiSquared() const { + return _cached._oneOverRadiiSquared; +} - const Vec3& Ellipsoid::radiiToTheFourth() const { - return _cached._radiiToTheFourth; - } +const glm::dvec3& Ellipsoid::radiiToTheFourth() const { + return _cached._radiiToTheFourth; +} - Scalar Ellipsoid::minimumRadius() const { - return _cached._minimumRadius; - } +double Ellipsoid::minimumRadius() const { + return _cached._minimumRadius; +} - Scalar Ellipsoid::maximumRadius() const { - return _cached._maximumRadius; - } +double Ellipsoid::maximumRadius() const { + return _cached._maximumRadius; +} - Scalar Ellipsoid::averageRadius() const { - return (_radii.x + _radii.y + _radii.z) / 3.0; - } +double Ellipsoid::averageRadius() const { + return (_radii.x + _radii.y + _radii.z) / 3.0; +} - Scalar Ellipsoid::longitudalDistance(Scalar lat, Scalar lon1, Scalar lon2) const { - Vec2 ellipseRadii = glm::cos(lat) * Vec2(_radii); - // Approximating with the ellipse mean radius - Scalar meanRadius = 0.5 * (ellipseRadii.x + ellipseRadii.y); - return meanRadius * std::abs(lon2 - lon1); - } +double Ellipsoid::longitudalDistance(double lat, double lon1, double lon2) const { + glm::dvec2 ellipseRadii = glm::cos(lat) * glm::dvec2(_radii); + // Approximating with the ellipse mean radius + double meanRadius = 0.5 * (ellipseRadii.x + ellipseRadii.y); + return meanRadius * std::abs(lon2 - lon1); +} - Scalar Ellipsoid::greatCircleDistance(const Geodetic2& p1, const Geodetic2& p2) const{ - // https://en.wikipedia.org/wiki/Meridian_arc - // https://en.wikipedia.org/wiki/Great-circle_distance#Vector_version +double Ellipsoid::greatCircleDistance(const Geodetic2& p1, const Geodetic2& p2) const{ + // https://en.wikipedia.org/wiki/Meridian_arc + // https://en.wikipedia.org/wiki/Great-circle_distance#Vector_version - Vec3 n1 = geodeticSurfaceNormal(p1); - Vec3 n2 = geodeticSurfaceNormal(p2); - Scalar centralAngle = glm::atan(glm::length(glm::cross(n1, n2)) / glm::dot(n1, n2)); + glm::dvec3 n1 = geodeticSurfaceNormal(p1); + glm::dvec3 n2 = geodeticSurfaceNormal(p2); + double centralAngle = glm::atan(glm::length(glm::cross(n1, n2)) / glm::dot(n1, n2)); - Geodetic2 pMid = (p1 + p2) / 2; - Vec3 centralNormal = cartesianSurfacePosition(pMid); + Geodetic2 pMid = (p1 + p2) / 2; + glm::dvec3 centralNormal = cartesianSurfacePosition(pMid); - return centralAngle * glm::length(centralNormal); - } + return centralAngle * glm::length(centralNormal); +} - Geodetic2 Ellipsoid::cartesianToGeodetic2(const Vec3& p) const - { - Vec3 normal = geodeticSurfaceNormalForGeocentricallyProjectedPoint(p); - return Geodetic2( - asin(normal.z / length(normal)), // Latitude - atan2(normal.y, normal.x)); // Longitude - } +Geodetic2 Ellipsoid::cartesianToGeodetic2(const glm::dvec3& p) const +{ + glm::dvec3 normal = geodeticSurfaceNormalForGeocentricallyProjectedPoint(p); + return Geodetic2( + asin(normal.z / length(normal)), // Latitude + atan2(normal.y, normal.x)); // Longitude +} - Vec3 Ellipsoid::cartesianSurfacePosition(const Geodetic2& geodetic2) const - { - // Position on surface : height = 0 - return cartesianPosition(Geodetic3({ geodetic2, 0 })); - } +glm::dvec3 Ellipsoid::cartesianSurfacePosition(const Geodetic2& geodetic2) const +{ + // Position on surface : height = 0 + return cartesianPosition(Geodetic3({ geodetic2, 0 })); +} - Vec3 Ellipsoid::cartesianPosition(const Geodetic3& geodetic3) const - { - Vec3 normal = geodeticSurfaceNormal(geodetic3.geodetic2); - Vec3 k = _cached._radiiSquared * normal; - Scalar gamma = sqrt(dot(k, normal)); - Vec3 rSurface = k / gamma; - return rSurface + geodetic3.height * normal; - } +glm::dvec3 Ellipsoid::cartesianPosition(const Geodetic3& geodetic3) const +{ + glm::dvec3 normal = geodeticSurfaceNormal(geodetic3.geodetic2); + glm::dvec3 k = _cached._radiiSquared * normal; + double gamma = sqrt(dot(k, normal)); + glm::dvec3 rSurface = k / gamma; + return rSurface + geodetic3.height * normal; +} +} // namespace globebrowsing } // namespace openspace diff --git a/modules/globebrowsing/geometry/ellipsoid.h b/modules/globebrowsing/geometry/ellipsoid.h index a65c3d00e8..f4931a85d9 100644 --- a/modules/globebrowsing/geometry/ellipsoid.h +++ b/modules/globebrowsing/geometry/ellipsoid.h @@ -22,91 +22,83 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __ELLIPSOID_H__ -#define __ELLIPSOID_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___ELLIPSOID___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___ELLIPSOID___H__ #include -namespace openspace { +#include - /** - This class is based largely on the Ellipsoid class defined in the book - "3D Engine Design for Virtual Globes". Most planets or planetary objects are better - described using ellipsoids than spheres. All inputs and outputs to this class is - in the WGS84 standard coordinate system where the x-axis points towards geographic - (lat = 0, lon = 0), the y-axis points towards (lat = 0, lon = 90deg) and the - z-axis points towards the north pole. - */ +namespace openspace { +namespace globebrowsing { + +/** + * This class is based largely on the Ellipsoid class defined in the book + * "3D Engine Design for Virtual Globes". Most planets or planetary objects are better + * described using ellipsoids than spheres. All inputs and outputs to this class is + * based on the WGS84 standard coordinate system where the x-axis points towards geographic + * (lat = 0, lon = 0), the y-axis points towards (lat = 0, lon = 90deg) and the + * z-axis points towards the north pole. For other globes than earth of course the radii + * can differ. + */ class Ellipsoid { public: - - Ellipsoid(); + /** + * \param radii defines three radii for the Ellipsoid + */ + Ellipsoid(glm::dvec3 radii = glm::dvec3(1.0, 1.0, 1.0)); /** - \param radii defines three radii for the Ellipsoid - */ - Ellipsoid(Vec3 radii); + * Scales a point along the geocentric normal and places it on the surface of the + * Ellipsoid. + * \param p is a point in the cartesian coordinate system to be placed on the surface + * of the Ellipsoid + */ + glm::dvec3 geocentricSurfaceProjection(const glm::dvec3& p) const; /** - \param x defines the radius in x direction. - \param y defines the radius in y direction. - \param z defines the radius in z direction. - */ - Ellipsoid(Scalar x, Scalar y, Scalar z); - ~Ellipsoid(); + * Scales a point along the geodetic normal and places it on the surface of the + * Ellipsoid. + * \param p is a point in the cartesian coordinate system to be placed on the surface + * of the Ellipsoid + */ + glm::dvec3 geodeticSurfaceProjection(const glm::dvec3& p) const; - - /** - Scales a point along the geocentric normal and places it on the surface of the - Ellipsoid. - \param p is a point in the cartesian coordinate system to be placed on the surface - of the Ellipsoid - */ - Vec3 geocentricSurfaceProjection(const Vec3& p) const; - - - /** - Scales a point along the geodetic normal and places it on the surface of the - Ellipsoid. - \param p is a point in the cartesian coordinate system to be placed on the surface - of the Ellipsoid - */ - Vec3 geodeticSurfaceProjection(const Vec3& p) const; - - Vec3 geodeticSurfaceNormalForGeocentricallyProjectedPoint(const Vec3& p) const; - Vec3 geodeticSurfaceNormal(Geodetic2 geodetic2) const; + glm::dvec3 geodeticSurfaceNormalForGeocentricallyProjectedPoint(const glm::dvec3& p) const; + glm::dvec3 geodeticSurfaceNormal(Geodetic2 geodetic2) const; - const Vec3& radii() const; - const Vec3& radiiSquared() const; - const Vec3& oneOverRadiiSquared() const; - const Vec3& radiiToTheFourth() const; + const glm::dvec3& radii() const; + const glm::dvec3& radiiSquared() const; + const glm::dvec3& oneOverRadiiSquared() const; + const glm::dvec3& radiiToTheFourth() const; + double minimumRadius() const; + double maximumRadius() const; + double averageRadius() const; - Scalar minimumRadius() const; - Scalar maximumRadius() const; - Scalar averageRadius() const; + double longitudalDistance(double lat, double lon1, double lon2) const; + double greatCircleDistance(const Geodetic2& p1, const Geodetic2& p2) const; - Scalar longitudalDistance(Scalar lat, Scalar lon1, Scalar lon2) const; - Scalar greatCircleDistance(const Geodetic2& p1, const Geodetic2& p2) const; - - Geodetic2 cartesianToGeodetic2(const Vec3& p) const; - Vec3 cartesianSurfacePosition(const Geodetic2& geodetic2) const; - Vec3 cartesianPosition(const Geodetic3& geodetic3) const; + Geodetic2 cartesianToGeodetic2(const glm::dvec3& p) const; + glm::dvec3 cartesianSurfacePosition(const Geodetic2& geodetic2) const; + glm::dvec3 cartesianPosition(const Geodetic3& geodetic3) const; private: struct EllipsoidCache { - Vec3 _radiiSquared; - Vec3 _oneOverRadiiSquared; - Vec3 _radiiToTheFourth; - Scalar _minimumRadius; - Scalar _maximumRadius; - Scalar _medianRadius; + glm::dvec3 _radiiSquared; + glm::dvec3 _oneOverRadiiSquared; + glm::dvec3 _radiiToTheFourth; + double _minimumRadius; + double _maximumRadius; + double _medianRadius; } _cached; void updateInternalCache(); - Vec3 _radii; + glm::dvec3 _radii; }; + +} // namespace globebrowsing } // namespace openspace -#endif // __ELLIPSOID_H__ +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___ELLIPSOID___H__ diff --git a/modules/globebrowsing/geometry/geodetic2.cpp b/modules/globebrowsing/geometry/geodetic2.cpp index 4b0eb79519..b0f7f81d98 100644 --- a/modules/globebrowsing/geometry/geodetic2.cpp +++ b/modules/globebrowsing/geometry/geodetic2.cpp @@ -23,292 +23,252 @@ ****************************************************************************************/ #include + #include -#include - -#include - - - -namespace { - const std::string _loggerCat = "Geodetic2"; -} namespace openspace { - ////////////////////////////////////////////////////////////////////////////////////// - // GEODETIC2 // - ////////////////////////////////////////////////////////////////////////////////////// +namespace globebrowsing { - Geodetic2::Geodetic2() - : lat(0) - , lon(0) - {} +Geodetic2::Geodetic2(double latitude, double longitude) + : lat(latitude) + , lon(longitude) +{} - Geodetic2::Geodetic2(Scalar latitude, Scalar longitude) - : lat(latitude) - , lon(longitude) - { +Geodetic2::Geodetic2(const Geodetic2& p) + : Geodetic2(p.lat, p.lon) +{} - } +glm::dvec2 Geodetic2::toLonLatVec2() const { + return glm::dvec2(lon, lat); +} - Geodetic2::Geodetic2(const Geodetic2& p) - : Geodetic2(p.lat, p.lon) - { +bool Geodetic2::operator==(const Geodetic2& other) const { + return lat == other.lat && lon == other.lon; +} - } +Geodetic2 Geodetic2::operator+(const Geodetic2& other) const { + return Geodetic2(lat + other.lat, lon + other.lon); +} +Geodetic2 Geodetic2::operator-(const Geodetic2& other) const { + return Geodetic2(lat - other.lat, lon - other.lon); +} - Vec2 Geodetic2::toLonLatVec2() const { - return Vec2(lon, lat); - } +Geodetic2 Geodetic2::operator*(double scalar) const { + return Geodetic2(lat * scalar, lon * scalar); +} - bool Geodetic2::operator==(const Geodetic2& other) const { - return lat == other.lat && lon == other.lon; - } +Geodetic2 Geodetic2::operator/(double scalar) const { + return Geodetic2(lat / scalar, lon / scalar); +} - Geodetic2 Geodetic2::operator+(const Geodetic2& other) const { - return Geodetic2(lat + other.lat, lon + other.lon); - } +GeodeticPatch::GeodeticPatch(double centerLat, double centerLon, double halfSizeLat, + double halfSizeLon) + : _center(Geodetic2(centerLat, centerLon)) + , _halfSize(Geodetic2(halfSizeLat, halfSizeLon)) +{} - Geodetic2 Geodetic2::operator-(const Geodetic2& other) const { - return Geodetic2(lat - other.lat, lon - other.lon); - } +GeodeticPatch::GeodeticPatch(const Geodetic2& center, const Geodetic2& halfSize) + : _center(center) + , _halfSize(halfSize) +{} - Geodetic2 Geodetic2::operator*(Scalar scalar) const { - return Geodetic2(lat * scalar, lon * scalar); - } +GeodeticPatch::GeodeticPatch(const GeodeticPatch& patch) + : _center(patch._center) + , _halfSize(patch._halfSize) +{} - Geodetic2 Geodetic2::operator/(Scalar scalar) const { - return Geodetic2(lat / scalar, lon / scalar); - } +GeodeticPatch::GeodeticPatch(const TileIndex& tileIndex) { + double deltaLat = (2 * glm::pi()) / ((double)(1 << tileIndex.level)); + double deltaLon = (2 * glm::pi()) / ((double)(1 << tileIndex.level)); + Geodetic2 nwCorner(glm::pi() / 2 - deltaLat * tileIndex.y, -glm::pi() + deltaLon * tileIndex.x); + _halfSize = Geodetic2(deltaLat / 2, deltaLon / 2); + _center = Geodetic2(nwCorner.lat - _halfSize.lat, nwCorner.lon + _halfSize.lon); +} +void GeodeticPatch::setCenter(const Geodetic2& center) { + _center = center; +} - ////////////////////////////////////////////////////////////////////////////////////// - // GEODETICPATCH // - ////////////////////////////////////////////////////////////////////////////////////// +void GeodeticPatch::setHalfSize(const Geodetic2& halfSize) { + _halfSize = halfSize; +} - GeodeticPatch::GeodeticPatch( - Scalar centerLat, - Scalar centerLon, - Scalar halfSizeLat, - Scalar halfSizeLon) - : _center(Geodetic2(centerLat, centerLon)) - , _halfSize(Geodetic2(halfSizeLat, halfSizeLon)) - { +double GeodeticPatch::maximumTileLevel() const { + // Numerator is just pi, not 2*pi, since we are dealing with HALF sizes + return log2(glm::pi() / glm::min(_halfSize.lat, _halfSize.lon)); +} - } +double GeodeticPatch::minimumTileLevel() const { + // Numerator is just pi, not 2*pi, since we are dealing with HALF sizes + return log2(glm::pi() / glm::max(_halfSize.lat, _halfSize.lon)); +} - GeodeticPatch::GeodeticPatch( - const Geodetic2& center, - const Geodetic2& halfSize) - : _center(center) - , _halfSize(halfSize) - { +const Geodetic2& GeodeticPatch::center() const { + return _center; +} - } +const Geodetic2& GeodeticPatch::halfSize() const { + return _halfSize; +} - GeodeticPatch::GeodeticPatch(const GeodeticPatch& patch) - : _center(patch._center) - , _halfSize(patch._halfSize) - { +Geodetic2 GeodeticPatch::size() const { + return Geodetic2(2 * _halfSize.lat, 2 * _halfSize.lon); +} - } - - - GeodeticPatch::GeodeticPatch(const ChunkIndex& chunkIndex) { - Scalar deltaLat = (2 * M_PI) / ((double)(1 << chunkIndex.level)); - Scalar deltaLon = (2 * M_PI) / ((double)(1 << chunkIndex.level)); - Geodetic2 nwCorner(M_PI / 2 - deltaLat * chunkIndex.y, -M_PI + deltaLon * chunkIndex.x); - _halfSize = Geodetic2(deltaLat / 2, deltaLon / 2); - _center = Geodetic2(nwCorner.lat - _halfSize.lat, nwCorner.lon + _halfSize.lon); - } - - - - - void GeodeticPatch::setCenter(const Geodetic2& center) { - _center = center; - } - - void GeodeticPatch::setHalfSize(const Geodetic2& halfSize) { - _halfSize = halfSize; - } - - Scalar GeodeticPatch::maximumTileLevel() const { - // Numerator is just pi, not 2*pi, since we are dealing with HALF sizes - return log2(M_PI / glm::min(_halfSize.lat, _halfSize.lon)); - } - - Scalar GeodeticPatch::minimumTileLevel() const { - // Numerator is just pi, not 2*pi, since we are dealing with HALF sizes - return log2(M_PI / glm::max(_halfSize.lat, _halfSize.lon)); - } - - const Geodetic2& GeodeticPatch::center() const { - return _center; - } - - const Geodetic2& GeodeticPatch::halfSize() const { - return _halfSize; - } - - Geodetic2 GeodeticPatch::size() const { - return Geodetic2(2 * _halfSize.lat, 2 * _halfSize.lon); - } - - Geodetic2 GeodeticPatch::getCorner(Quad q) const { - switch (q) { +Geodetic2 GeodeticPatch::getCorner(Quad q) const { + switch (q) { case NORTH_WEST: return Geodetic2(maxLat(), minLon());// northWestCorner(); case NORTH_EAST: return Geodetic2(maxLat(), maxLon());// northEastCorner(); case SOUTH_WEST: return Geodetic2(minLat(), minLon());// southWestCorner(); case SOUTH_EAST: return Geodetic2(minLat(), maxLon());// southEastCorner(); - } } +} - Scalar GeodeticPatch::minLat() const { - return _center.lat - _halfSize.lat; - } +Geodetic2 GeodeticPatch::getSize() const { + return _halfSize * 2; +} - Scalar GeodeticPatch::maxLat() const { - return _center.lat + _halfSize.lat; - } +double GeodeticPatch::minLat() const { + return _center.lat - _halfSize.lat; +} - Scalar GeodeticPatch::minLon() const { - return _center.lon - _halfSize.lon; - } +double GeodeticPatch::maxLat() const { + return _center.lat + _halfSize.lat; +} - Scalar GeodeticPatch::maxLon() const { - return _center.lon + _halfSize.lon; - } +double GeodeticPatch::minLon() const { + return _center.lon - _halfSize.lon; +} +double GeodeticPatch::maxLon() const { + return _center.lon + _halfSize.lon; +} - bool GeodeticPatch::contains(const Geodetic2& p) const { - Geodetic2 diff = _center - p; - return glm::abs(diff.lat) <= _halfSize.lat && glm::abs(diff.lon) <= _halfSize.lon; - } +bool GeodeticPatch::contains(const Geodetic2& p) const { + Geodetic2 diff = _center - p; + return glm::abs(diff.lat) <= _halfSize.lat && glm::abs(diff.lon) <= _halfSize.lon; +} +double GeodeticPatch::edgeLatitudeNearestEquator() const { + return _center.lat + _halfSize.lat * (isNorthern() ? -1 : 1); +} - Scalar GeodeticPatch::edgeLatitudeNearestEquator() const { - return _center.lat + _halfSize.lat * (isNorthern() ? -1 : 1); - } +double GeodeticPatch::isNorthern() const { + return _center.lat > 0.0; +} - Scalar GeodeticPatch::isNorthern() const { - return _center.lat > 0.0; - } +Geodetic2 GeodeticPatch::clamp(const Geodetic2& p) const { + using Ang = Angle; + // Convert to Angles for normalization + Ang centerLat = Ang::fromRadians(_center.lat); + Ang centerLon = Ang::fromRadians(_center.lon); + Ang pointLat = Ang::fromRadians(p.lat); + Ang pointLon = Ang::fromRadians(p.lon); - Geodetic2 GeodeticPatch::clamp(const Geodetic2& p) const { - using Ang = Angle; + // Normalize w.r.t. the center in order for the clamping to done correctly + // + // Example: + // centerLat = 0 deg, halfSize.lat = 10 deg, pointLat = 330 deg + // --> Just clamping pointLat would be clamp(330, -10, 10) = 10 // WRONG! + // Instead, if we first normalize 330 deg around 0, we get -30 deg + // --> clamp(-30, -10, 10) = -10 // CORRECT! + pointLat.normalizeAround(centerLat); + pointLon.normalizeAround(centerLon); - // Convert to Angles for normalization - Ang centerLat = Ang::fromRadians(_center.lat); - Ang centerLon = Ang::fromRadians(_center.lon); - Ang pointLat = Ang::fromRadians(p.lat); - Ang pointLon = Ang::fromRadians(p.lon); + return Geodetic2( + glm::clamp(pointLat.asRadians(), minLat(), maxLat()), + glm::clamp(pointLon.asRadians(), minLon(), maxLon()) + ); +} - // Normalize w.r.t. the center in order for the clamping to done correctly - // - // Example: - // centerLat = 0 deg, halfSize.lat = 10 deg, pointLat = 330 deg - // --> Just clamping pointLat would be clamp(330, -10, 10) = 10 // WRONG! - // Instead, if we first normalize 330 deg around 0, we get -30 deg - // --> clamp(-30, -10, 10) = -10 // CORRECT! - pointLat.normalizeAround(centerLat); - pointLon.normalizeAround(centerLon); +Geodetic2 GeodeticPatch::closestCorner(const Geodetic2& p) const { + using Ang = Angle; - return Geodetic2( - glm::clamp(pointLat.asRadians(), minLat(), maxLat()), - glm::clamp(pointLon.asRadians(), minLon(), maxLon()) - ); - } - - - Geodetic2 GeodeticPatch::closestCorner(const Geodetic2& p) const { - using Ang = Angle; - - // LatLon vector from patch center to the point - Geodetic2 centerToPoint = p - _center; + // LatLon vector from patch center to the point + Geodetic2 centerToPoint = p - _center; - // Normalize the difference angles to be centered around 0. - Ang latDiff = Ang::fromRadians(centerToPoint.lat).normalizeAround(Ang::ZERO); - Ang lonDiff = Ang::fromRadians(centerToPoint.lon).normalizeAround(Ang::ZERO); + // Normalize the difference angles to be centered around 0. + Ang latDiff = Ang::fromRadians(centerToPoint.lat).normalizeAround(Ang::ZERO); + Ang lonDiff = Ang::fromRadians(centerToPoint.lon).normalizeAround(Ang::ZERO); - // If latDiff > 0 - // --> point p is north of the patch center - // --> the closest corner to the point must be a northern one - // --> set the corner's latitude coordinate to center.lat + halfSize.lat - // else - // --> set corner's latidude coordinate to center.lat - halfSize.lat - Scalar cornerLat = _center.lat + _halfSize.lat * (latDiff > Ang::ZERO ? 1 : -1); + // If latDiff > 0 + // --> point p is north of the patch center + // --> the closest corner to the point must be a northern one + // --> set the corner's latitude coordinate to center.lat + halfSize.lat + // else + // --> set corner's latidude coordinate to center.lat - halfSize.lat + double cornerLat = _center.lat + _halfSize.lat * (latDiff > Ang::ZERO ? 1 : -1); - // We then assigned the corner's longitude coordinate in a similar fashion - Scalar cornerLon = _center.lon + _halfSize.lon * (lonDiff > Ang::ZERO ? 1 : -1); + // We then assigned the corner's longitude coordinate in a similar fashion + double cornerLon = _center.lon + _halfSize.lon * (lonDiff > Ang::ZERO ? 1 : -1); - return Geodetic2(cornerLat, cornerLon); - } + return Geodetic2(cornerLat, cornerLon); +} - - Geodetic2 GeodeticPatch::closestPoint(const Geodetic2& p) const { - // This method finds the closest point on the patch, to the provided - // point p. As we are deali ng with latitude-longitude patches, distance in this - // context refers to great-circle distance. - // (https://en.wikipedia.org/wiki/Great-circle_distance) - // - // This uses a simple clamping approach to find the closest point on the - // patch. A naive castesian clamp is not sufficient for this purpose, - // as illustrated with an example below. +Geodetic2 GeodeticPatch::closestPoint(const Geodetic2& p) const { + // This method finds the closest point on the patch, to the provided + // point p. As we are deali ng with latitude-longitude patches, distance in this + // context refers to great-circle distance. + // (https://en.wikipedia.org/wiki/Great-circle_distance) + // + // This uses a simple clamping approach to find the closest point on the + // patch. A naive castesian clamp is not sufficient for this purpose, + // as illustrated with an example below. - // Example: (degrees are used for latidude, longitude) - // patchCenter = (0,0), patchHalfSize = (45,45), point = (5, 170) - // Note, the point and the patch are on opposite sides of the sphere - // - // cartesian clamp: - // --> clampedPointLat = clamp(5, -45, 45) = 5 - // --> clampedPointLon = clamp(170, -45, 45) = 45 - // --> result: (5, 45) - // --> closest point is actually (45, 45) - // --> The error is significant - // - // This method simply adds an extra clamp on the latitude in these cases. In the - // above example, that would be the following: - // --> clampedPointLat = clamp(180 - 5, -45, 45) = 45 - // - // Just doing this actually makes points returned from this methods being the - // true closest point, great-circle distance-wise. + // Example: (degrees are used for latidude, longitude) + // patchCenter = (0,0), patchHalfSize = (45,45), point = (5, 170) + // Note, the point and the patch are on opposite sides of the sphere + // + // cartesian clamp: + // --> clampedPointLat = clamp(5, -45, 45) = 5 + // --> clampedPointLon = clamp(170, -45, 45) = 45 + // --> result: (5, 45) + // --> closest point is actually (45, 45) + // --> The error is significant + // + // This method simply adds an extra clamp on the latitude in these cases. In the + // above example, that would be the following: + // --> clampedPointLat = clamp(180 - 5, -45, 45) = 45 + // + // Just doing this actually makes points returned from this methods being the + // true closest point, great-circle distance-wise. - using Ang = Angle; + using Ang = Angle; - // Convert to Angles for normalization - Ang centerLat = Ang::fromRadians(_center.lat); - Ang centerLon = Ang::fromRadians(_center.lon); - Ang pointLat = Ang::fromRadians(p.lat); - Ang pointLon = Ang::fromRadians(p.lon); + // Convert to Angles for normalization + Ang centerLat = Ang::fromRadians(_center.lat); + Ang centerLon = Ang::fromRadians(_center.lon); + Ang pointLat = Ang::fromRadians(p.lat); + Ang pointLon = Ang::fromRadians(p.lon); - // Normalize point with respect to center. This is done because the point - // will later be clamped. See LatLonPatch::clamp(const LatLon&) for explanation - pointLat.normalizeAround(centerLat); - pointLon.normalizeAround(centerLon); + // Normalize point with respect to center. This is done because the point + // will later be clamped. See LatLonPatch::clamp(const LatLon&) for explanation + pointLat.normalizeAround(centerLat); + pointLon.normalizeAround(centerLon); - // Calculate the longitud difference between center and point. We normalize around - // zero because we want the "shortest distance" difference, i.e the difference - // should be in the interval [-180 deg, 180 deg] - Ang centerToPointLon = (centerLon - pointLon).normalizeAround(Ang::ZERO); + // Calculate the longitud difference between center and point. We normalize around + // zero because we want the "shortest distance" difference, i.e the difference + // should be in the interval [-180 deg, 180 deg] + Ang centerToPointLon = (centerLon - pointLon).normalizeAround(Ang::ZERO); - // Calculate the longitudinal distance to the closest patch edge - Ang longitudeDistanceToClosestPatchEdge = centerToPointLon.abs() - Ang::fromRadians(_halfSize.lon); + // Calculate the longitudinal distance to the closest patch edge + Ang longitudeDistanceToClosestPatchEdge = centerToPointLon.abs() - Ang::fromRadians(_halfSize.lon); - // If the longitude distance to the closest patch edge is larger than 90 deg - // the latitude will have to be clamped to its closest corner, as explained in - // the example above. - Scalar clampedLat = longitudeDistanceToClosestPatchEdge > Ang::QUARTER ? - clampedLat = glm::clamp((Ang::HALF - pointLat).normalizeAround(centerLat).asRadians(), minLat(), maxLat()) : - clampedLat = glm::clamp(pointLat.asRadians(), minLat(), maxLat()); + // If the longitude distance to the closest patch edge is larger than 90 deg + // the latitude will have to be clamped to its closest corner, as explained in + // the example above. + double clampedLat = longitudeDistanceToClosestPatchEdge > Ang::QUARTER ? + clampedLat = glm::clamp((Ang::HALF - pointLat).normalizeAround(centerLat).asRadians(), minLat(), maxLat()) : + clampedLat = glm::clamp(pointLat.asRadians(), minLat(), maxLat()); - // Longitude is just clamped normally - Scalar clampedLon = glm::clamp(pointLon.asRadians(), minLon(), maxLon()); + // Longitude is just clamped normally + double clampedLon = glm::clamp(pointLon.asRadians(), minLon(), maxLon()); - return Geodetic2(clampedLat, clampedLon); - } + return Geodetic2(clampedLat, clampedLon); +} +} // namespace globebrowsing } // namespace openspace diff --git a/modules/globebrowsing/geometry/geodetic2.h b/modules/globebrowsing/geometry/geodetic2.h index 60e2fbca16..d9732077c7 100644 --- a/modules/globebrowsing/geometry/geodetic2.h +++ b/modules/globebrowsing/geometry/geodetic2.h @@ -22,81 +22,51 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __GEODETIC2_H__ -#define __GEODETIC2_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___GEODETIC2___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___GEODETIC2___H__ -#include -#include -#include -#include +#include -#define _USE_MATH_DEFINES -#include - -#include - -#include - - - - -// Using double precision -typedef double Scalar; -typedef glm::dvec2 Vec2; -typedef glm::dvec3 Vec3; +#include namespace openspace { +namespace globebrowsing { - // Forward declaration - class Ellipsoid; +class Ellipsoid; struct Geodetic2 { - Geodetic2(); - Geodetic2(Scalar latitude, Scalar longitude); + Geodetic2(double latitude = 0.0, double longitude = 0.0); Geodetic2(const Geodetic2& src); - - /* - static Geodetic2 fromCartesian(const Vec3& v); - Vec3 asUnitCartesian() const; - */ + //static Geodetic2 fromCartesian(const Vec3& v); + //Vec3 asUnitCartesian() const; - - - Vec2 toLonLatVec2() const; + glm::dvec2 toLonLatVec2() const; bool operator==(const Geodetic2& other) const; bool operator!=(const Geodetic2& other) const { return !(*this == (other)); } Geodetic2 operator+(const Geodetic2& other) const; Geodetic2 operator-(const Geodetic2& other) const; - Geodetic2 operator*(Scalar scalar) const; - Geodetic2 operator/(Scalar scalar) const; + Geodetic2 operator*(double scalar) const; + Geodetic2 operator/(double scalar) const; - Scalar lat; - Scalar lon; + double lat; + double lon; }; - - struct Geodetic3 { Geodetic2 geodetic2; - Scalar height; + double height; }; - - - -////////////////////////////////////////////////////////////////////////////////////// -// GEODETICPATCH // -////////////////////////////////////////////////////////////////////////////////////// class GeodeticPatch { public: GeodeticPatch( - Scalar centerLat, - Scalar centerLon, - Scalar halfSizeLat, - Scalar halfSizeLon); + double centerLat, + double centerLon, + double halfSizeLat, + double halfSizeLon); GeodeticPatch( const Geodetic2& center, @@ -104,8 +74,7 @@ public: GeodeticPatch(const GeodeticPatch& patch); - GeodeticPatch(const ChunkIndex& chunkIndex); - + GeodeticPatch(const TileIndex& tileIndex); void setCenter(const Geodetic2&); void setHalfSize(const Geodetic2&); @@ -113,19 +82,20 @@ public: /** returns the latitude boundary which is closest to the equator */ - Scalar edgeLatitudeNearestEquator() const; + double edgeLatitudeNearestEquator() const; /** Returns true if the center above the equator */ - Scalar isNorthern() const; + double isNorthern() const; Geodetic2 getCorner(Quad q) const; + Geodetic2 getSize() const; - Scalar minLat() const; - Scalar maxLat() const; - Scalar minLon() const; - Scalar maxLon() const; + double minLat() const; + double maxLat() const; + double minLon() const; + double maxLon() const; /** * returns true if the specified coordinate is contained within the patch @@ -152,12 +122,12 @@ public: /** * Returns the minimum tile level of the patch (based on largest side) */ - Scalar minimumTileLevel() const; + double minimumTileLevel() const; /** * Returns the maximum level of the patch (based on smallest side) */ - Scalar maximumTileLevel() const; + double maximumTileLevel() const; const Geodetic2& center() const; const Geodetic2& halfSize() const; @@ -168,6 +138,7 @@ private: Geodetic2 _halfSize; }; +} // namespace globebrowsing } // namespace openspace -#endif // __GEODETIC2_H__ +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___GEODETIC2___H__ diff --git a/modules/globebrowsing/globebrowsingmodule.cpp b/modules/globebrowsing/globebrowsingmodule.cpp index 7f511f938b..c251b976eb 100644 --- a/modules/globebrowsing/globebrowsingmodule.cpp +++ b/modules/globebrowsing/globebrowsingmodule.cpp @@ -26,6 +26,13 @@ #include #include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -33,38 +40,31 @@ #include #include -#include -#include -#include -#include -#include - - namespace openspace { - GlobeBrowsingModule::GlobeBrowsingModule() - : OpenSpaceModule("GlobeBrowsing") -{} +GlobeBrowsingModule::GlobeBrowsingModule() : OpenSpaceModule("GlobeBrowsing") {} void GlobeBrowsingModule::internalInitialize() { + using namespace globebrowsing; auto fRenderable = FactoryManager::ref().factory(); ghoul_assert(fRenderable, "Renderable factory was not created"); - fRenderable->registerClass("RenderableGlobe"); + fRenderable->registerClass("RenderableGlobe"); - void addFactory(std::unique_ptr factory); - // add Tile Provider factory - FactoryManager::ref().addFactory( - std::make_unique>()); + auto fTileProvider = std::make_unique>(); - auto fTileProvider = FactoryManager::ref().factory(); fTileProvider->registerClass("LRUCaching"); fTileProvider->registerClass("SingleImage"); fTileProvider->registerClass("Temporal"); - fTileProvider->registerClass("ChunkIndex"); + fTileProvider->registerClass("TileIndex"); fTileProvider->registerClass("SizeReference"); - + + // Combining Tile Providers + fTileProvider->registerClass("ByLevel"); + fTileProvider->registerClass("ByIndex"); + + FactoryManager::ref().addFactory(std::move(fTileProvider)); } } // namespace openspace diff --git a/modules/globebrowsing/globebrowsingmodule.h b/modules/globebrowsing/globebrowsingmodule.h index 95c0ef2039..9431aa8bce 100644 --- a/modules/globebrowsing/globebrowsingmodule.h +++ b/modules/globebrowsing/globebrowsingmodule.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __GLOBEBROWSING_H__ -#define __GLOBEBROWSING_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___GLOBEBROWSING___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___GLOBEBROWSING___H__ #include @@ -39,4 +39,4 @@ protected: } // namespace openspace -#endif // __GLOBEBROWSING_H__ +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___GLOBEBROWSING___H__ diff --git a/modules/globebrowsing/globes/chunkedlodglobe.cpp b/modules/globebrowsing/globes/chunkedlodglobe.cpp new file mode 100644 index 0000000000..296c69ebe1 --- /dev/null +++ b/modules/globebrowsing/globes/chunkedlodglobe.cpp @@ -0,0 +1,327 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include + +namespace openspace { +namespace globebrowsing { + +const TileIndex ChunkedLodGlobe::LEFT_HEMISPHERE_INDEX = TileIndex(0, 0, 1); +const TileIndex ChunkedLodGlobe::RIGHT_HEMISPHERE_INDEX = TileIndex(1, 0, 1); +const GeodeticPatch ChunkedLodGlobe::COVERAGE = GeodeticPatch(0, 0, 90, 180); + +ChunkedLodGlobe::ChunkedLodGlobe(const RenderableGlobe& owner, size_t segmentsPerPatch, + std::shared_ptr layerManager) + : _owner(owner) + , _leftRoot(std::make_unique(Chunk(owner, LEFT_HEMISPHERE_INDEX))) + , _rightRoot(std::make_unique(Chunk(owner, RIGHT_HEMISPHERE_INDEX))) + , minSplitDepth(2) + , maxSplitDepth(22) + , _layerManager(layerManager) + , stats(StatsCollector(absPath("test_stats"), 1, StatsCollector::Enabled::No)) +{ + auto geometry = std::make_shared( + static_cast(segmentsPerPatch), + static_cast(segmentsPerPatch), + TriangleSoup::Positions::No, + TriangleSoup::TextureCoordinates::Yes, + TriangleSoup::Normals::No + ); + + _chunkCullers.push_back(std::make_unique()); + _chunkCullers.push_back(std::make_unique( + AABB3(glm::vec3(-1, -1, 0), glm::vec3(1, 1, 1e35))) + ); + + _chunkEvaluatorByAvailableTiles = + std::make_unique(); + _chunkEvaluatorByProjectedArea = + std::make_unique(); + _chunkEvaluatorByDistance = + std::make_unique(); + + _renderer = std::make_unique(geometry, layerManager); +} + +// The destructor is defined here to make it feasiable to use a unique_ptr +// with a forward declaration +ChunkedLodGlobe::~ChunkedLodGlobe() {} + +bool ChunkedLodGlobe::initialize() { + return true; +} + +bool ChunkedLodGlobe::deinitialize() { + return true; +} + +bool ChunkedLodGlobe::isReady() const { + return true; +} + +std::shared_ptr ChunkedLodGlobe::layerManager() const { + return _layerManager; +} + +bool ChunkedLodGlobe::testIfCullable(const Chunk& chunk, + const RenderData& renderData) const +{ + if (_owner.debugProperties().performHorizonCulling && + _chunkCullers[0]->isCullable(chunk, renderData)) { + return true; + } + if (_owner.debugProperties().performFrustumCulling && + _chunkCullers[1]->isCullable(chunk, renderData)) { + return true; + } + return false; +} + +const ChunkNode& ChunkedLodGlobe::findChunkNode(const Geodetic2& p) const { + ghoul_assert(COVERAGE.contains(p), + "Point must be in lat [-90, 90] and lon [-180, 180]"); + + return p.lon < COVERAGE.center().lon ? _leftRoot->find(p) : _rightRoot->find(p); +} + +int ChunkedLodGlobe::getDesiredLevel( + const Chunk& chunk, const RenderData& renderData) const { + int desiredLevel = 0; + if (_owner.debugProperties().levelByProjectedAreaElseDistance) { + desiredLevel = _chunkEvaluatorByProjectedArea->getDesiredLevel(chunk, renderData); + } + else { + desiredLevel = _chunkEvaluatorByDistance->getDesiredLevel(chunk, renderData); + } + + int desiredLevelByAvailableData = _chunkEvaluatorByAvailableTiles->getDesiredLevel( + chunk, renderData + ); + if (desiredLevelByAvailableData != ChunkLevelEvaluator::UNKNOWN_DESIRED_LEVEL) { + desiredLevel = glm::min(desiredLevel, desiredLevelByAvailableData); + } + + desiredLevel = glm::clamp(desiredLevel, minSplitDepth, maxSplitDepth); + return desiredLevel; +} + +float ChunkedLodGlobe::getHeight(glm::dvec3 position) const { + float height = 0; + + // Get the uv coordinates to sample from + Geodetic2 geodeticPosition = _owner.ellipsoid().cartesianToGeodetic2(position); + int chunkLevel = findChunkNode(geodeticPosition).getChunk().tileIndex().level; + + TileIndex tileIndex = TileIndex(geodeticPosition, chunkLevel); + GeodeticPatch patch = GeodeticPatch(tileIndex); + + Geodetic2 geoDiffPatch = + patch.getCorner(Quad::NORTH_EAST) - patch.getCorner(Quad::SOUTH_WEST); + + Geodetic2 geoDiffPoint = geodeticPosition - patch.getCorner(Quad::SOUTH_WEST); + glm::vec2 patchUV = glm::vec2( + geoDiffPoint.lon / geoDiffPatch.lon, + geoDiffPoint.lat / geoDiffPatch.lat + ); + + // Get the tile providers for the height maps + const auto& heightMapLayers = _layerManager->layerGroup(LayerManager::HeightLayers).activeLayers(); + + for (const auto& layer : heightMapLayers) { + TileProvider* tileProvider = layer->tileProvider(); + // Transform the uv coordinates to the current tile texture + ChunkTile chunkTile = tileProvider->getChunkTile(tileIndex); + const auto& tile = chunkTile.tile; + const auto& uvTransform = chunkTile.uvTransform; + const auto& depthTransform = tileProvider->depthTransform(); + if (tile.status != Tile::Status::OK) { + return 0; + } + + glm::vec2 transformedUv = Tile::TileUvToTextureSamplePosition( + uvTransform, + patchUV, + glm::uvec2(tile.texture->dimensions()) + ); + + // Sample and do linear interpolation + // (could possibly be moved as a function in ghoul texture) + // Suggestion: a function in ghoul::opengl::Texture that takes uv coordinates + // in range [0,1] and uses the set interpolation method and clamping. + + glm::uvec3 dimensions = tile.texture->dimensions(); + + glm::vec2 samplePos = transformedUv * glm::vec2(dimensions); + glm::uvec2 samplePos00 = samplePos; + samplePos00 = glm::clamp( + samplePos00, + glm::uvec2(0, 0), + glm::uvec2(dimensions) - glm::uvec2(1) + ); + glm::vec2 samplePosFract = samplePos - glm::vec2(samplePos00); + + glm::uvec2 samplePos10 = glm::min( + samplePos00 + glm::uvec2(1, 0), + glm::uvec2(dimensions) - glm::uvec2(1) + ); + glm::uvec2 samplePos01 = glm::min( + samplePos00 + glm::uvec2(0, 1), + glm::uvec2(dimensions) - glm::uvec2(1) + ); + glm::uvec2 samplePos11 = glm::min( + samplePos00 + glm::uvec2(1, 1), + glm::uvec2(dimensions) - glm::uvec2(1) + ); + + float sample00 = tile.texture->texelAsFloat(samplePos00).x; + float sample10 = tile.texture->texelAsFloat(samplePos10).x; + float sample01 = tile.texture->texelAsFloat(samplePos01).x; + float sample11 = tile.texture->texelAsFloat(samplePos11).x; + + // In case the texture has NaN or no data values don't use this height map. + bool anySampleIsNaN = + std::isnan(sample00) || + std::isnan(sample01) || + std::isnan(sample10) || + std::isnan(sample11); + + bool anySampleIsNoData = + sample00 == tileProvider->noDataValueAsFloat() || + sample01 == tileProvider->noDataValueAsFloat() || + sample10 == tileProvider->noDataValueAsFloat() || + sample11 == tileProvider->noDataValueAsFloat(); + + if (anySampleIsNaN || anySampleIsNoData) { + continue; + } + + float sample0 = sample00 * (1.0 - samplePosFract.x) + sample10 * samplePosFract.x; + float sample1 = sample01 * (1.0 - samplePosFract.x) + sample11 * samplePosFract.x; + + float sample = sample0 * (1.0 - samplePosFract.y) + sample1 * samplePosFract.y; + + // Perform depth transform to get the value in meters + height = depthTransform.depthOffset + depthTransform.depthScale * sample; + } + // Return the result + return height; +} + +void ChunkedLodGlobe::render(const RenderData& data) { + stats.startNewRecord(); + + auto duration = std::chrono::system_clock::now().time_since_epoch(); + auto millis = std::chrono::duration_cast(duration).count(); + stats.i["time"] = millis; + + _leftRoot->updateChunkTree(data); + _rightRoot->updateChunkTree(data); + + // Calculate the MVP matrix + glm::dmat4 viewTransform = glm::dmat4(data.camera.combinedViewMatrix()); + glm::dmat4 vp = glm::dmat4(data.camera.projectionMatrix()) * viewTransform; + glm::dmat4 mvp = vp * _owner.modelTransform(); + + // Render function + auto renderJob = [this, &data, &mvp](const ChunkNode& chunkNode) { + stats.i["chunks nodes"]++; + const Chunk& chunk = chunkNode.getChunk(); + if (chunkNode.isLeaf()) { + stats.i["leafs chunk nodes"]++; + if (chunk.isVisible()) { + stats.i["rendered chunks"]++; + double t0 = Time::now().j2000Seconds(); + _renderer->renderChunk(chunkNode.getChunk(), data); + debugRenderChunk(chunk, mvp); + } + } + }; + + _leftRoot->breadthFirst(renderJob); + _rightRoot->breadthFirst(renderJob); + + //_leftRoot->reverseBreadthFirst(renderJob); + //_rightRoot->reverseBreadthFirst(renderJob); + + auto duration2 = std::chrono::system_clock::now().time_since_epoch(); + auto millis2 = std::chrono::duration_cast(duration2).count(); + stats.i["chunk globe render time"] = millis2 - millis; +} + +void ChunkedLodGlobe::debugRenderChunk(const Chunk& chunk, const glm::dmat4& mvp) const { + if (_owner.debugProperties().showChunkBounds || + _owner.debugProperties().showChunkAABB) + { + const std::vector modelSpaceCorners = + chunk.getBoundingPolyhedronCorners(); + std::vector clippingSpaceCorners(8); + AABB3 screenSpaceBounds; + + for (size_t i = 0; i < 8; ++i) { + const glm::vec4& clippingSpaceCorner = mvp * modelSpaceCorners[i]; + clippingSpaceCorners[i] = clippingSpaceCorner; + + glm::vec3 screenSpaceCorner = + (1.0f / clippingSpaceCorner.w) * clippingSpaceCorner; + screenSpaceBounds.expand(screenSpaceCorner); + } + + unsigned int colorBits = 1 + chunk.tileIndex().level % 6; + glm::vec4 color = glm::vec4(colorBits & 1, colorBits & 2, colorBits & 4, 0.3); + + if (_owner.debugProperties().showChunkBounds) { + DebugRenderer::ref().renderNiceBox(clippingSpaceCorners, color); + } + + if (_owner.debugProperties().showChunkAABB) { + auto& screenSpacePoints = + DebugRenderer::ref().verticesFor(screenSpaceBounds); + DebugRenderer::ref().renderNiceBox(screenSpacePoints, color); + } + } +} + +void ChunkedLodGlobe::update(const UpdateData& data) { + _renderer->update(); +} + +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/globes/chunkedlodglobe.h b/modules/globebrowsing/globes/chunkedlodglobe.h new file mode 100644 index 0000000000..74a820f921 --- /dev/null +++ b/modules/globebrowsing/globes/chunkedlodglobe.h @@ -0,0 +1,140 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___CHUNKED_LOD_GLOBE___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___CHUNKED_LOD_GLOBE___H__ + +#include + +#include +#include + +#include + +namespace openspace { +namespace globebrowsing { + +class Chunk; +class ChunkCuller; +class ChunkLevelEvaluator; +class ChunkNode; +class ChunkRenderer; +class Geodetic2; +class LayerManager; +class RenderableGlobe; + +class ChunkedLodGlobe : public Renderable { +public: + ChunkedLodGlobe(const RenderableGlobe& owner, size_t segmentsPerPatch, + std::shared_ptr layerManager); + ~ChunkedLodGlobe(); + + bool initialize() override; + bool deinitialize() override; + bool isReady() const override; + + void render(const RenderData& data) override; + void update(const UpdateData& data) override; + + /** + * Traverse the chunk tree and find the highest level chunk node. + * + * \param location is given in geodetic coordinates and must be in the range + * latitude [-90. 90] and longitude [-180, 180]. In other words, it must be a + * position defined on the globe in georeferenced coordinates. + */ + const ChunkNode& findChunkNode(const Geodetic2& location) const; + + /** + * Test if a specific chunk can saefely be culled without affecting the rendered + * image. + * + * Goes through all available ChunkCullers and check if any of them + * allows culling of the Chunks in question. + */ + bool testIfCullable(const Chunk& chunk, const RenderData& renderData) const; + + /** + * Gets the desired level which can be used to determine if a chunk should split + * or merge. + * + * Using ChunkLevelEvaluators, the desired level can be higher or + * lower than the current level of the Chunkss + * TileIndex. If the desired level is higher than that of the + * Chunk, it wants to split. If it is lower, it wants to merge with + * its siblings. + */ + int getDesiredLevel(const Chunk& chunk, const RenderData& renderData) const; + + /** + * Calculates the height from the surface of the reference ellipsoid to the + * heigh mapped surface. + * + * The height can be negative if the height map contains negative values. + * + * \param position is the position of a point that gets geodetically + * projected on the reference ellipsoid. position must be in + * cartesian model space. + * \returns the height from the reference ellipsoid to the globe surface. + */ + float getHeight(glm::dvec3 position) const; + + const int minSplitDepth; + const int maxSplitDepth; + + std::shared_ptr layerManager() const; + + StatsCollector stats; + +private: + void debugRenderChunk(const Chunk& chunk, const glm::dmat4& data) const; + + static const GeodeticPatch COVERAGE; + static const TileIndex LEFT_HEMISPHERE_INDEX; + static const TileIndex RIGHT_HEMISPHERE_INDEX; + + // Covers all negative longitudes + std::unique_ptr _leftRoot; + + // Covers all positive longitudes + std::unique_ptr _rightRoot; + + // the patch used for actual rendering + std::unique_ptr _renderer; + + std::vector> _chunkCullers; + + std::unique_ptr _chunkEvaluatorByAvailableTiles; + std::unique_ptr _chunkEvaluatorByProjectedArea; + std::unique_ptr _chunkEvaluatorByDistance; + + std::shared_ptr _layerManager; + + const RenderableGlobe& _owner; +}; + +} // namespace globebrowsing +} // namespace openspace + +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___CHUNKED_LOD_GLOBE___H__ diff --git a/modules/globebrowsing/globes/pointglobe.cpp b/modules/globebrowsing/globes/pointglobe.cpp new file mode 100644 index 0000000000..5e47fdede8 --- /dev/null +++ b/modules/globebrowsing/globes/pointglobe.cpp @@ -0,0 +1,123 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include +#include + +namespace openspace { +namespace globebrowsing { + +PointGlobe::PointGlobe(const RenderableGlobe& owner) + : _owner(owner) +{} + +PointGlobe::~PointGlobe() { + glDeleteBuffers(1, &_vertexBufferID); + glDeleteVertexArrays(1, &_vaoID); +} + +bool PointGlobe::initialize() { + _programObject = OsEng.renderEngine().buildRenderProgram( + "PointGlobe", + "${MODULE_GLOBEBROWSING}/shaders/pointglobe_vs.glsl", + "${MODULE_GLOBEBROWSING}/shaders/pointglobe_fs.glsl"); + + glGenVertexArrays(1, &_vaoID); + glGenBuffers(1, &_vertexBufferID); + + glBindVertexArray(_vaoID); + + // Vertex data is only one point in the origin + glm::vec3 data = glm::vec3(0,0,0); + + // Vertex buffer + glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferID); + glBufferData( + GL_ARRAY_BUFFER, + sizeof(glm::vec3), + &data, + GL_STATIC_DRAW + ); + + // Position at location 0 + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), 0); + + glBindVertexArray(0); + + return isReady(); +} + +bool PointGlobe::deinitialize() { + return true; +} + +bool PointGlobe::isReady() const { + return (_vaoID != 0) && (_vertexBufferID != 0); +} + +void PointGlobe::render(const RenderData& data) { + _programObject->activate(); + + // Calculate variables to be used as uniform variables in shader + glm::dvec3 bodyPosition = data.modelTransform.translation; + + // Model transform and view transform needs to be in double precision + glm::dmat4 modelTransform = + glm::translate(glm::dmat4(1.0), bodyPosition) * // Translation + glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)); // Scale + glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() * modelTransform; + glm::vec3 directionToSun = glm::normalize(glm::vec3(0) - glm::vec3(bodyPosition)); + glm::vec3 directionToSunViewSpace = glm::mat3(data.camera.combinedViewMatrix()) * directionToSun; + + int windowWidth = OsEng.windowWrapper().currentWindowSize().x; + float avgRadius = _owner.ellipsoid().averageRadius(); + + _programObject->setUniform("windowWidth", windowWidth); + _programObject->setUniform("globeRadius", avgRadius); + _programObject->setUniform("directionToSunViewSpace", directionToSunViewSpace); + _programObject->setUniform("modelViewTransform", glm::mat4(modelViewTransform)); + _programObject->setUniform("projectionTransform", data.camera.projectionMatrix()); + + glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); + + glBindVertexArray(_vaoID); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _vertexBufferID); + glDrawArrays(GL_POINTS, 0, 1); + glBindVertexArray(0); + + glDisable(GL_VERTEX_PROGRAM_POINT_SIZE); + + _programObject->deactivate(); +} + +void PointGlobe::update(const UpdateData& data) {} + +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/globes/pointglobe.h b/modules/globebrowsing/globes/pointglobe.h new file mode 100644 index 0000000000..a377ad27e2 --- /dev/null +++ b/modules/globebrowsing/globes/pointglobe.h @@ -0,0 +1,62 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___POINTGLOBE___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___POINTGLOBE___H__ + +#include + +namespace ghoul { namespace opengl { +class ProgramObject; +}} + +namespace openspace { +namespace globebrowsing { + +class RenderableGlobe; + +class PointGlobe : public Renderable { +public: + PointGlobe(const RenderableGlobe& owner); + virtual ~PointGlobe(); + + bool initialize() override; + bool deinitialize() override; + bool isReady() const override; + + void render(const RenderData& data) override; + void update(const UpdateData& data) override; + +private: + const RenderableGlobe& _owner; + std::unique_ptr _programObject; + + GLuint _vertexBufferID; + GLuint _vaoID; +}; + +} // namespace globebrowsing +} // namespace openspace + +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___POINTGLOBE___H__ diff --git a/modules/globebrowsing/globes/renderableglobe.cpp b/modules/globebrowsing/globes/renderableglobe.cpp index 52b5f012b0..3441fc86fa 100644 --- a/modules/globebrowsing/globes/renderableglobe.cpp +++ b/modules/globebrowsing/globes/renderableglobe.cpp @@ -1,281 +1,250 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ #include - -#include -#include - -#include -#include - -// open space includes -#include -#include -#include -#include - -// ghoul includes -#include - + +#include +#include +#include namespace { - const std::string _loggerCat = "RenderableGlobe"; - - // Keys for the dictionary - const std::string keyFrame = "Frame"; - const std::string keyRadii = "Radii"; - const std::string keyInteractionDepthBelowEllipsoid = "InteractionDepthBelowEllipsoid"; - const std::string keyCameraMinHeight = "CameraMinHeight"; - const std::string keySegmentsPerPatch = "SegmentsPerPatch"; - const std::string keyTextureInitData = "TextureInitData"; - const std::string keyTextures = "Textures"; - const std::string keyColorTextures = "ColorTextures"; - const std::string keyHeightMaps = "HeightMaps"; + const char* keyFrame = "Frame"; + const char* keyRadii = "Radii"; + const char* keyInteractionDepthBelowEllipsoid = "InteractionDepthBelowEllipsoid"; + const char* keyCameraMinHeight = "CameraMinHeight"; + const char* keySegmentsPerPatch = "SegmentsPerPatch"; + const char* keyLayers = "Layers"; } - - namespace openspace { +using namespace properties; - RenderableGlobe::RenderableGlobe(const ghoul::Dictionary& dictionary) - : _isEnabled(properties::BoolProperty("Enabled", "Enabled", true)) - , _toggleEnabledEveryFrame(properties::BoolProperty("Toggle enabled every frame", "Toggle enabled every frame", false)) - , _saveOrThrowCamera(properties::BoolProperty("saveOrThrowCamera", "saveOrThrowCamera")) - , _resetTileProviders(properties::BoolProperty("resetTileProviders", "resetTileProviders")) - , _cameraMinHeight(properties::FloatProperty("cameraMinHeight", "cameraMinHeight", 100.0f, 0.0f, 1000.0f)) - , lodScaleFactor(properties::FloatProperty("lodScaleFactor", "lodScaleFactor", 10.0f, 1.0f, 50.0f)) - , debugSelection(ReferencedBoolSelection("Debug", "Debug")) - , atmosphereEnabled(properties::BoolProperty("Atmosphere", "Atmosphere", false)) - { - setName("RenderableGlobe"); +namespace globebrowsing { + +RenderableGlobe::RenderableGlobe(const ghoul::Dictionary& dictionary) + : _generalProperties({ + BoolProperty("enabled", "Enabled", true), + BoolProperty("performShading", "perform shading", true), + BoolProperty("atmosphere", "atmosphere", false), + FloatProperty("lodScaleFactor", "lodScaleFactor",10.0f, 1.0f, 50.0f), + FloatProperty("cameraMinHeight", "cameraMinHeight", 100.0f, 0.0f, 1000.0f) + }) + , _debugProperties({ + BoolProperty("saveOrThrowCamera", "save or throw camera", false), + BoolProperty("showChunkEdges", "show chunk edges", false), + BoolProperty("showChunkBounds", "show chunk bounds", false), + BoolProperty("showChunkAABB", "show chunk AABB", false), + BoolProperty("showHeightResolution", "show height resolution", false), + BoolProperty("showHeightIntensities", "show height intensities", false), + BoolProperty("performFrustumCulling", "perform frustum culling", true), + BoolProperty("performHorizonCulling", "perform horizon culling", true), + BoolProperty("levelByProjectedAreaElseDistance", "level by projected area (else distance)",false), + BoolProperty("resetTileProviders", "reset tile providers", false), + BoolProperty("toggleEnabledEveryFrame", "toggle enabled every frame", false), + BoolProperty("collectStats", "collect stats", false), + BoolProperty("onlyModelSpaceRendering", "Only Model Space Rendering", false) + }) +{ + setName("RenderableGlobe"); - dictionary.getValue(keyFrame, _frame); + dictionary.getValue(keyFrame, _frame); - // Read the radii in to its own dictionary - Vec3 radii; - dictionary.getValue(keyRadii, radii); - _ellipsoid = Ellipsoid(radii); - setBoundingSphere(pss(_ellipsoid.averageRadius(), 0.0)); + // Read the radii in to its own dictionary + glm::dvec3 radii; + dictionary.getValue(keyRadii, radii); + _ellipsoid = Ellipsoid(radii); + setBoundingSphere(pss(_ellipsoid.averageRadius(), 0.0)); - // Ghoul can't read ints from lua dictionaries - double patchSegmentsd; - dictionary.getValue(keySegmentsPerPatch, patchSegmentsd); - int patchSegments = patchSegmentsd; + // Ghoul can't read ints from lua dictionaries... + double patchSegmentsd; + dictionary.getValue(keySegmentsPerPatch, patchSegmentsd); + int patchSegments = patchSegmentsd; - dictionary.getValue(keyInteractionDepthBelowEllipsoid, _interactionDepthBelowEllipsoid); - float cameraMinHeight; - dictionary.getValue(keyCameraMinHeight, cameraMinHeight); - _cameraMinHeight.set(cameraMinHeight); + dictionary.getValue(keyInteractionDepthBelowEllipsoid, + _interactionDepthBelowEllipsoid); + float cameraMinHeight; + dictionary.getValue(keyCameraMinHeight, cameraMinHeight); + _generalProperties.cameraMinHeight.set(cameraMinHeight); - // Init tile provider manager - ghoul::Dictionary textureInitDataDictionary; - ghoul::Dictionary texturesDictionary; - dictionary.getValue(keyTextureInitData, textureInitDataDictionary); - dictionary.getValue(keyTextures, texturesDictionary); + // Init layer manager + ghoul::Dictionary layersDictionary; + if (!dictionary.getValue(keyLayers, layersDictionary)) + throw ghoul::RuntimeError(std::string(keyLayers) + " must be specified specified!"); - _tileProviderManager = std::make_shared( - texturesDictionary, textureInitDataDictionary); + _layerManager = std::make_shared(layersDictionary); - _chunkedLodGlobe = std::make_shared( - _ellipsoid, patchSegments, _tileProviderManager); - _distanceSwitch.addSwitchValue(_chunkedLodGlobe, 1e12); + _chunkedLodGlobe = std::make_shared( + *this, patchSegments, _layerManager); + + // This distance will be enough to render the globe as one pixel if the field of + // view is 'fov' radians and the screen resolution is 'res' pixels. + double fov = 2 * glm::pi() / 6; // 60 degrees + int res = 2880; + double distance = res * _ellipsoid.maximumRadius() / tan(fov / 2); + _distanceSwitch.addSwitchValue(_chunkedLodGlobe, distance); + + _debugPropertyOwner.setName("Debug"); + _texturePropertyOwner.setName("Textures"); - addProperty(_isEnabled); - addProperty(_toggleEnabledEveryFrame); + addProperty(_generalProperties.isEnabled); + addProperty(_generalProperties.atmosphereEnabled); + addProperty(_generalProperties.performShading); + addProperty(_generalProperties.lodScaleFactor); + addProperty(_generalProperties.cameraMinHeight); + + _debugPropertyOwner.addProperty(_debugProperties.saveOrThrowCamera); + _debugPropertyOwner.addProperty(_debugProperties.showChunkEdges); + _debugPropertyOwner.addProperty(_debugProperties.showChunkBounds); + _debugPropertyOwner.addProperty(_debugProperties.showChunkAABB); + _debugPropertyOwner.addProperty(_debugProperties.showHeightResolution); + _debugPropertyOwner.addProperty(_debugProperties.showHeightIntensities); + _debugPropertyOwner.addProperty(_debugProperties.performFrustumCulling); + _debugPropertyOwner.addProperty(_debugProperties.performHorizonCulling); + _debugPropertyOwner.addProperty( + _debugProperties.levelByProjectedAreaElseDistance + ); + _debugPropertyOwner.addProperty(_debugProperties.resetTileProviders); + _debugPropertyOwner.addProperty(_debugProperties.toggleEnabledEveryFrame); + _debugPropertyOwner.addProperty(_debugProperties.collectStats); + _debugPropertyOwner.addProperty(_debugProperties.onlyModelSpaceRendering); + + addPropertySubOwner(_debugPropertyOwner); + addPropertySubOwner(_layerManager.get()); +} +bool RenderableGlobe::initialize() { + return _distanceSwitch.initialize(); +} - // Add debug options - must be after chunkedLodGlobe has been created as it - // references its members - addProperty(debugSelection); - debugSelection.addOption("Show chunk edges", &_chunkedLodGlobe->debugOptions.showChunkEdges); - debugSelection.addOption("Show chunk bounds", &_chunkedLodGlobe->debugOptions.showChunkBounds); - debugSelection.addOption("Show chunk AABB", &_chunkedLodGlobe->debugOptions.showChunkAABB); - debugSelection.addOption("Show height resolution", &_chunkedLodGlobe->debugOptions.showHeightResolution); - debugSelection.addOption("Show height intensities", &_chunkedLodGlobe->debugOptions.showHeightIntensities); +bool RenderableGlobe::deinitialize() { + return _distanceSwitch.deinitialize(); +} - debugSelection.addOption("Culling: Frustum", &_chunkedLodGlobe->debugOptions.doFrustumCulling); - debugSelection.addOption("Culling: Horizon", &_chunkedLodGlobe->debugOptions.doHorizonCulling); +bool RenderableGlobe::isReady() const { + return true; +} - debugSelection.addOption("Level by proj area (else distance)", &_chunkedLodGlobe->debugOptions.levelByProjAreaElseDistance); +void RenderableGlobe::render(const RenderData& data) { + bool statsEnabled = _debugProperties.collectStats.value(); + _chunkedLodGlobe->stats.setEnabled(statsEnabled); - // Add all tile layers as being toggleable for each category - for (int i = 0; i < LayeredTextures::NUM_TEXTURE_CATEGORIES; i++){ - LayeredTextures::TextureCategory category = (LayeredTextures::TextureCategory) i; - std::string categoryName = LayeredTextures::TEXTURE_CATEGORY_NAMES[i]; - auto selection = std::make_unique(categoryName, categoryName); - - auto& categoryProviders = _tileProviderManager->getTileProviderGroup(category); - for (auto& provider : categoryProviders.tileProviders) { - selection->addOption(provider.name, &provider.isActive); + if (_debugProperties.toggleEnabledEveryFrame.value()) { + _generalProperties.isEnabled.setValue( + !_generalProperties.isEnabled.value() + ); + } + if (_generalProperties.isEnabled.value()) { + if (_debugProperties.saveOrThrowCamera.value()) { + _debugProperties.saveOrThrowCamera.setValue(false); + + if (savedCamera() == nullptr) { // save camera + setSaveCamera(std::make_shared(data.camera)); } - selection->addOption(" - Blend tile levels - ", &_tileProviderManager->getTileProviderGroup(i).levelBlendingEnabled); - - addProperty(selection.get()); - _categorySelections.push_back(std::move(selection)); - } - - addProperty(atmosphereEnabled); - addProperty(_saveOrThrowCamera); - addProperty(_resetTileProviders); - addProperty(lodScaleFactor); - addProperty(_cameraMinHeight); - } - - RenderableGlobe::~RenderableGlobe() { - - } - - bool RenderableGlobe::initialize() { - for (auto& selection : _categorySelections) { - selection->initialize(); - } - debugSelection.initialize(); - - return _distanceSwitch.initialize(); - } - - bool RenderableGlobe::deinitialize() { - return _distanceSwitch.deinitialize(); - } - - bool RenderableGlobe::isReady() const { - return _distanceSwitch.isReady(); - } - - void RenderableGlobe::render(const RenderData& data) { - if (_toggleEnabledEveryFrame.value()) { - _isEnabled.setValue(!_isEnabled.value()); - } - if (_isEnabled.value()) { - if (_saveOrThrowCamera.value()) { - _saveOrThrowCamera.setValue(false); - - if (_chunkedLodGlobe->getSavedCamera() == nullptr) { // save camera - LDEBUG("Saving snapshot of camera!"); - _chunkedLodGlobe->setSaveCamera(std::make_shared(data.camera)); - } - else { // throw camera - LDEBUG("Throwing away saved camera!"); - _chunkedLodGlobe->setSaveCamera(nullptr); - } + else { // throw camera + setSaveCamera(nullptr); } - _distanceSwitch.render(data); } + _distanceSwitch.render(data); } - - void RenderableGlobe::update(const UpdateData& data) { - _time = data.time; - _distanceSwitch.update(data); - - _chunkedLodGlobe->lodScaleFactor = lodScaleFactor.value(); - _chunkedLodGlobe->atmosphereEnabled = atmosphereEnabled.value(); - - if (_resetTileProviders) { - _tileProviderManager->reset(); - _resetTileProviders = false; - } - _tileProviderManager->update(); - _chunkedLodGlobe->update(data); + if (_savedCamera != nullptr) { + DebugRenderer::ref().renderCameraFrustum(data, *_savedCamera); } +} - glm::dvec3 RenderableGlobe::projectOnEllipsoid(glm::dvec3 position) { - return _ellipsoid.geodeticSurfaceProjection(position); +void RenderableGlobe::update(const UpdateData& data) { + _time = data.time; + _distanceSwitch.update(data); + + glm::dmat4 translation = + glm::translate(glm::dmat4(1.0), data.modelTransform.translation); + glm::dmat4 rotation = glm::dmat4(data.modelTransform.rotation); + glm::dmat4 scaling = + glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale, + data.modelTransform.scale, data.modelTransform.scale)); + + _cachedModelTransform = translation * rotation * scaling; + _cachedInverseModelTransform = glm::inverse(_cachedModelTransform); + + if (_debugProperties.resetTileProviders) { + _layerManager->reset(); + _debugProperties.resetTileProviders = false; } + _layerManager->update(); + _chunkedLodGlobe->update(data); +} - const Ellipsoid& RenderableGlobe::ellipsoid() { - return _ellipsoid; +glm::dvec3 RenderableGlobe::projectOnEllipsoid(glm::dvec3 position) { + return _ellipsoid.geodeticSurfaceProjection(position); +} + +float RenderableGlobe::getHeight(glm::dvec3 position) { + if (_chunkedLodGlobe) { + return _chunkedLodGlobe->getHeight(position); } - - float RenderableGlobe::getHeight(glm::dvec3 position) { - // Get the tile provider for the height map - const auto& heightMapProviders = _tileProviderManager->getTileProviderGroup(LayeredTextures::HeightMaps).getActiveTileProviders(); - if (heightMapProviders.size() == 0) - return 0; - const auto& tileProvider = heightMapProviders[0]; - - // Get the uv coordinates to sample from - Geodetic2 geodeticPosition = _ellipsoid.cartesianToGeodetic2(position); - int chunkLevel = _chunkedLodGlobe->findChunkNode(geodeticPosition).getChunk().index().level; - - ChunkIndex chunkIdx = ChunkIndex(geodeticPosition, chunkLevel); - GeodeticPatch patch = GeodeticPatch(chunkIdx); - Geodetic2 geoDiffPatch = patch.getCorner(Quad::NORTH_EAST) - patch.getCorner(Quad::SOUTH_WEST); - Geodetic2 geoDiffPoint = geodeticPosition - patch.getCorner(Quad::SOUTH_WEST); - glm::vec2 patchUV = glm::vec2(geoDiffPoint.lon / geoDiffPatch.lon, geoDiffPoint.lat / geoDiffPatch.lat); - - // Transform the uv coordinates to the current tile texture - TileAndTransform tileAndTransform = TileSelector::getHighestResolutionTile(tileProvider.get(), chunkIdx); - const auto& tile = tileAndTransform.tile; - const auto& uvTransform = tileAndTransform.uvTransform; - const auto& depthTransform = tileProvider->depthTransform(); - if (tile.status != Tile::Status::OK) { - return 0; - } - glm::vec2 transformedUv = uvTransform.uvOffset + uvTransform.uvScale * patchUV; - - // Sample and do linear interpolation (could possibly be moved as a function in ghoul texture) - glm::uvec3 dimensions = tile.texture->dimensions(); - - glm::vec2 samplePos = transformedUv * glm::vec2(dimensions); - glm::uvec2 samplePos00 = samplePos; - samplePos00 = glm::clamp(samplePos00, glm::uvec2(0, 0), glm::uvec2(dimensions) - glm::uvec2(1)); - glm::vec2 samplePosFract = samplePos - glm::vec2(samplePos00); - - glm::uvec2 samplePos10 = glm::min(samplePos00 + glm::uvec2(1, 0), glm::uvec2(dimensions) - glm::uvec2(1)); - glm::uvec2 samplePos01 = glm::min(samplePos00 + glm::uvec2(0, 1), glm::uvec2(dimensions) - glm::uvec2(1)); - glm::uvec2 samplePos11 = glm::min(samplePos00 + glm::uvec2(1, 1), glm::uvec2(dimensions) - glm::uvec2(1)); - - float sample00 = tile.texture->texelAsFloat(samplePos00).x; - float sample10 = tile.texture->texelAsFloat(samplePos10).x; - float sample01 = tile.texture->texelAsFloat(samplePos01).x; - float sample11 = tile.texture->texelAsFloat(samplePos11).x; - - float sample0 = sample00 * (1.0 - samplePosFract.x) + sample10 * samplePosFract.x; - float sample1 = sample01 * (1.0 - samplePosFract.x) + sample11 * samplePosFract.x; - - float sample = sample0 * (1.0 - samplePosFract.y) + sample1 * samplePosFract.y; - - // Perform depth transform to get the value in meters - float height = depthTransform.depthOffset + depthTransform.depthScale * sample; - - // Return the result - return height; + else { + return 0; } +} - double RenderableGlobe::interactionDepthBelowEllipsoid() { - return _interactionDepthBelowEllipsoid; - } +std::shared_ptr RenderableGlobe::chunkedLodGlobe() const{ + return _chunkedLodGlobe; +} - float RenderableGlobe::cameraMinHeight() { - return _cameraMinHeight.value(); - } +const Ellipsoid& RenderableGlobe::ellipsoid() const{ + return _ellipsoid; +} - std::shared_ptr RenderableGlobe::chunkedLodGlobe() { - return _chunkedLodGlobe; - } +const glm::dmat4& RenderableGlobe::modelTransform() const{ + return _cachedModelTransform; +} -} // namespace openspace +const glm::dmat4& RenderableGlobe::inverseModelTransform() const{ + return _cachedInverseModelTransform; +} +const RenderableGlobe::DebugProperties& + RenderableGlobe::debugProperties() const{ + return _debugProperties; +} + +const RenderableGlobe::GeneralProperties& + RenderableGlobe::generalProperties() const{ + return _generalProperties; +} + +const std::shared_ptr RenderableGlobe::savedCamera() const { + return _savedCamera; +} + +double RenderableGlobe::interactionDepthBelowEllipsoid() { + return _interactionDepthBelowEllipsoid; +} + +void RenderableGlobe::setSaveCamera(std::shared_ptr camera) { + _savedCamera = camera; +} + +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/globes/renderableglobe.h b/modules/globebrowsing/globes/renderableglobe.h index f854a94156..2305f9246c 100644 --- a/modules/globebrowsing/globes/renderableglobe.h +++ b/modules/globebrowsing/globes/renderableglobe.h @@ -1,109 +1,82 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __RENDERABLEGLOBE_H__ -#define __RENDERABLEGLOBE_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___RENDERABLEGLOBE___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___RENDERABLEGLOBE___H__ -#include - -// open space includes #include -#include -#include -#include - -#include - -#include - #include - - -#include #include -#include - -namespace ghoul { -namespace opengl { - class ProgramObject; -} -} - +#include namespace openspace { +namespace globebrowsing { class ChunkedLodGlobe; -class TileProviderManager; - -struct ReferencedBoolSelection : public properties::SelectionProperty { - ReferencedBoolSelection(const std::string& identifier, const std::string& guiName) - : properties::SelectionProperty(identifier, guiName) { } - - void addOption(const std::string& name, bool* ref) { - int optionId= options().size(); - _referenceMap.insert({ optionId, ref }); - properties::SelectionProperty::addOption({ optionId, name}); - } - - void initialize() { - // Set values in GUI to the current values of the references - int nOptions = options().size(); - std::vector selected; - for (int i = 0; i < nOptions; ++i) { - if (*_referenceMap[i]) { - selected.push_back(i); - } - } - setValue(selected); - - - onChange([this]() { - int nOptions = this->options().size(); - for (int i = 0; i < nOptions; ++i) { - (*_referenceMap[i]) = false; - } - - const std::vector& selectedIndices = (*this); - for (auto selectedIndex : selectedIndices) { - (*_referenceMap[selectedIndex]) = true; - } - }); - } - - std::unordered_map _referenceMap; -}; - - - +class LayerManager; +/** + * A RenderableGlobe is a globe modeled as an ellipsoid using a chunked LOD + * algorithm for rendering. + * The renderable uses a DistanceSwitch to determine if the renderable + * should be rendered. + */ class RenderableGlobe : public Renderable { public: + /** + * These properties are specific for ChunkedLodGlobe and separated from + * the general properties of RenderableGlobe. + */ + struct DebugProperties { + properties::BoolProperty saveOrThrowCamera; + properties::BoolProperty showChunkEdges; + properties::BoolProperty showChunkBounds; + properties::BoolProperty showChunkAABB; + properties::BoolProperty showHeightResolution; + properties::BoolProperty showHeightIntensities; + properties::BoolProperty performFrustumCulling; + properties::BoolProperty performHorizonCulling; + properties::BoolProperty levelByProjectedAreaElseDistance; + properties::BoolProperty resetTileProviders; + properties::BoolProperty toggleEnabledEveryFrame; + properties::BoolProperty collectStats; + properties::BoolProperty onlyModelSpaceRendering; + }; + + struct GeneralProperties { + properties::BoolProperty isEnabled; + properties::BoolProperty performShading; + properties::BoolProperty atmosphereEnabled; + properties::FloatProperty lodScaleFactor; + properties::FloatProperty cameraMinHeight; + }; + RenderableGlobe(const ghoul::Dictionary& dictionary); - ~RenderableGlobe(); + ~RenderableGlobe() = default; bool initialize() override; bool deinitialize() override; @@ -112,39 +85,47 @@ public: void render(const RenderData& data) override; void update(const UpdateData& data) override; + // Getters that perform calculations glm::dvec3 projectOnEllipsoid(glm::dvec3 position); - const Ellipsoid& ellipsoid(); float getHeight(glm::dvec3 position); - float cameraMinHeight(); - double interactionDepthBelowEllipsoid(); - std::shared_ptr chunkedLodGlobe(); - - // Properties - properties::BoolProperty _isEnabled; - properties::BoolProperty _toggleEnabledEveryFrame; - properties::FloatProperty lodScaleFactor; - std::vector> _categorySelections; - properties::BoolProperty atmosphereEnabled; - ReferencedBoolSelection debugSelection; - properties::BoolProperty _saveOrThrowCamera; - properties::BoolProperty _resetTileProviders; -private: - double _interactionDepthBelowEllipsoid; + // Getters + std::shared_ptr chunkedLodGlobe() const; + const Ellipsoid& ellipsoid() const; + const glm::dmat4& modelTransform() const; + const glm::dmat4& inverseModelTransform() const; + const DebugProperties& debugProperties() const; + const GeneralProperties& generalProperties() const; + const std::shared_ptr savedCamera() const; + double interactionDepthBelowEllipsoid(); + // Setters + void setSaveCamera(std::shared_ptr camera); +private: + // Globes. These are renderables inserted in a distance switch so that the heavier + // ChunkedLodGlobe does not have to be rendered at far distances. + std::shared_ptr _chunkedLodGlobe; + + Ellipsoid _ellipsoid; + std::shared_ptr _layerManager; + DistanceSwitch _distanceSwitch; + std::shared_ptr _savedCamera; + + double _interactionDepthBelowEllipsoid; std::string _frame; double _time; - Ellipsoid _ellipsoid; + glm::dmat4 _cachedModelTransform; + glm::dmat4 _cachedInverseModelTransform; - std::shared_ptr _tileProviderManager; - std::shared_ptr _chunkedLodGlobe; - - DistanceSwitch _distanceSwitch; - - properties::FloatProperty _cameraMinHeight; + // Properties + DebugProperties _debugProperties; + GeneralProperties _generalProperties; + properties::PropertyOwner _debugPropertyOwner; + properties::PropertyOwner _texturePropertyOwner; }; -} // namespace openspace +} // namespace globebrowsing +} // namespace openspace -#endif // __RENDERABLEGLOBE_H__ \ No newline at end of file +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___RENDERABLEGLOBE___H__ diff --git a/modules/globebrowsing/include.cmake b/modules/globebrowsing/include.cmake index e69de29bb2..f442a1eee4 100644 --- a/modules/globebrowsing/include.cmake +++ b/modules/globebrowsing/include.cmake @@ -0,0 +1,4 @@ +set (OPENSPACE_DEPENDENCIES + debugging + space +) \ No newline at end of file diff --git a/modules/globebrowsing/meshes/basicgrid.cpp b/modules/globebrowsing/meshes/basicgrid.cpp index 98061deb00..6f86f2a672 100644 --- a/modules/globebrowsing/meshes/basicgrid.cpp +++ b/modules/globebrowsing/meshes/basicgrid.cpp @@ -1,70 +1,60 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ #include -namespace { - const std::string _loggerCat = "BasicGrid"; -} +#include namespace openspace { +namespace globebrowsing { -BasicGrid::BasicGrid( - unsigned int xSegments, - unsigned int ySegments, - TriangleSoup::Positions usePositions, - TriangleSoup::TextureCoordinates useTextureCoordinates, - TriangleSoup::Normals useNormals) - : Grid( - xSegments, - ySegments, - usePositions, - useTextureCoordinates, - useNormals) +BasicGrid::BasicGrid(unsigned int xSegments, unsigned int ySegments, + TriangleSoup::Positions usePositions, + TriangleSoup::TextureCoordinates useTextureCoordinates, + TriangleSoup::Normals useNormals) + : Grid(xSegments, ySegments, usePositions, useTextureCoordinates, useNormals) { - _geometry = std::unique_ptr(new TriangleSoup( + _geometry = std::make_unique( CreateElements(xSegments, ySegments), usePositions, useTextureCoordinates, - useNormals)); + useNormals + ); - if (usePositions == TriangleSoup::Positions::Yes) { + if (usePositions) { _geometry->setVertexPositions(CreatePositions(_xSegments, _ySegments)); } - if (useTextureCoordinates == TriangleSoup::TextureCoordinates::Yes) { - _geometry->setVertexTextureCoordinates(CreateTextureCoordinates(_xSegments, _ySegments)); + if (useTextureCoordinates) { + _geometry->setVertexTextureCoordinates( + CreateTextureCoordinates(_xSegments, _ySegments) + ); } - if (useNormals == TriangleSoup::Normals::Yes) { + if (useNormals) { _geometry->setVertexNormals(CreateNormals(_xSegments, _ySegments)); } } -BasicGrid::~BasicGrid() -{ - -} - int BasicGrid::xSegments() const { return _xSegments; } @@ -78,7 +68,7 @@ void BasicGrid::validate(int xSegments, int ySegments) { "Resolution must be at least 1x1. (" << xSegments << ", " << ySegments << ")"); } -inline size_t BasicGrid::numElements(int xSegments, int ySegments){ +inline size_t BasicGrid::numElements(int xSegments, int ySegments) { return 3 * 2 * xSegments * ySegments; } @@ -121,28 +111,29 @@ std::vector BasicGrid::CreateElements(int xSegments, int ySegments) { return elements; } -std::vector BasicGrid::CreatePositions( - int xSegments, - int ySegments) -{ +std::vector BasicGrid::CreatePositions(int xSegments, int ySegments) { validate(xSegments, ySegments); std::vector positions; positions.reserve(numVertices(xSegments, ySegments)); // Copy from 2d texture coordinates and use as template to create positions - std::vector templateTextureCoords = CreateTextureCoordinates(xSegments, ySegments); - for (unsigned int i = 0; i < templateTextureCoords.size(); i++) - { - positions.push_back(glm::vec4( - templateTextureCoords[i], - 0.0f, - 1.0f - )); + std::vector templateTextureCoords = CreateTextureCoordinates( + xSegments, ySegments + ); + for (const glm::vec2& coords : templateTextureCoords) { + positions.push_back(glm::vec4(coords, 0.f, 1.f)); } + //for (unsigned int i = 0; i < templateTextureCoords.size(); i++) { + // positions.push_back(glm::vec4( + // templateTextureCoords[i], + // 0.0f, + // 1.0f + // )); + //} return positions; } -std::vector BasicGrid::CreateTextureCoordinates(int xSegments, int ySegments){ +std::vector BasicGrid::CreateTextureCoordinates(int xSegments, int ySegments) { validate(xSegments, ySegments); std::vector textureCoordinates; textureCoordinates.reserve(numVertices(xSegments, ySegments)); @@ -172,4 +163,5 @@ std::vector BasicGrid::CreateNormals(int xSegments, int ySegments) { return normals; } -}// namespace openspace \ No newline at end of file +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/meshes/basicgrid.h b/modules/globebrowsing/meshes/basicgrid.h index 05097758da..648d423daf 100644 --- a/modules/globebrowsing/meshes/basicgrid.h +++ b/modules/globebrowsing/meshes/basicgrid.h @@ -22,38 +22,34 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ - -#ifndef __BASICGRIDGEOMETRY_H__ -#define __BASICGRIDGEOMETRY_H__ - -#include +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___BASICGRIDGEOMETRY___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___BASICGRIDGEOMETRY___H__ #include +#include + #include namespace openspace { +namespace globebrowsing { -class BasicGrid : public Grid -{ +class BasicGrid : public Grid { public: /** - \param xSegments is the number of grid cells in the x direction. - \param ySegments is the number of grid cells in the y direction. - \param usePositions determines whether or not to upload any vertex position data - to the GPU. - \param useTextureCoordinates determines whether or not to upload any vertex texture - coordinate data to the GPU. - \param useNormals determines whether or not to upload any vertex normal data - to the GPU. + * \param xSegments is the number of grid cells in the x direction. + * \param ySegments is the number of grid cells in the y direction. + * \param usePositions determines whether or not to upload any vertex position data + * to the GPU. + * \param useTextureCoordinates determines whether or not to upload any vertex texture + * coordinate data to the GPU. + * \param useNormals determines whether or not to upload any vertex normal data + * to the GPU. */ - BasicGrid( - unsigned int xSegments, - unsigned int ySegments, - TriangleSoup::Positions usePositions, - TriangleSoup::TextureCoordinates useTextureCoordinates, - TriangleSoup::Normals useNormals); - ~BasicGrid(); + BasicGrid(unsigned int xSegments, unsigned int ySegments, + TriangleSoup::Positions usePositions, + TriangleSoup::TextureCoordinates useTextureCoordinates, + TriangleSoup::Normals useNormals); virtual int xSegments() const; virtual int ySegments() const; @@ -69,5 +65,8 @@ private: inline size_t numElements(int xSegments, int ySegments); inline size_t numVertices(int xSegments, int ySegments); }; + +} // namespace globebrowsing } // namespace openspace -#endif // __BASICGRIDGEOMETRY_H__ \ No newline at end of file + +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___BASICGRIDGEOMETRY___H__ diff --git a/modules/globebrowsing/meshes/clipmapgrid.cpp b/modules/globebrowsing/meshes/clipmapgrid.cpp deleted file mode 100644 index 771f6c89d9..0000000000 --- a/modules/globebrowsing/meshes/clipmapgrid.cpp +++ /dev/null @@ -1,448 +0,0 @@ -/***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ - -#include - -#include - -namespace { - const std::string _loggerCat = "ClipMapGrid"; -} - -namespace openspace { - -////////////////////////////////////////////////////////////////////////////////////////// -// CLIPMAP GRID (Abstract class) // -////////////////////////////////////////////////////////////////////////////////////////// - -ClipMapGrid::ClipMapGrid(unsigned int segments) - : Grid(segments, segments, TriangleSoup::Positions::No, TriangleSoup::TextureCoordinates::Yes, TriangleSoup::Normals::No) -{ - -} - -ClipMapGrid::~ClipMapGrid() -{ - -} - -int ClipMapGrid::xSegments() const { - return segments(); -} - -int ClipMapGrid::ySegments() const { - return segments(); -} - -int ClipMapGrid::segments() const { - return _xSegments; -} - -////////////////////////////////////////////////////////////////////////////////////////// -// OUTER CLIPMAP GRID // -////////////////////////////////////////////////////////////////////////////////////////// - -OuterClipMapGrid::OuterClipMapGrid(unsigned int segments) -: ClipMapGrid(segments) -{ - _geometry = std::unique_ptr(new TriangleSoup( - CreateElements(segments, segments), - TriangleSoup::Positions::No, - TriangleSoup::TextureCoordinates::Yes, - TriangleSoup::Normals::No)); - - _geometry->setVertexTextureCoordinates(CreateTextureCoordinates(segments, segments)); -} - -OuterClipMapGrid::~OuterClipMapGrid() -{ - -} - -size_t OuterClipMapGrid::numElements(int segments) -{ - int numElementsInTotalSquare = 6 * (segments + 1) * (segments + 1); - int numElementsInHole = 6 * (segments / 4 * segments / 4); - return numElementsInTotalSquare - numElementsInHole; -} - -size_t OuterClipMapGrid::numVerticesBottom(int segments) -{ - return (segments + 1 + 2) * (segments / 4 + 1 + 1); -} - -size_t OuterClipMapGrid::numVerticesLeft(int segments) -{ - return (segments / 4 + 1 + 1) * (segments / 2 + 1); -} - -size_t OuterClipMapGrid::numVerticesRight(int segments) -{ - return (segments / 4 + 1 + 1) * (segments / 2 + 1); -} - -size_t OuterClipMapGrid::numVerticesTop(int segments) -{ - return (segments + 1 + 2) * (segments / 4 + 1 + 1); -} - -size_t OuterClipMapGrid::numVertices(int segments) -{ - return numVerticesBottom(segments) + - numVerticesLeft(segments) + - numVerticesRight(segments) + - numVerticesTop(segments); -} - -void OuterClipMapGrid::validate(int xRes, int yRes) { - - ghoul_assert(xRes == yRes, - "segments must be equal in x and in y. "); - int segments = xRes; - ghoul_assert(segments >= 8, - "segments must be at least 8. (" << segments << ")"); - ghoul_assert(segments == pow(2, int(log2(segments))), - "segments must be a power of 2. (" << segments << ")"); -} - -std::vector OuterClipMapGrid::CreateElements(int xRes, int yRes) { - validate(xRes, yRes); - int segments = xRes; - std::vector elements; - elements.reserve(numElements(segments)); - - // The clipmap geometry is built up by four parts as follows: - // 0 = Bottom part - // 1 = Left part - // 2 = Right part - // 3 = Top part - // - // 33333333 - // 33333333 - // 11 22 - // 11 22 - // 00000000 - // 00000000 - - - // x v01---v11 x .. - // | / | - // x v00---v10 x .. - // - // x x x x .. - // : : : : - - unsigned int previousVerts[4]; - previousVerts[0] = 0; - previousVerts[1] = previousVerts[0] + numVerticesBottom(segments); - previousVerts[2] = previousVerts[1] + numVerticesLeft(segments); - previousVerts[3] = previousVerts[2] + numVerticesRight(segments); - - // Build the bottom part of the clipmap geometry - for (unsigned int y = 0; y < segments / 4 + 1; y++) { - for (unsigned int x = 0; x < segments + 2; x++) { - GLuint v00 = previousVerts[0] + (y + 0) * (segments + 3) + x + 0; - GLuint v10 = previousVerts[0] + (y + 0) * (segments + 3) + x + 1; - GLuint v01 = previousVerts[0] + (y + 1) * (segments + 3) + x + 0; - GLuint v11 = previousVerts[0] + (y + 1) * (segments + 3) + x + 1; - - elements.push_back(v00); - elements.push_back(v10); - elements.push_back(v11); - - elements.push_back(v00); - elements.push_back(v11); - elements.push_back(v01); - } - } - - // Build the left part of the clipmap geometry - for (unsigned int y = 0; y < segments / 2; y++) { - for (unsigned int x = 0; x < segments / 4 + 1; x++) { - GLuint v00 = previousVerts[1] + (y + 0) * (segments / 4 + 2) + x + 0; - GLuint v10 = previousVerts[1] + (y + 0) * (segments / 4 + 2) + x + 1; - GLuint v01 = previousVerts[1] + (y + 1) * (segments / 4 + 2) + x + 0; - GLuint v11 = previousVerts[1] + (y + 1) * (segments / 4 + 2) + x + 1; - - elements.push_back(v00); - elements.push_back(v10); - elements.push_back(v11); - - elements.push_back(v00); - elements.push_back(v11); - elements.push_back(v01); - } - } - - // Build the left part of the clipmap geometry - for (unsigned int y = 0; y < segments / 2; y++) { - for (unsigned int x = 0; x < segments / 4 + 1; x++) { - GLuint v00 = previousVerts[2] + (y + 0) * (segments / 4 + 2) + x + 0; - GLuint v10 = previousVerts[2] + (y + 0) * (segments / 4 + 2) + x + 1; - GLuint v01 = previousVerts[2] + (y + 1) * (segments / 4 + 2) + x + 0; - GLuint v11 = previousVerts[2] + (y + 1) * (segments / 4 + 2) + x + 1; - - elements.push_back(v00); - elements.push_back(v10); - elements.push_back(v11); - - elements.push_back(v00); - elements.push_back(v11); - elements.push_back(v01); - } - } - - // Build the left part of the clipmap geometry - for (unsigned int y = 0; y < segments / 4 + 1; y++) { - for (unsigned int x = 0; x < segments + 2; x++) { - GLuint v00 = previousVerts[3] + (y + 0) * (segments + 3) + x + 0; - GLuint v10 = previousVerts[3] + (y + 0) * (segments + 3) + x + 1; - GLuint v01 = previousVerts[3] + (y + 1) * (segments + 3) + x + 0; - GLuint v11 = previousVerts[3] + (y + 1) * (segments + 3) + x + 1; - - elements.push_back(v00); - elements.push_back(v10); - elements.push_back(v11); - - elements.push_back(v00); - elements.push_back(v11); - elements.push_back(v01); - } - } - return elements; -} - -std::vector OuterClipMapGrid::CreatePositions(int xRes, int yRes) -{ - validate(xRes, yRes); - int segments = xRes; - std::vector positions; - positions.reserve(numVertices(segments)); - std::vector templateTextureCoords = CreateTextureCoordinates(xRes, yRes); - - // Copy from 2d texture coordinates and use as template to create positions - for (unsigned int i = 0; i < templateTextureCoords.size(); i++) { - positions.push_back( - glm::vec4( - templateTextureCoords[i].x, - templateTextureCoords[i].y, - 0, - 1)); - } - - return positions; -} - - -std::vector OuterClipMapGrid::CreateTextureCoordinates(int xRes, int yRes){ - validate(xRes, yRes); - int segments = xRes; - std::vector textureCoordinates; - textureCoordinates.reserve(numVertices(segments)); - - // Build the bottom part of the clipmap geometry - for (int y = -1; y < segments / 4 + 1; y++) { - for (int x = -1; x < segments + 2; x++) { - textureCoordinates.push_back(glm::vec2( - static_cast(x) / segments, - static_cast(y) / segments)); - } - } - - // Build the left part of the clipmap geometry - for (int y = segments / 4; y < 3 * segments / 4 + 1; y++) { - for (int x = -1; x < segments / 4 + 1; x++) { - textureCoordinates.push_back(glm::vec2( - static_cast(x) / segments, - static_cast(y) / segments)); - } - } - - // Build the right part of the clipmap geometry - for (int y = segments / 4; y < 3 * segments / 4 + 1; y++) { - for (int x = 3 * segments / 4; x < segments + 2; x++) { - float u = static_cast(x) / segments; - float v = static_cast(y) / segments; - textureCoordinates.push_back(glm::vec2(u, v)); - } - } - - // Build the top part of the clipmap geometry - for (int y = 3 * segments / 4; y < segments + 2; y++) { - for (int x = -1; x < segments + 2; x++) { - textureCoordinates.push_back(glm::vec2( - static_cast(x) / segments, - static_cast(y) / segments)); - } - } - - return textureCoordinates; -} - -std::vector OuterClipMapGrid::CreateNormals(int xRes, int yRes) { - validate(xRes, yRes); - int segments = xRes; - std::vector normals; - normals.reserve(numVertices(segments)); - - for (int y = -1; y < segments + 2; y++) { - for (int x = -1; x < segments + 2; x++) { - normals.push_back(glm::vec3(0, 0, 1)); - } - } - - return normals; -} - -////////////////////////////////////////////////////////////////////////////////////////// -// INNER CLIPMAP GRID // -////////////////////////////////////////////////////////////////////////////////////////// - - -InnerClipMapGrid::InnerClipMapGrid(unsigned int segments) - : ClipMapGrid(segments) -{ - _geometry = std::unique_ptr(new TriangleSoup( - CreateElements(segments, segments), - TriangleSoup::Positions::No, - TriangleSoup::TextureCoordinates::Yes, - TriangleSoup::Normals::No)); - - _geometry->setVertexTextureCoordinates(CreateTextureCoordinates(segments, segments)); -} - -InnerClipMapGrid::~InnerClipMapGrid() -{ - -} - -size_t InnerClipMapGrid::numElements(int segments) -{ - return segments * segments * 6; -} - -size_t InnerClipMapGrid::numVertices(int segments) -{ - return (segments + 1) * (segments + 1); -} - -void InnerClipMapGrid::validate(int xRes, int yRes) { - - ghoul_assert(xRes == yRes, - "segments must be equal in x and in y. "); - int segments = xRes; - ghoul_assert(segments >= 1, - "segments must be at least 1. (" << segments << ")"); -} - -std::vector InnerClipMapGrid::CreateElements(int xRes, int yRes) { - validate(xRes, yRes); - int segments = xRes; - std::vector elements; - elements.reserve(numElements(segments)); - - // x v01---v11 x .. - // | / | - // x v00---v10 x .. - // - // x x x x .. - // : : : : - - for (unsigned int y = 0; y < segments + 2; y++) { - for (unsigned int x = 0; x < segments + 2; x++) { - GLuint v00 = (y + 0) * (segments + 3) + x + 0; - GLuint v10 = (y + 0) * (segments + 3) + x + 1; - GLuint v01 = (y + 1) * (segments + 3) + x + 0; - GLuint v11 = (y + 1) * (segments + 3) + x + 1; - - elements.push_back(v00); - elements.push_back(v10); - elements.push_back(v11); - - elements.push_back(v00); - elements.push_back(v11); - elements.push_back(v01); - } - } - - return elements; -} - -std::vector InnerClipMapGrid::CreatePositions(int xRes, int yRes) -{ - validate(xRes, yRes); - int segments = xRes; - std::vector positions; - positions.reserve(numVertices(segments)); - std::vector templateTextureCoords = CreateTextureCoordinates(xRes, yRes); - - // Copy from 2d texture coordinates and use as template to create positions - for (unsigned int i = 0; i < templateTextureCoords.size(); i++) { - positions.push_back( - glm::vec4( - templateTextureCoords[i].x, - templateTextureCoords[i].y, - 0, - 1)); - } - - return positions; -} - - -std::vector InnerClipMapGrid::CreateTextureCoordinates(int xRes, int yRes) { - validate(xRes, yRes); - int segments = xRes; - std::vector textureCoordinates; - textureCoordinates.reserve(numVertices(segments)); - - // Build the bottom part of the clipmap geometry - for (int y = -1; y < segments + 2; y++) { - for (int x = -1; x < segments + 2; x++) { - textureCoordinates.push_back(glm::vec2( - static_cast(x) / segments, - static_cast(y) / segments)); - } - } - - return textureCoordinates; -} - -std::vector InnerClipMapGrid::CreateNormals(int xRes, int yRes) { - validate(xRes, yRes); - int segments = xRes; - std::vector normals; - normals.reserve(numVertices(segments)); - - for (int y = -1; y < segments + 2; y++) { - for (int x = -1; x < segments + 2; x++) { - normals.push_back(glm::vec3(0, 0, 1)); - } - } - - return normals; -} - - -}// namespace openspace \ No newline at end of file diff --git a/modules/globebrowsing/meshes/clipmapgrid.h b/modules/globebrowsing/meshes/clipmapgrid.h deleted file mode 100644 index 80a68030d8..0000000000 --- a/modules/globebrowsing/meshes/clipmapgrid.h +++ /dev/null @@ -1,129 +0,0 @@ -/***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ - -#ifndef __CLIPMAPGEOMETRY_H__ -#define __CLIPMAPGEOMETRY_H__ - -#include - -#include -#include - -namespace openspace { - -////////////////////////////////////////////////////////////////////////////////////////// -// CLIPMAP GRID (Abstract class) // -////////////////////////////////////////////////////////////////////////////////////////// - -/** -This class defines a grid used for the layers of a geometry clipmap. A geometry -clipmap is built up from a pyramid of clipmaps so the majority of the grids used -are of the class OuterClipMapGrid. The vertex positions and texture coordinated are -defined differently than for a normal BasicGrid. Other than having the basic grid -vertices it also creates padding of one grid cell on the perimeter. This padding can be -used when rendering a ClipMapGrid so that an inner layer of the pyramid can move and -snap to the outer layers grid cells. -*/ -class ClipMapGrid : public Grid -{ -public: - ClipMapGrid(unsigned int segments); - - ~ClipMapGrid(); - - virtual int xSegments() const; - virtual int ySegments() const; - - /** - Returns the segments of the grid. A ClipMapGrid must have the segments in x and - y direction equal so this function works as a wrapper for xSegments() and - ySegments(). - */ - int segments() const; -}; - -////////////////////////////////////////////////////////////////////////////////////////// -// OUTER CLIPMAP GRID // -////////////////////////////////////////////////////////////////////////////////////////// - -/** -The outer layers of a geometry clipmap pyramid can be built up by grids with sizes -increasing with the power of 2. The OuterClipMapGrid has a whole in the middle where -a smaller ClipMapGrid of half the size can fit. -*/ -class OuterClipMapGrid : public ClipMapGrid -{ -public: - OuterClipMapGrid(unsigned int segments); - - ~OuterClipMapGrid(); - -protected: - virtual std::vector CreateElements(int xSegments, int ySegments); - virtual std::vector CreatePositions(int xSegments, int ySegments); - virtual std::vector CreateTextureCoordinates(int xSegments, int ySegments); - virtual std::vector CreateNormals(int xSegments, int ySegments); - -private: - void validate(int xSegments, int ySegments); - - static size_t numVerticesBottom(int segments); - static size_t numVerticesLeft(int segments); - static size_t numVerticesRight(int segments); - static size_t numVerticesTop(int segments); - - static size_t numElements(int segments); - static size_t numVertices(int segments); -}; - -////////////////////////////////////////////////////////////////////////////////////////// -// INNER CLIPMAP GRID // -////////////////////////////////////////////////////////////////////////////////////////// - -/** -The InnerClipMapGrid can be used for the inner most (smallest) grid of a geometry clipmap -pyramid. The only difference from a OuterClipMapGrid is that this grid does not have -a whole where a smaller ClipMapGrid can be positioned. -*/ -class InnerClipMapGrid : public ClipMapGrid -{ -public: - InnerClipMapGrid(unsigned int segments); - - ~InnerClipMapGrid(); - -private: - virtual std::vector CreateElements( int xSegments, int ySegments); - virtual std::vector CreatePositions(int xSegments, int ySegments); - virtual std::vector CreateTextureCoordinates(int xSegments, int ySegments); - virtual std::vector CreateNormals(int xSegments, int ySegments); - - void validate(int xSegments, int ySegments); - - static size_t numElements(int segments); - static size_t numVertices(int segments); -}; - -} // namespace openspace -#endif // __CLIPMAPGEOMETRY_H__ \ No newline at end of file diff --git a/modules/globebrowsing/meshes/grid.cpp b/modules/globebrowsing/meshes/grid.cpp index 414b81eecd..f6d6a1f2e3 100644 --- a/modules/globebrowsing/meshes/grid.cpp +++ b/modules/globebrowsing/meshes/grid.cpp @@ -1,55 +1,41 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ #include -namespace { - const std::string _loggerCat = "Grid"; -} - namespace openspace { +namespace globebrowsing { - Grid::Grid( - int xSegments, - int ySegments, - TriangleSoup::Positions usePositions, - TriangleSoup::TextureCoordinates useTextures, - TriangleSoup::Normals useNormals) +Grid::Grid(int xSegments, int ySegments, TriangleSoup::Positions usePositions, + TriangleSoup::TextureCoordinates useTextures, TriangleSoup::Normals useNormals) : _xSegments(xSegments) , _ySegments(ySegments) -{ +{} -} - -Grid::~Grid() -{ - -} - -TriangleSoup& Grid::geometry() -{ +TriangleSoup& Grid::geometry() { return *_geometry; } -}// namespace openspace \ No newline at end of file +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/meshes/grid.h b/modules/globebrowsing/meshes/grid.h index 30986a04c6..37d169d696 100644 --- a/modules/globebrowsing/meshes/grid.h +++ b/modules/globebrowsing/meshes/grid.h @@ -1,97 +1,98 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __GRIDGEOMETRY_H__ -#define __GRIDGEOMETRY_H__ - -#include -#include +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___GRIDGEOMETRY___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___GRIDGEOMETRY___H__ #include +#include + +#include #include namespace openspace { +namespace globebrowsing { /** -* Abstract class defining an interface used for geometries with grid structures. -* The class Grid should be extended for use of geometries with a 2D -* structure where the number of segments in x and y direction represents the number -* of vertices + 1 in each direction. -*/ -class Grid -{ + * Abstract class defining an interface used for geometries with grid structures. + * The class Grid should be extended for use of geometries with a 2D + * structure where the number of segments in x and y direction represents the number + * of vertices + 1 in each direction. + */ +class Grid { public: - Grid( - int xSegments, - int ySegments, + Grid(int xSegments, int ySegments, TriangleSoup::Positions usePositions = TriangleSoup::Positions::No, - TriangleSoup::TextureCoordinates useTextures = TriangleSoup::TextureCoordinates::No, + TriangleSoup::TextureCoordinates useTextures = + TriangleSoup::TextureCoordinates::No, TriangleSoup::Normals useNormals = TriangleSoup::Normals::No); - ~Grid(); + + virtual ~Grid() = default; TriangleSoup& geometry(); /** - * Returns the number of grid cells in the x direction. Hence the number of vertices - * in the x direction is xResolution + 1. - */ + * Returns the number of grid cells in the x direction. Hence the number of vertices + * in the x direction is xResolution + 1. + */ virtual int xSegments() const = 0; /** - * Returns the number of grid cells in the y direction. Hence the number of vertices - * in the y direction is xResolution + 1. - */ + * Returns the number of grid cells in the y direction. Hence the number of vertices + * in the y direction is xResolution + 1. + */ virtual int ySegments() const = 0; protected: /** - * Should return the indices of vertices for a grid with size xSegments * - * ySegments. Where the number of vertices in each direction is the number - * of segments + 1. - */ + * Should return the indices of vertices for a grid with size xSegments * + * ySegments. Where the number of vertices in each direction is the number + * of segments + 1. + */ virtual std::vector CreateElements(int xSegments, int ySegments) = 0; /** - * Should return the positions of vertices for a grid with size xSegments * - * ySegments. Where the number of vertices in each direction is the number - * of segments + 1. - */ + * Should return the positions of vertices for a grid with size xSegments + * * ySegments. Where the number of vertices in each direction is the + * number of segments + 1. + */ virtual std::vector CreatePositions(int xSegments, int ySegments) = 0; /** - * Should return the texture coordinates of vertices for a grid with size - * xSegments * ySegments. Where the number of vertices in - * each direction is the number of segments + 1. - */ - virtual std::vector CreateTextureCoordinates(int xSegments, int ySegments) = 0; + * Should return the texture coordinates of vertices for a grid with size + * xSegments * ySegments. Where the number of vertices in + * each direction is the number of segments + 1. + */ + virtual std::vector + CreateTextureCoordinates(int xSegments, int ySegments) = 0; /** - * Should return the normals of vertices for a grid with size xSegments * - * ySegments. Where the number of vertices in each direction is the number - * of segments + 1. - */ + * Should return the normals of vertices for a grid with size xSegments * + * ySegments. Where the number of vertices in each direction is the number + * of segments + 1. + */ virtual std::vector CreateNormals(int xSegments, int ySegments) = 0; std::unique_ptr _geometry; @@ -99,5 +100,8 @@ protected: const int _xSegments; const int _ySegments; }; + +} // namespace globebrowsing } // namespace openspace -#endif // __GRIDGEOMETRY_H__ + +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___GRIDGEOMETRY___H__ diff --git a/modules/globebrowsing/meshes/skirtedgrid.cpp b/modules/globebrowsing/meshes/skirtedgrid.cpp index 7a130204e6..9ccea91d28 100644 --- a/modules/globebrowsing/meshes/skirtedgrid.cpp +++ b/modules/globebrowsing/meshes/skirtedgrid.cpp @@ -1,174 +1,180 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ #include +#include + namespace { - const std::string _loggerCat = "SkirtedGrid"; + const char*_loggerCat = "SkirtedGrid"; } namespace openspace { +namespace globebrowsing { - SkirtedGrid::SkirtedGrid( - unsigned int xSegments, - unsigned int ySegments, - TriangleSoup::Positions usePositions, - TriangleSoup::TextureCoordinates useTextureCoordinates, - TriangleSoup::Normals useNormals) - : Grid( - xSegments, - ySegments, - usePositions, - useTextureCoordinates, - useNormals) - { - _geometry = std::unique_ptr(new TriangleSoup( - CreateElements(xSegments, ySegments), - usePositions, - useTextureCoordinates, - useNormals)); +SkirtedGrid::SkirtedGrid(unsigned int xSegments, unsigned int ySegments, + TriangleSoup::Positions usePositions, + TriangleSoup::TextureCoordinates useTextureCoordinates, + TriangleSoup::Normals useNormals) + : Grid(xSegments, ySegments, usePositions, useTextureCoordinates, useNormals) +{ + _geometry = std::make_unique( + CreateElements(xSegments, ySegments), + usePositions, + useTextureCoordinates, + useNormals + ); - if (usePositions == TriangleSoup::Positions::Yes) { - _geometry->setVertexPositions(CreatePositions(_xSegments, _ySegments)); - } - if (useTextureCoordinates == TriangleSoup::TextureCoordinates::Yes) { - _geometry->setVertexTextureCoordinates(CreateTextureCoordinates(_xSegments, _ySegments)); - } - if (useNormals == TriangleSoup::Normals::Yes) { - _geometry->setVertexNormals(CreateNormals(_xSegments, _ySegments)); + if (usePositions) { + _geometry->setVertexPositions(CreatePositions(_xSegments, _ySegments)); + } + if (useTextureCoordinates) { + _geometry->setVertexTextureCoordinates(CreateTextureCoordinates(_xSegments, _ySegments)); + } + if (useNormals) { + _geometry->setVertexNormals(CreateNormals(_xSegments, _ySegments)); + } +} + +int SkirtedGrid::xSegments() const { + return _xSegments; +} + +int SkirtedGrid::ySegments() const { + return _ySegments; +} + +void SkirtedGrid::validate(int xSegments, int ySegments) { + ghoul_assert( + xSegments > 0 && ySegments > 0, + "Resolution must be at least 1x1. (" + std::to_string(xSegments) + ", " + std::to_string(ySegments) + ")" + ); +} + +inline size_t SkirtedGrid::numElements(int xSegments, int ySegments) { + return 3 * 2 * xSegments * ySegments; +} + +inline size_t SkirtedGrid::numVertices(int xSegments, int ySegments) { + return (xSegments + 1) * (ySegments + 1); +} + +std::vector SkirtedGrid::CreateElements(int xSegments, int ySegments) { + validate(xSegments, ySegments); + + std::vector elements; + elements.reserve(numElements(xSegments + 2, ySegments + 2)); + for (unsigned int y = 0; y < ySegments + 2; y++) { + for (unsigned int x = 0; x < xSegments + 2; x++) { + + // x v01---v11 x .. + // | / | + // x v00---v10 x .. + // + // x x x x .. + // : : : : + + GLuint v00 = (y + 0) * (xSegments + 2 + 1) + x + 0; + GLuint v10 = (y + 0) * (xSegments + 2 + 1) + x + 1; + GLuint v01 = (y + 1) * (xSegments + 2 + 1) + x + 0; + GLuint v11 = (y + 1) * (xSegments + 2 + 1) + x + 1; + + // add upper triangle + elements.push_back(v00); + elements.push_back(v10); + elements.push_back(v11); + + // add lower triangle + elements.push_back(v00); + elements.push_back(v11); + elements.push_back(v01); } } - SkirtedGrid::~SkirtedGrid() - { + return elements; +} +std::vector SkirtedGrid::CreatePositions(int xSegments, int ySegments) { + validate(xSegments, ySegments); + std::vector positions; + positions.reserve(numVertices(xSegments, ySegments)); + + // Copy from 2d texture coordinates and use as template to create positions + std::vector templateTextureCoords = CreateTextureCoordinates( + xSegments, ySegments + ); + for (const auto& c : templateTextureCoords) { + positions.push_back(glm::vec4(c, 0.f, 1.f)); } + //for (unsigned int i = 0; i < templateTextureCoords.size(); i++) { + // positions.push_back(glm::vec4( + // templateTextureCoords[i], + // 0.0f, + // 1.0f + // )); + //} + return positions; +} - int SkirtedGrid::xSegments() const { - return _xSegments; - } +std::vector SkirtedGrid::CreateTextureCoordinates(int xSegments, int ySegments) +{ + validate(xSegments, ySegments); + std::vector textureCoordinates; + textureCoordinates.reserve(numVertices(xSegments + 2, ySegments + 2)); - int SkirtedGrid::ySegments() const { - return _ySegments; - } - - void SkirtedGrid::validate(int xSegments, int ySegments) { - ghoul_assert(xSegments > 0 && ySegments > 0, - "Resolution must be at least 1x1. (" << xSegments << ", " << ySegments << ")"); - } - - inline size_t SkirtedGrid::numElements(int xSegments, int ySegments) { - return 3 * 2 * xSegments * ySegments; - } - - inline size_t SkirtedGrid::numVertices(int xSegments, int ySegments) { - return (xSegments + 1) * (ySegments + 1); - } - - std::vector SkirtedGrid::CreateElements(int xSegments, int ySegments) { - validate(xSegments, ySegments); - - std::vector elements; - elements.reserve(numElements(xSegments + 2, ySegments + 2)); - for (unsigned int y = 0; y < ySegments + 2; y++) { - for (unsigned int x = 0; x < xSegments + 2; x++) { - - // x v01---v11 x .. - // | / | - // x v00---v10 x .. - // - // x x x x .. - // : : : : - - GLuint v00 = (y + 0) * (xSegments + 2 + 1) + x + 0; - GLuint v10 = (y + 0) * (xSegments + 2 + 1) + x + 1; - GLuint v01 = (y + 1) * (xSegments + 2 + 1) + x + 0; - GLuint v11 = (y + 1) * (xSegments + 2 + 1) + x + 1; - - // add upper triangle - elements.push_back(v00); - elements.push_back(v10); - elements.push_back(v11); - - // add lower triangle - elements.push_back(v00); - elements.push_back(v11); - elements.push_back(v01); - } + for (int y = -1; y < ySegments + 2; y++) { + for (int x = -1; x < xSegments + 2; x++) { + textureCoordinates.push_back(glm::vec2( + glm::clamp( + static_cast(x) / static_cast(xSegments), + 0 - 1.0f / (2 * xSegments), + 1 + 1.0f / (2 * xSegments) + ), + glm::clamp( + static_cast(y) / static_cast(ySegments), + 0 - 1.0f / (2 * ySegments), + 1 + 1.0f / (2 * ySegments) + ) + )); } - - return elements; } + return textureCoordinates; +} - std::vector SkirtedGrid::CreatePositions( - int xSegments, - int ySegments) - { - validate(xSegments, ySegments); - std::vector positions; - positions.reserve(numVertices(xSegments, ySegments)); +std::vector SkirtedGrid::CreateNormals(int xSegments, int ySegments) { + validate(xSegments, ySegments); + std::vector normals; + normals.reserve(numVertices(xSegments + 2, ySegments + 2)); - // Copy from 2d texture coordinates and use as template to create positions - std::vector templateTextureCoords = CreateTextureCoordinates(xSegments, ySegments); - for (unsigned int i = 0; i < templateTextureCoords.size(); i++) - { - positions.push_back(glm::vec4( - templateTextureCoords[i], - 0.0f, - 1.0f - )); + for (int y = -1; y < ySegments + 2; y++) { + for (int x = -1; x < xSegments + 2; x++) { + normals.push_back(glm::vec3(0, 0, 1)); } - return positions; } - std::vector SkirtedGrid::CreateTextureCoordinates(int xSegments, int ySegments) { - validate(xSegments, ySegments); - std::vector textureCoordinates; - textureCoordinates.reserve(numVertices(xSegments + 2, ySegments + 2)); + return normals; +} - for (int y = -1; y < ySegments + 2; y++) { - for (int x = -1; x < xSegments + 2; x++) { - textureCoordinates.push_back(glm::vec2( - glm::clamp(static_cast(x) / static_cast(xSegments), 0 - 1.0f / (2 * xSegments), 1 + 1.0f / (2 * xSegments)), - glm::clamp(static_cast(y) / static_cast(ySegments), 0 - 1.0f / (2 * ySegments), 1 + 1.0f / (2 * ySegments)) - )); - } - } - return textureCoordinates; - } - - std::vector SkirtedGrid::CreateNormals(int xSegments, int ySegments) { - validate(xSegments, ySegments); - std::vector normals; - normals.reserve(numVertices(xSegments + 2, ySegments + 2)); - - for (int y = -1; y < ySegments + 2; y++) { - for (int x = -1; x < xSegments + 2; x++) { - normals.push_back(glm::vec3(0, 0, 1)); - } - } - - return normals; - } -}// namespace openspace \ No newline at end of file +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/meshes/skirtedgrid.h b/modules/globebrowsing/meshes/skirtedgrid.h index 57669006df..1119c206f9 100644 --- a/modules/globebrowsing/meshes/skirtedgrid.h +++ b/modules/globebrowsing/meshes/skirtedgrid.h @@ -1,79 +1,78 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ - -#ifndef __SKIRTEDGRID_H__ -#define __SKIRTEDGRID_H__ - -#include +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___SKIRTEDGRID___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___SKIRTEDGRID___H__ #include +#include #include namespace openspace { +namespace globebrowsing { /** -* This grid is the same as BasicGrid except it has skirts around its edges. -* The areas covered by the skirts have position coordinates and texture coordinates -* that are outside of the range [0, 1]. The width of the skirts is half the size of one -* segment width or a cell. -*/ -class SkirtedGrid : public Grid -{ + * This grid is the same as BasicGrid except it has skirts around its edges. + * The areas covered by the skirts have position coordinates and texture coordinates + * that are outside of the range [0, 1]. The width of the skirts is half the size of one + * segment width or a cell. + */ +class SkirtedGrid : public Grid { public: /** - * \param xSegments is the number of grid cells in the x direction. - * \param ySegments is the number of grid cells in the y direction. - * \param usePositions determines whether or not to upload any vertex position data - * to the GPU. - * \param useTextureCoordinates determines whether or not to upload any vertex texture - * coordinate data to the GPU. - * \param useNormals determines whether or not to upload any vertex normal data - * to the GPU. - */ - SkirtedGrid( - unsigned int xSegments, - unsigned int ySegments, + * \param xSegments is the number of grid cells in the x direction. + * \param ySegments is the number of grid cells in the y direction. + * \param usePositions determines whether or not to upload any vertex position data + * to the GPU. + * \param useTextureCoordinates determines whether or not to upload any vertex texture + * coordinate data to the GPU. + * \param useNormals determines whether or not to upload any vertex normal data + * to the GPU. + */ + SkirtedGrid(unsigned int xSegments, unsigned int ySegments, TriangleSoup::Positions usePositions, TriangleSoup::TextureCoordinates useTextureCoordinates, TriangleSoup::Normals useNormals); - ~SkirtedGrid(); + ~SkirtedGrid() = default; virtual int xSegments() const; virtual int ySegments() const; private: - virtual std::vector CreateElements(int xRes, int yRes); - virtual std::vector CreatePositions(int xRes, int yRes); - virtual std::vector CreateTextureCoordinates(int xRes, int yRes); - virtual std::vector CreateNormals(int xRes, int yRes); + virtual std::vector CreateElements(int xRes, int yRes); + virtual std::vector CreatePositions(int xRes, int yRes); + virtual std::vector CreateTextureCoordinates(int xRes, int yRes); + virtual std::vector CreateNormals(int xRes, int yRes); void validate(int xSegments, int ySegments); - inline size_t numElements(int xSegments, int ySegments); - inline size_t numVertices(int xSegments, int ySegments); + size_t numElements(int xSegments, int ySegments); + size_t numVertices(int xSegments, int ySegments); }; + +} // namespace globebrowsing } // namespace openspace -#endif // __SKIRTEDGRID_H__ \ No newline at end of file + +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___SKIRTEDGRID___H__ diff --git a/modules/globebrowsing/meshes/trianglesoup.cpp b/modules/globebrowsing/meshes/trianglesoup.cpp index f50e88601b..74e9508d96 100644 --- a/modules/globebrowsing/meshes/trianglesoup.cpp +++ b/modules/globebrowsing/meshes/trianglesoup.cpp @@ -1,44 +1,46 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ #include +#include + namespace { const std::string _loggerCat = "TriangleSoup"; } -namespace openspace -{ +namespace openspace { +namespace globebrowsing { -TriangleSoup::TriangleSoup(std::vector elements, - Positions usePositions, TextureCoordinates useTextures, Normals useNormals) +TriangleSoup::TriangleSoup(std::vector elements, Positions usePositions, + TextureCoordinates useTextures, Normals useNormals) : _vaoID(0) - ,_vertexBufferID(0) - ,_elementBufferID(0) - ,_useVertexPositions(usePositions) - ,_useTextureCoordinates(useTextures) - ,_useVertexNormals(useNormals) + , _vertexBufferID(0) + , _elementBufferID(0) + , _useVertexPositions(usePositions) + , _useTextureCoordinates(useTextures) + , _useVertexNormals(useNormals) { setElements(elements); } @@ -53,8 +55,7 @@ void TriangleSoup::setVertexPositions(std::vector positions) { _useVertexPositions = true; _gpuDataNeedUpdate = true; _vertexData.resize(positions.size()); - for (size_t i = 0; i < positions.size(); i++) - { + for (size_t i = 0; i < positions.size(); i++) { _vertexData[i].position[0] = static_cast(positions[i].x); _vertexData[i].position[1] = static_cast(positions[i].y); _vertexData[i].position[2] = static_cast(positions[i].z); @@ -66,8 +67,7 @@ void TriangleSoup::setVertexTextureCoordinates(std::vector textures) _useTextureCoordinates = true; _gpuDataNeedUpdate = true; _vertexData.resize(textures.size()); - for (size_t i = 0; i < textures.size(); i++) - { + for (size_t i = 0; i < textures.size(); i++) { _vertexData[i].texture[0] = static_cast(textures[i].s); _vertexData[i].texture[1] = static_cast(textures[i].t); } @@ -77,8 +77,7 @@ void TriangleSoup::setVertexNormals(std::vector normals) { _useVertexNormals = true; _gpuDataNeedUpdate = true; _vertexData.resize(normals.size()); - for (size_t i = 0; i < normals.size(); i++) - { + for (size_t i = 0; i < normals.size(); i++) { _vertexData[i].normal[0] = static_cast(normals[i].x); _vertexData[i].normal[1] = static_cast(normals[i].y); _vertexData[i].normal[2] = static_cast(normals[i].z); @@ -88,16 +87,16 @@ void TriangleSoup::setVertexNormals(std::vector normals) { void TriangleSoup::setElements(std::vector elements) { _elementData.resize(elements.size()); _gpuDataNeedUpdate = true; - for (size_t i = 0; i < elements.size(); i++) - { + for (size_t i = 0; i < elements.size(); i++) { _elementData[i] = static_cast(elements[i]); } } bool TriangleSoup::updateDataOnGPU() { // Create VAO - if (_vaoID == 0) + if (_vaoID == 0) { glGenVertexArrays(1, &_vaoID); + } // Create VBOs if (_vertexBufferID == 0 && _vertexData.size() > 0) { @@ -124,7 +123,8 @@ bool TriangleSoup::updateDataOnGPU() { GL_ARRAY_BUFFER, _vertexData.size() * sizeof(Vertex), &_vertexData[0], - GL_STATIC_DRAW); + GL_STATIC_DRAW + ); // Positions at location 0 if (_useVertexPositions) { @@ -170,4 +170,5 @@ void TriangleSoup::drawUsingActiveProgram() { glBindVertexArray(0); } +} // namespace globebrowsing } // namespace openspace diff --git a/modules/globebrowsing/meshes/trianglesoup.h b/modules/globebrowsing/meshes/trianglesoup.h index c80988c29a..dd84ef078f 100644 --- a/modules/globebrowsing/meshes/trianglesoup.h +++ b/modules/globebrowsing/meshes/trianglesoup.h @@ -1,51 +1,49 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __TRIANGLESOUP_H__ -#define __TRIANGLESOUP_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___TRIANGLESOUP___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___TRIANGLESOUP___H__ +#include #include #include -#include - -#include #include namespace openspace { +namespace globebrowsing { /** -* Class to hold vertex data and handling OpenGL interfacing and rendering. -* A TriangleSoup has all data needed such as position buffer and normal -* buffer but all data is not necessarily needed for all purpouses so some vertex buffers -* such as normals can be disabled if not needed. -*/ + * Class to hold vertex data and handling OpenGL interfacing and rendering. + * A TriangleSoup has all data needed such as position buffer and normal + * buffer but all data is not necessarily needed for all purpouses so some vertex buffers + * such as normals can be disabled if not needed. + */ // TODO : Possibly render triangle strips in this class instead of triangles since // that is faster -class TriangleSoup -{ +class TriangleSoup { public: using Positions = ghoul::Boolean; using TextureCoordinates = ghoul::Boolean; @@ -92,8 +90,8 @@ protected: // Vertex data std::vector _vertexData; std::vector _elementData; -private: +private: bool updateDataOnGPU(); // GL handles @@ -104,6 +102,7 @@ private: bool _gpuDataNeedUpdate; }; +} // namespace globebrowsing } // namespace openspace -#endif // __TRIANGLESOUP_H__ +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___TRIANGLESOUP___H__ diff --git a/modules/globebrowsing/other/concurrentjobmanager.h b/modules/globebrowsing/other/concurrentjobmanager.h index e34bbf3c16..5020d0682e 100644 --- a/modules/globebrowsing/other/concurrentjobmanager.h +++ b/modules/globebrowsing/other/concurrentjobmanager.h @@ -22,99 +22,53 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __CONCURRENT_JOB_MANAGER_H__ -#define __CONCURRENT_JOB_MANAGER_H__ - -#include -#include -#include -#include -#include +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___CONCURRENT_JOB_MANAGER___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___CONCURRENT_JOB_MANAGER___H__ #include #include -//#include - -#include - - namespace openspace { +namespace globebrowsing { +// Templated abstract base class representing a job to be done. +// Client code derive from this class and implement the virtual execute() method +template +struct Job { + Job(); + virtual ~Job(); - // Templated abstract base class representing a job to be done. - // Client code derive from this class and implement the virtual execute() method - template - struct Job { + virtual void execute() = 0; + virtual std::shared_ptr

product() const = 0; +}; - Job() { } - virtual ~Job() { } +/* + * Templated Concurrent Job Manager + * This class is used execute specific jobs on one (1) parallell thread + */ +template +class ConcurrentJobManager { +public: + ConcurrentJobManager(std::shared_ptr pool); - virtual void execute() = 0; - virtual std::shared_ptr

product() = 0; - - }; + void enqueueJob(std::shared_ptr> job); + void clearEnqueuedJobs(); + std::shared_ptr> popFinishedJob(); + size_t numFinishedJobs() const; - /* - * Templated Concurrent Job Manager - * This class is used execute specific jobs on one (1) parallell thread - */ - template - class ConcurrentJobManager{ - public: - ConcurrentJobManager(std::shared_ptr pool) : threadPool(pool) - { - - } - - ~ConcurrentJobManager() { - - } - - - void enqueueJob(std::shared_ptr> job) { - //threadPool->queue([this, job]() { - // job->execute(); - // _finishedJobs.push(job); - //}); - threadPool->enqueue([this, job]() { - job->execute(); - _finishedJobs.push(job); - }); - } - - void clearEnqueuedJobs() { - //threadPool->clearRemainingTasks(); - threadPool->clearTasks(); - } - - std::shared_ptr> popFinishedJob() { - ghoul_assert(_finishedJobs.size() > 0, "There is no finished job to pop!"); - return _finishedJobs.pop(); - } - - size_t numFinishedJobs() const{ - return _finishedJobs.size(); - } - - void reset() { - //threadPool->clearRemainingTasks(); - threadPool->clearTasks(); - } - - - private: - - ConcurrentQueue>> _finishedJobs; - std::shared_ptr threadPool; - }; + void reset(); +private: + ConcurrentQueue>> _finishedJobs; + std::shared_ptr threadPool; +}; +} // namespace globebrowsing } // namespace openspace +#include "concurrentjobmanager.inl" - -#endif // __CONCURRENT_JOB_MANAGER_H__ +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___CONCURRENT_JOB_MANAGER___H__ diff --git a/modules/globebrowsing/other/concurrentjobmanager.inl b/modules/globebrowsing/other/concurrentjobmanager.inl index 662fe01799..58c75a7a9c 100644 --- a/modules/globebrowsing/other/concurrentjobmanager.inl +++ b/modules/globebrowsing/other/concurrentjobmanager.inl @@ -22,18 +22,57 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __LRU_CACHE__ -#define __LRU_CACHE__ - - #include -//#include - namespace openspace { +namespace globebrowsing { + +template +Job

::Job() {} + +template +Job

::~Job() {} + +template +ConcurrentJobManager

::ConcurrentJobManager(std::shared_ptr pool) : threadPool(pool) { + +} + +template +void ConcurrentJobManager

::enqueueJob(std::shared_ptr> job) { + //threadPool->queue([this, job]() { + // job->execute(); + // _finishedJobs.push(job); + //}); + threadPool->enqueue([this, job]() { + job->execute(); + _finishedJobs.push(job); + }); +} + +template +void ConcurrentJobManager

::clearEnqueuedJobs() { + //threadPool->clearRemainingTasks(); + threadPool->clearTasks(); +} + +template +std::shared_ptr> ConcurrentJobManager

::popFinishedJob() { + ghoul_assert(_finishedJobs.size() > 0, "There is no finished job to pop!"); + return _finishedJobs.pop(); +} + +template +size_t ConcurrentJobManager

::numFinishedJobs() const { + return _finishedJobs.size(); +} + +template +void ConcurrentJobManager

::reset() { + //threadPool->clearRemainingTasks(); + threadPool->clearTasks(); +} - +} // namespace globebrowsing } // namespace openspace - -#endif // \ No newline at end of file diff --git a/modules/globebrowsing/other/concurrentqueue.h b/modules/globebrowsing/other/concurrentqueue.h index 2694fc2de7..7495b0124d 100644 --- a/modules/globebrowsing/other/concurrentqueue.h +++ b/modules/globebrowsing/other/concurrentqueue.h @@ -22,20 +22,15 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __CONCURRENT_QUEUE_H__ -#define __CONCURRENT_QUEUE_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___CONCURRENT_QUEUE___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___CONCURRENT_QUEUE___H__ -#include -#include -#include -#include -#include -#include #include +#include +#include namespace openspace { - - +namespace globebrowsing { /** * Templated thread-safe queue based on std::thread and std::queue @@ -43,47 +38,15 @@ namespace openspace { template class ConcurrentQueue { public: + T pop(); - T pop() { - std::unique_lock mlock(_mutex); - while (_queue.empty()) { - _cond.wait(mlock); - } - auto item = _queue.front(); - _queue.pop(); - return item; - } + void pop(T& item); - void pop(T& item) { - std::unique_lock mlock(_mutex); - while (_queue.empty()) { - _cond.wait(mlock); - } - item = _queue.front(); - _queue.pop(); - } + void push(const T& item); - void push(const T& item) { - std::unique_lock mlock(_mutex); - _queue.push(item); - mlock.unlock(); - _cond.notify_one(); - } + void push(T&& item); - void push(T&& item) { - std::unique_lock mlock(_mutex); - _queue.push(std::move(item)); - mlock.unlock(); - _cond.notify_one(); - } - - size_t size() const{ - std::unique_lock mlock(_mutex); - size_t s = _queue.size(); - mlock.unlock(); - _cond.notify_one(); - return s; - } + size_t size() const; private: std::queue _queue; @@ -91,6 +54,9 @@ private: mutable std::condition_variable _cond; }; -} +} // namespace globebrowsing +} // namespace openspace -#endif // __CONCURRENT_QUEUE_H__ +#include "concurrentqueue.inl" + +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___CONCURRENT_QUEUE___H__ diff --git a/modules/globebrowsing/other/concurrentqueue.inl b/modules/globebrowsing/other/concurrentqueue.inl new file mode 100644 index 0000000000..17b610c997 --- /dev/null +++ b/modules/globebrowsing/other/concurrentqueue.inl @@ -0,0 +1,75 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +namespace openspace { +namespace globebrowsing { + +template +T ConcurrentQueue::pop() { + std::unique_lock mlock(_mutex); + while (_queue.empty()) { + _cond.wait(mlock); + } + auto item = _queue.front(); + _queue.pop(); + return item; +} + +template +void ConcurrentQueue::pop(T& item) { + std::unique_lock mlock(_mutex); + while (_queue.empty()) { + _cond.wait(mlock); + } + item = _queue.front(); + _queue.pop(); +} + +template +void ConcurrentQueue::push(const T& item) { + std::unique_lock mlock(_mutex); + _queue.push(item); + mlock.unlock(); + _cond.notify_one(); +} + +template +void ConcurrentQueue::push(T&& item) { + std::unique_lock mlock(_mutex); + _queue.push(std::move(item)); + mlock.unlock(); + _cond.notify_one(); +} + +template +size_t ConcurrentQueue::size() const { + std::unique_lock mlock(_mutex); + size_t s = _queue.size(); + mlock.unlock(); + _cond.notify_one(); + return s; +} + +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/other/distanceswitch.cpp b/modules/globebrowsing/other/distanceswitch.cpp index aa18752e40..2cee681bc6 100644 --- a/modules/globebrowsing/other/distanceswitch.cpp +++ b/modules/globebrowsing/other/distanceswitch.cpp @@ -1,43 +1,31 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -// open space includes #include -namespace { - const std::string _loggerCat = "DistanceSwitch"; -} - namespace openspace { - -DistanceSwitch::DistanceSwitch(){ - -} - -DistanceSwitch::~DistanceSwitch() { - -} +namespace globebrowsing { bool DistanceSwitch::initialize() { for (int i = 0; i < _renderables.size(); ++i) { @@ -53,9 +41,6 @@ bool DistanceSwitch::deinitialize() { return true; } -bool DistanceSwitch::isReady() const { - return true; -} void DistanceSwitch::render(const RenderData& data) { if (_maxDistances.size() == 0) { @@ -84,10 +69,11 @@ void DistanceSwitch::update(const UpdateData& data) { } } - -void DistanceSwitch::addSwitchValue(std::shared_ptr renderable, double maxDistance) { +void DistanceSwitch::addSwitchValue(std::shared_ptr renderable, + double maxDistance) +{ ghoul_assert(maxDistance > 0, "Renderable must have a positive maxDistance"); - if (_maxDistances.size() > 0){ + if (_maxDistances.size() > 0) { ghoul_assert(maxDistance > _maxDistances.back(), "Renderables must be inserted in ascending order wrt distance"); } @@ -95,5 +81,5 @@ void DistanceSwitch::addSwitchValue(std::shared_ptr renderable, doub _maxDistances.push_back(maxDistance); } -} // namespace openspace - +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/other/distanceswitch.h b/modules/globebrowsing/other/distanceswitch.h index 32f3b40377..009a3300ae 100644 --- a/modules/globebrowsing/other/distanceswitch.h +++ b/modules/globebrowsing/other/distanceswitch.h @@ -1,74 +1,70 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __DISTANCESWITCH_H__ -#define __DISTANCESWITCH_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___DISTANCESWITCH___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___DISTANCESWITCH___H__ -// open space includes #include -#include -#include -#include -#include +#include #include namespace openspace { +struct RenderData; +struct UpdateData; + +namespace globebrowsing { /** - Selects a specific Renderable to be used for rendering, based on distance to the - camera + * Selects a specific Renderable to be used for rendering, based on distance to the + * camera */ class DistanceSwitch { public: - DistanceSwitch(); - virtual ~DistanceSwitch(); - bool initialize(); bool deinitialize(); - bool isReady() const; /** - Picks the first Renderable with the associated maxDistance greater than the - current distance to the camera + * Picks the first Renderable with the associated maxDistance greater than the + * current distance to the camera */ void render(const RenderData& data); void update(const UpdateData& data); /** - Adds a new renderable (first argument) which may be rendered only if the distance - to the camera is less than maxDistance (second argument) + * Adds a new renderable (first argument) which may be rendered only if the distance + * to the camera is less than maxDistance (second argument) */ void addSwitchValue(std::shared_ptr renderable, double maxDistance); private: - - std::vector> _renderables; std::vector _maxDistances; - }; + +} // namespace globebrowsing } // openspace -#endif //__DISTANCESWITCH_H__ + +#endif //__OPENSPACE_MODULE_GLOBEBROWSING___DISTANCESWITCH___H__ diff --git a/modules/globebrowsing/other/lrucache.h b/modules/globebrowsing/other/lrucache.h index 031463373e..2758ed0c3d 100644 --- a/modules/globebrowsing/other/lrucache.h +++ b/modules/globebrowsing/other/lrucache.h @@ -22,51 +22,40 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __LRU_CACHE_H__ -#define __LRU_CACHE_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___LRU_CACHE___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___LRU_CACHE___H__ -#include -#include -#include -#include #include - - +#include namespace openspace { +namespace globebrowsing { - // Templated class implementing a Least-Recently-Used Cache - template - class LRUCache { - public: - LRUCache(size_t size); - ~LRUCache(); +// Templated class implementing a Least-Recently-Used Cache +template +class LRUCache { +public: + LRUCache(size_t size); + void put(const KeyType& key, const ValueType& value); + void clear(); + bool exist(const KeyType& key) const; + ValueType get(const KeyType& key); + size_t size() const; - void put(const KeyType& key, const ValueType& value); - void clear(); - bool exist(const KeyType& key) const; - ValueType get(const KeyType& key); - size_t size() const; - - - private: - void clean(); - - - // Member varialbes - private: - - std::list> _itemList; - std::unordered_map _itemMap; - size_t _cacheSize; - - }; +private: + void clean(); +// Member varialbes +private: + std::list> _itemList; + std::unordered_map _itemMap; + size_t _cacheSize; +}; +} // namespace globebrowsing } // namespace openspace - #include -#endif // __LRU_CACHE_H__ +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___LRU_CACHE___H__ diff --git a/modules/globebrowsing/other/lrucache.inl b/modules/globebrowsing/other/lrucache.inl index 2ff72383b0..83c37bbc88 100644 --- a/modules/globebrowsing/other/lrucache.inl +++ b/modules/globebrowsing/other/lrucache.inl @@ -22,91 +22,61 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __LRU_CACHE__ -#define __LRU_CACHE__ - - #include -//#include - namespace openspace { - +namespace globebrowsing { - template - LRUCache::LRUCache(size_t size) - : _cacheSize(size) { } +template +LRUCache::LRUCache(size_t size) + : _cacheSize(size) +{} - template - LRUCache::~LRUCache() { - // Clean up list and map! +template +void LRUCache::clear() { + _itemList.erase(_itemList.begin(), _itemList.end()); + _itemMap.erase(_itemMap.begin(), _itemMap.end()); +} + +template +void LRUCache::put(const KeyType& key, const ValueType& value) { + auto it = _itemMap.find(key); + if (it != _itemMap.end()) { + _itemList.erase(it->second); + _itemMap.erase(it); } + _itemList.push_front(std::make_pair(key, value)); + _itemMap.insert(std::make_pair(key, _itemList.begin())); + clean(); +} +template +bool LRUCache::exist(const KeyType& key) const { + return _itemMap.count(key) > 0; +} - ////////////////////////////// - // PUBLIC INTERFACE // - ////////////////////////////// +template +ValueType LRUCache::get(const KeyType& key) { + //ghoul_assert(exist(key), "Key " << key << " must exist"); + auto it = _itemMap.find(key); + // Move list iterator pointing to value + _itemList.splice(_itemList.begin(), _itemList, it->second); + return it->second->second; +} - template - void LRUCache::clear() - { - _itemList.erase(_itemList.begin(), _itemList.end()); - _itemMap.erase(_itemMap.begin(), _itemMap.end()); +template +size_t LRUCache::size() const { + return _itemMap.size(); +} + +template +void LRUCache::clean() { + while (_itemMap.size() > _cacheSize) { + auto last_it = _itemList.end(); last_it--; + _itemMap.erase(last_it->first); + _itemList.pop_back(); } +} - template - void LRUCache::put(const KeyType& key, const ValueType& value) - { - auto it = _itemMap.find(key); - if (it != _itemMap.end()) { - _itemList.erase(it->second); - _itemMap.erase(it); - } - _itemList.push_front(std::make_pair(key, value)); - _itemMap.insert(std::make_pair(key, _itemList.begin())); - clean(); - } - - - template - bool LRUCache::exist(const KeyType& key) const - { - return _itemMap.count(key) > 0; - } - - - template - ValueType LRUCache::get(const KeyType& key) - { - //ghoul_assert(exist(key), "Key " << key << " must exist"); - auto it = _itemMap.find(key); - // Move list iterator pointing to value - _itemList.splice(_itemList.begin(), _itemList, it->second); - return it->second->second; - } - - template - size_t LRUCache::size() const - { - return _itemMap.size(); - } - - - - ////////////////////////////// - // PRIVATE HELPERS // - ////////////////////////////// - template - void LRUCache::clean() - { - while (_itemMap.size() > _cacheSize) { - auto last_it = _itemList.end(); last_it--; - _itemMap.erase(last_it->first); - _itemList.pop_back(); - } - } - - +} // namespace globebrowsing } // namespace openspace - -#endif // !__LRU_CACHE__ \ No newline at end of file diff --git a/modules/globebrowsing/other/statscollector.cpp b/modules/globebrowsing/other/statscollector.cpp index 62ee4f6c89..721a24b092 100644 --- a/modules/globebrowsing/other/statscollector.cpp +++ b/modules/globebrowsing/other/statscollector.cpp @@ -22,13 +22,101 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ - - #include - +#include +#include +#include namespace openspace { +namespace globebrowsing { +StatsCollector::StatsCollector(const std::string& filename, int dumpEveryXRecord, + Enabled enabled, const std::string & delimiter) + : _filename(filename) + , _dumpEveryXRecord(dumpEveryXRecord) + , _recordsSinceLastDump(0) + , _enabled(enabled) + , _delimiter(delimiter) + , _hasWrittenHeader(false) + , i(TemplatedStatsCollector(_enabled, delimiter)) + , d(TemplatedStatsCollector(_enabled, delimiter)) +{} -} // namespace openspace \ No newline at end of file +StatsCollector::~StatsCollector() { + dumpToDisk(); +} + +void StatsCollector::startNewRecord() { + if (_enabled) { + if (_dumpEveryXRecord && ++_recordsSinceLastDump >= _dumpEveryXRecord) { + dumpToDisk(); + _recordsSinceLastDump = 0; + } + + i.startNewRecord(); + d.startNewRecord(); + } +} + +void StatsCollector::setEnabled(bool enabled) { + _enabled = enabled; +} + +void StatsCollector::disable() { + _enabled = false; +} + +void StatsCollector::enable() { + _enabled = true; +} + +int StatsCollector::hasHeaders() { + return i.hasHeaders() || d.hasHeaders(); +} + +void StatsCollector::dumpToDisk() { + if (_enabled && hasHeaders()) { + if (!_hasWrittenHeader) { + writeHeader(); + } + writeData(); + } +} + +void StatsCollector::writeHeader() { + std::ofstream ofs(_filename); + if (i.hasHeaders()) { + i.writeHeader(ofs); + if (d.hasHeaders()) { + ofs << _delimiter; + d.writeHeader(ofs); + } + } + else { + d.writeHeader(ofs); + } + _hasWrittenHeader = true; + ofs << std::endl; + ofs.close(); +} + +void StatsCollector::writeData() { + std::ofstream ofs(_filename, std::ofstream::out | std::ofstream::app); + ofs << std::setprecision(32); + while (i.hasRecordsToWrite() || d.hasRecordsToWrite()) { + if (i.hasHeaders() && d.hasHeaders()) { + i.writeNextRecord(ofs); ofs << _delimiter; d.writeNextRecord(ofs); + } + else { + i.writeNextRecord(ofs); d.writeNextRecord(ofs); + } + ofs << std::endl; + } + i.reset(); + d.reset(); + ofs.close(); +} + +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/other/statscollector.h b/modules/globebrowsing/other/statscollector.h index 3bb73728fa..447e308ee4 100644 --- a/modules/globebrowsing/other/statscollector.h +++ b/modules/globebrowsing/other/statscollector.h @@ -21,270 +21,104 @@ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __STATS_TRACKER_H__ -#define __STATS_TRACKER_H__ + +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___STATS_TRACKER___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___STATS_TRACKER___H__ #include -#include -#include - -#include -#include +#include +#include #include #include -#include -#include - - namespace openspace { - +namespace globebrowsing { - template - struct StatsRecord : public std::unordered_map { +template +using StatsRecord = std::unordered_map; - }; +template +struct StatsCollection : public std::vector> { + std::set keys; +}; - template - struct StatsCollection : public std::vector> { - std::set keys; - }; +template +class TemplatedStatsCollector { +public: + TemplatedStatsCollector(bool& enabled, const std::string& delimiter); + ~TemplatedStatsCollector() = default; - template class TemplatedStatsCollector{ - public: + void startNewRecord(); - TemplatedStatsCollector(bool& enabled, const std::string& delimiter) - : _enabled(enabled) - , _delimiter(delimiter) - , _writePos(0) { }; + T& operator[](const std::string& name); - ~TemplatedStatsCollector() { }; + T previous(const std::string& name); - void startNewRecord() { - if(_enabled) - _data.push_back(StatsRecord()); - } + bool hasHeaders(); - T& operator[](const std::string& name) { - if (_enabled) { - _data.keys.insert(name); - return _data.back()[name]; - } - else return _dummy; - } + bool hasRecordsToWrite(); - T previous(const std::string& name) { - if (_data.size() > 1) { - return _data[_data.size() - 2][name]; - } - return T(); - } + void reset(); - bool hasHeaders() { - return _data.keys.size() > 0; - } + void writeHeader(std::ostream& os); - bool hasRecordsToWrite() { - return _writePos < _data.size() - 1; - } + void writeNextRecord(std::ostream& os); - void reset() { - // copy last, i.e. current record - StatsRecord lastRecord = _data.back(); - _data.clear(); - // add it again after cleared the vector - _data.push_back(lastRecord); - _writePos = 0; - - } +private: + StatsCollection _data; + T _dummy; // used when disabled + bool& _enabled; - void writeHeader(std::ostream& os) { - auto keyIt = _data.keys.begin(); - os << *keyIt; - while (++keyIt != _data.keys.end()) { - os << _delimiter << *keyIt; - } - } + size_t _writePos; + std::string _delimiter; +}; - void writeNextRecord(std::ostream& os) { - if (hasRecordsToWrite()) { - // output line by line - StatsRecord& record = _data[_writePos]; +class StatsCollector { +public: + StatsCollector() = delete; - // Access every key. Records with no entry will get a default value - auto keyIt = _data.keys.begin(); - if (keyIt != _data.keys.end()) { - os << record[(*keyIt)]; - while (++keyIt != _data.keys.end()) { - os << _delimiter << record[(*keyIt)]; - } - } + using Enabled = ghoul::Boolean; - _writePos++; - } - } + StatsCollector(const std::string& filename, int dumpEveryXRecord, + Enabled enabled = Enabled::Yes, const std::string& delimiter = ","); - - private: + ~StatsCollector(); - StatsCollection _data; - T _dummy; // used when disabled - bool& _enabled; + void startNewRecord(); - size_t _writePos; - std::string _delimiter; + void setEnabled(bool enabled); - }; + void disable(); - class StatsCollector { + void enable(); - public: + int hasHeaders(); - StatsCollector() = delete; + void dumpToDisk(); - using Enabled = ghoul::Boolean; + TemplatedStatsCollector i; + TemplatedStatsCollector d; - StatsCollector(const std::string& filename, int dumpEveryXRecord, Enabled enabled = Enabled::Yes, const std::string& delimiter = ",") - : _filename(filename) - , _dumpEveryXRecord(dumpEveryXRecord) - , _recordsSinceLastDump(0) - , _enabled(enabled) - , _delimiter(delimiter) - , _hasWrittenHeader(false) - , i(TemplatedStatsCollector(_enabled, delimiter)) - , d(TemplatedStatsCollector(_enabled, delimiter)) - { +private: + void writeHeader(); - }; + void writeData(); - ~StatsCollector() { - dumpToDisk(); - } - - void startNewRecord() { - if (_enabled) { - if (_dumpEveryXRecord && ++_recordsSinceLastDump >= _dumpEveryXRecord) { - dumpToDisk(); - _recordsSinceLastDump = 0; - } + std::string _filename; + std::string _delimiter; - i.startNewRecord(); - d.startNewRecord(); - } - } - - void disable() { - _enabled = false; - } - - void enable() { - _enabled = true; - } - - int hasHeaders() { - return i.hasHeaders() || d.hasHeaders(); - } - - void dumpToDisk() { - if (_enabled && hasHeaders()) { - if (!_hasWrittenHeader) { - writeHeader(); - } - writeData(); - } - } - - TemplatedStatsCollector i; - TemplatedStatsCollector d; - - private: - void writeHeader() { - std::ofstream ofs(_filename); - if (i.hasHeaders()) { - i.writeHeader(ofs); - if (d.hasHeaders()) { - ofs << _delimiter; - d.writeHeader(ofs); - } - } - else { - d.writeHeader(ofs); - } - _hasWrittenHeader = true; - ofs << std::endl; - ofs.close(); - } - - void writeData() { - std::ofstream ofs(_filename, std::ofstream::out | std::ofstream::app); - ofs << std::setprecision(32); - while (i.hasRecordsToWrite() || d.hasRecordsToWrite()) { - if (i.hasHeaders() && d.hasHeaders()) { - i.writeNextRecord(ofs); ofs << _delimiter; d.writeNextRecord(ofs); - } - else { - i.writeNextRecord(ofs); d.writeNextRecord(ofs); - } - ofs << std::endl; - } - i.reset(); d.reset(); - ofs.close(); - } - - std::string _filename; - std::string _delimiter; - - int _dumpEveryXRecord; - int _recordsSinceLastDump; - - bool _enabled; - bool _hasWrittenHeader; - - }; - - /* - - template - struct StatsCsvWriter { - StatsCsvWriter(const std::string& delimiter) - : _delimiter(delimiter) { }; - - virtual void write(const StatsCollection& stats, const std::string& filename) { - std::ofstream ofs(filename); - - // output headers - auto keyIt = stats.keys.begin(); - ofs << *keyIt; - while (keyIt++ != stats.keys.end()) { - ofs << _delimiter << *keyIt; - } - ofs << std::endl; - - // output line by line - for (const StatsRecord& record : stats) { - // Access every key. Records with no entry will get a default value - auto keyIt = stats.keys.begin(); - ofs << record[*keyIt]; - while (keyIt++ != stats.keys.end()) { - ofs << _delimiter << record[*keyIt]; - } - ofs << std::endl; - } - ofs.close(); - } - - private: - std::string _delimiter; - }; - */ + int _dumpEveryXRecord; + int _recordsSinceLastDump; + bool _enabled; + bool _hasWrittenHeader; +}; +} // namespace globebrowsing } // namespace openspace +#include "statscollector.inl" - - - -#endif // __STATS_TRACKER_H__ \ No newline at end of file +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___STATS_TRACKER___H__ diff --git a/modules/base/rotation/spicerotation.cpp b/modules/globebrowsing/other/statscollector.inl similarity index 50% rename from modules/base/rotation/spicerotation.cpp rename to modules/globebrowsing/other/statscollector.inl index 709292554d..bd41627cb2 100644 --- a/modules/base/rotation/spicerotation.cpp +++ b/modules/globebrowsing/other/statscollector.inl @@ -1,3 +1,4 @@ +#include "statscollector.h" /***************************************************************************************** * * * OpenSpace * @@ -22,72 +23,91 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include - -#include -#include - -namespace { - const std::string _loggerCat = "SpiceRotation"; - //const std::string keyGhosting = "EphmerisGhosting"; - - const std::string KeySourceFrame = "SourceFrame"; - const std::string KeyDestinationFrame = "DestinationFrame"; - const std::string KeyKernels = "Kernels"; -} - namespace openspace { - -SpiceRotation::SpiceRotation(const ghoul::Dictionary& dictionary) - : _sourceFrame("") - , _destinationFrame("") - , _rotationMatrix(1.0) - , _kernelsLoadedSuccessfully(true) -{ - const bool hasSourceFrame = dictionary.getValue(KeySourceFrame, _sourceFrame); - if (!hasSourceFrame) - LERROR("SpiceRotation does not contain the key '" << KeySourceFrame << "'"); +namespace globebrowsing { - const bool hasDestinationFrame = dictionary.getValue(KeyDestinationFrame, _destinationFrame); - if (!hasDestinationFrame) - LERROR("SpiceRotation does not contain the key '" << KeyDestinationFrame << "'"); +template +TemplatedStatsCollector::TemplatedStatsCollector(bool& enabled, + const std::string& delimiter) + : _enabled(enabled) + , _delimiter(delimiter) + , _writePos(0) +{} - ghoul::Dictionary kernels; - dictionary.getValue(KeyKernels, kernels); - for (size_t i = 1; i <= kernels.size(); ++i) { - std::string kernel; - bool success = kernels.getValue(std::to_string(i), kernel); - if (!success) - LERROR("'" << KeyKernels << "' has to be an array-style table"); +template +void TemplatedStatsCollector::startNewRecord() { + if (_enabled) { + _data.push_back(StatsRecord()); + } +} - try { - SpiceManager::ref().loadKernel(kernel); - _kernelsLoadedSuccessfully = true; +template +T& TemplatedStatsCollector::operator[](const std::string& name) { + if (_enabled) { + _data.keys.insert(name); + return _data.back()[name]; + } + else { + return _dummy; + } +} + +template +T TemplatedStatsCollector::previous(const std::string& name) { + if (_data.size() > 1) { + return _data[_data.size() - 2][name]; + } + return T(); +} + +template +bool TemplatedStatsCollector::hasHeaders() { + return _data.keys.size() > 0; +} + +template +bool TemplatedStatsCollector::hasRecordsToWrite() { + return _writePos < _data.size() - 1; +} + +template +void TemplatedStatsCollector::reset() { + // copy last, i.e. current record + StatsRecord lastRecord = _data.back(); + _data.clear(); + // add it again after cleared the vector + _data.push_back(lastRecord); + _writePos = 0; + +} + +template +void TemplatedStatsCollector::writeHeader(std::ostream& os) { + auto keyIt = _data.keys.begin(); + os << *keyIt; + while (++keyIt != _data.keys.end()) { + os << _delimiter << *keyIt; + } +} + +template +void TemplatedStatsCollector::writeNextRecord(std::ostream& os) { + if (hasRecordsToWrite()) { + // output line by line + StatsRecord& record = _data[_writePos]; + + // Access every key. Records with no entry will get a default value + auto keyIt = _data.keys.begin(); + if (keyIt != _data.keys.end()) { + os << record[(*keyIt)]; + while (++keyIt != _data.keys.end()) { + os << _delimiter << record[(*keyIt)]; + } } - catch (const SpiceManager::SpiceException& e) { - LERROR("Could not load SPICE kernel: " << e.what()); - _kernelsLoadedSuccessfully = false; - } - } -} - -const glm::dmat3& SpiceRotation::matrix() const { - return _rotationMatrix; -} -void SpiceRotation::update(const UpdateData& data) { - if (!_kernelsLoadedSuccessfully) - return; - try { - _rotationMatrix = SpiceManager::ref().positionTransformMatrix( - _sourceFrame, - _destinationFrame, - data.time); - } - catch (const ghoul::RuntimeError&) { - // In case of missing coverage - _rotationMatrix = glm::dmat3(1); + _writePos++; } } -} // namespace openspace \ No newline at end of file +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/other/threadpool.cpp b/modules/globebrowsing/other/threadpool.cpp index 50618c49fb..517fa183c6 100644 --- a/modules/globebrowsing/other/threadpool.cpp +++ b/modules/globebrowsing/other/threadpool.cpp @@ -22,102 +22,82 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include -#include -#include -#include - -#include #include -#include -#include - - - namespace openspace { +namespace globebrowsing { - Worker::Worker(ThreadPool& pool) - : pool(pool) - { +Worker::Worker(ThreadPool& pool) + : pool(pool) +{} +void Worker::operator()() { + std::function task; + while (true) { + // acquire lock + { + std::unique_lock lock(pool.queue_mutex); + + // look for a work item + while (!pool.stop && pool.tasks.empty()) { + // if there are none wait for notification + pool.condition.wait(lock); + } + + if (pool.stop) { // exit if the pool is stopped + return; + } + + // get the task from the queue + task = pool.tasks.front(); + pool.tasks.pop_front(); + + }// release lock + + // execute the task + task(); } +} - void Worker::operator()() { - std::function task; - while (true) { - - // acquire lock - { - std::unique_lock lock(pool.queue_mutex); - - // look for a work item - while (!pool.stop && pool.tasks.empty()) { - // if there are none wait for notification - pool.condition.wait(lock); - } - - if (pool.stop) { // exit if the pool is stopped - return; - } - - // get the task from the queue - task = pool.tasks.front(); - pool.tasks.pop_front(); - - }// release lock - - // execute the task - task(); - } - - +ThreadPool::ThreadPool(size_t numThreads) + : stop(false) +{ + for (size_t i = 0; i < numThreads; ++i) { + workers.push_back(std::thread(Worker(*this))); } +} +// the destructor joins all threads +ThreadPool::~ThreadPool() { + // stop all threads + stop = true; + condition.notify_all(); - - - - ThreadPool::ThreadPool(size_t numThreads) - : stop(false) - { - for (size_t i = 0; i < numThreads; ++i) { - workers.push_back(std::thread(Worker(*this))); - } + // join them + for (size_t i = 0; i < workers.size(); ++i) { + workers[i].join(); } +} - // the destructor joins all threads - ThreadPool::~ThreadPool() { - // stop all threads - stop = true; - condition.notify_all(); +// add new work item to the pool +void ThreadPool::enqueue(std::function f) { + { // acquire lock + std::unique_lock lock(queue_mutex); - // join them - for (size_t i = 0; i < workers.size(); ++i) { - workers[i].join(); - } - } - + // add the task + tasks.push_back(f); + } // release lock - // add new work item to the pool - void ThreadPool::enqueue(std::function f) { - { // acquire lock - std::unique_lock lock(queue_mutex); + // wake up one thread + condition.notify_one(); +} - // add the task - tasks.push_back(f); - } // release lock +void ThreadPool::clearTasks() { + { // acquire lock + std::unique_lock lock(queue_mutex); + tasks.clear(); + } // release lock +} - // wake up one thread - condition.notify_one(); - } - - void ThreadPool::clearTasks() { - { // acquire lock - std::unique_lock lock(queue_mutex); - tasks.clear(); - } // release lock - } - - -} // namespace openspace \ No newline at end of file +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/other/threadpool.h b/modules/globebrowsing/other/threadpool.h index 00f0964705..683d0064e7 100644 --- a/modules/globebrowsing/other/threadpool.h +++ b/modules/globebrowsing/other/threadpool.h @@ -22,60 +22,53 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __THREAD_POOL_H__ -#define __THREAD_POOL_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___THREAD_POOL___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___THREAD_POOL___H__ -#include -#include -#include -#include +#include +#include +#include #include - -#include - -#include - - +#include +#include // Implementatin based on http://progsch.net/wordpress/?p=81 namespace openspace { - +namespace globebrowsing { - class ThreadPool; +class ThreadPool; - class Worker { - public: - Worker(ThreadPool& pool); - void operator()(); - private: - ThreadPool& pool; - }; +class Worker { +public: + Worker(ThreadPool& pool); + void operator()(); +private: + ThreadPool& pool; +}; - class ThreadPool { - public: - ThreadPool(size_t numThreads); - ~ThreadPool(); +class ThreadPool { +public: + ThreadPool(size_t numThreads); + ~ThreadPool(); - void enqueue(std::function f); - void clearTasks(); + void enqueue(std::function f); + void clearTasks(); - private: - friend class Worker; +private: + friend class Worker; - std::vector workers; + std::vector workers; - std::deque> tasks; + std::deque> tasks; - std::mutex queue_mutex; - std::condition_variable condition; - - bool stop; - }; + std::mutex queue_mutex; + std::condition_variable condition; + bool stop; +}; +} // namespace globebrowsing } // namespace openspace - - -#endif // __THREAD_POOL_H__ \ No newline at end of file +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___THREAD_POOL___H__ diff --git a/modules/globebrowsing/rendering/chunkrenderer.cpp b/modules/globebrowsing/rendering/chunkrenderer.cpp new file mode 100644 index 0000000000..cca9bd191c --- /dev/null +++ b/modules/globebrowsing/rendering/chunkrenderer.cpp @@ -0,0 +1,298 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include +#include +#include + +namespace { + const char* keyFrame = "Frame"; + const char* keyGeometry = "Geometry"; + const char* keyShading = "PerformShading"; + + const char* keyBody = "Body"; +} + +namespace openspace { +namespace globebrowsing { + +ChunkRenderer::ChunkRenderer(std::shared_ptr grid, + std::shared_ptr layerManager) + : _layerManager(layerManager) + , _grid(grid) +{ + _globalLayerShaderManager = std::make_shared( + "GlobalChunkedLodPatch", + "${MODULE_GLOBEBROWSING}/shaders/globalchunkedlodpatch_vs.glsl", + "${MODULE_GLOBEBROWSING}/shaders/globalchunkedlodpatch_fs.glsl"); + + _localLayerShaderManager = std::make_shared( + "LocalChunkedLodPatch", + "${MODULE_GLOBEBROWSING}/shaders/localchunkedlodpatch_vs.glsl", + "${MODULE_GLOBEBROWSING}/shaders/localchunkedlodpatch_fs.glsl"); + + _globalGpuLayerManager = std::make_shared(); + _localGpuLayerManager = std::make_shared(); + +} + +void ChunkRenderer::renderChunk(const Chunk& chunk, const RenderData& data) { + // A little arbitrary with 10 but it works + if (chunk.owner().debugProperties().onlyModelSpaceRendering || chunk.tileIndex().level < 10) { + renderChunkGlobally(chunk, data); + } + else { + renderChunkLocally(chunk, data); + } +} + +void ChunkRenderer::update() { + // unused atm. Could be used for caching or precalculating +} + +ghoul::opengl::ProgramObject* ChunkRenderer::getActivatedProgramWithTileData( + std::shared_ptr layeredShaderManager, + std::shared_ptr gpuLayerManager, + const Chunk& chunk) +{ + const TileIndex& tileIndex = chunk.tileIndex(); + + LayerShaderPreprocessingData layeredTexturePreprocessingData; + + for (size_t i = 0; i < LayerManager::NUM_LAYER_GROUPS; i++) { + LayerGroupPreprocessingData layeredTextureInfo; + auto layerGroup = _layerManager->layerGroup(i); + layeredTextureInfo.lastLayerIdx = layerGroup.activeLayers().size() - 1; + layeredTextureInfo.layerBlendingEnabled = layerGroup.layerBlendingEnabled(); + + layeredTexturePreprocessingData.layeredTextureInfo[i] = layeredTextureInfo; + } + + const auto& generalProps = chunk.owner().generalProperties(); + const auto& debugProps = chunk.owner().debugProperties(); + auto& pairs = layeredTexturePreprocessingData.keyValuePairs; + + pairs.push_back(std::make_pair("useAtmosphere", + std::to_string(generalProps.atmosphereEnabled))); + pairs.push_back(std::make_pair("performShading", + std::to_string(generalProps.performShading))); + pairs.push_back(std::make_pair("showChunkEdges", + std::to_string(debugProps.showChunkEdges))); + pairs.push_back(std::make_pair("showHeightResolution", + std::to_string(debugProps.showHeightResolution))); + pairs.push_back(std::make_pair("showHeightIntensities", + std::to_string(debugProps.showHeightIntensities))); + pairs.push_back(std::make_pair("defaultHeight", + std::to_string(Chunk::DEFAULT_HEIGHT))); + + // Now the shader program can be accessed + ProgramObject* programObject = + layeredShaderManager->programObject( + layeredTexturePreprocessingData); + + if (layeredShaderManager->updatedOnLastCall()) { + gpuLayerManager->bind(programObject, *_layerManager); + } + + // Activate the shader program + programObject->activate(); + + gpuLayerManager->setValue(programObject, *_layerManager, tileIndex); + + // The length of the skirts is proportional to its size + // TODO: Skirt length should probably be proportional to the size reffered to by + // the chunk's most high resolution height map. + programObject->setUniform("skirtLength", + glm::min(static_cast(chunk.surfacePatch().halfSize().lat * 1000000), + 8700.0f)); + programObject->setUniform("xSegments", _grid->xSegments()); + + if (chunk.owner().debugProperties().showHeightResolution) { + programObject->setUniform("vertexResolution", + glm::vec2(_grid->xSegments(), _grid->ySegments())); + } + + return programObject; +} + +void ChunkRenderer::renderChunkGlobally(const Chunk& chunk, const RenderData& data){ + + ProgramObject* programObject = getActivatedProgramWithTileData( + _globalLayerShaderManager, + _globalGpuLayerManager, + chunk); + if (programObject == nullptr) { + return; + } + + const Ellipsoid& ellipsoid = chunk.owner().ellipsoid(); + + if (_layerManager->hasAnyBlendingLayersEnabled()) { + // Calculations are done in the reference frame of the globe. Hence, the + // camera position needs to be transformed with the inverse model matrix + glm::dmat4 inverseModelTransform = chunk.owner().inverseModelTransform(); + glm::dvec3 cameraPosition = glm::dvec3( + inverseModelTransform * glm::dvec4(data.camera.positionVec3(), 1)); + float distanceScaleFactor = chunk.owner().generalProperties().lodScaleFactor * + ellipsoid.minimumRadius(); + programObject->setUniform("cameraPosition", glm::vec3(cameraPosition)); + programObject->setUniform("distanceScaleFactor", distanceScaleFactor); + programObject->setUniform("chunkLevel", chunk.tileIndex().level); + } + + // Calculate other uniform variables needed for rendering + Geodetic2 swCorner = chunk.surfacePatch().getCorner(Quad::SOUTH_WEST); + auto patchSize = chunk.surfacePatch().size(); + + glm::dmat4 modelTransform = chunk.owner().modelTransform(); + glm::dmat4 viewTransform = data.camera.combinedViewMatrix(); + glm::mat4 modelViewTransform = glm::mat4(viewTransform * modelTransform); + glm::mat4 modelViewProjectionTransform = data.camera.projectionMatrix() * + modelViewTransform; + + // Upload the uniform variables + programObject->setUniform( + "modelViewProjectionTransform", modelViewProjectionTransform); + programObject->setUniform("minLatLon", glm::vec2(swCorner.toLonLatVec2())); + programObject->setUniform("lonLatScalingFactor", glm::vec2(patchSize.toLonLatVec2())); + programObject->setUniform("radiiSquared", glm::vec3(ellipsoid.radiiSquared())); + + if (_layerManager->layerGroup( + LayerManager::NightLayers).activeLayers().size() > 0 || + _layerManager->layerGroup( + LayerManager::WaterMasks).activeLayers().size() > 0 || + chunk.owner().generalProperties().atmosphereEnabled || + chunk.owner().generalProperties().performShading) { + // This code temporary until real light sources can be implemented. + glm::vec3 directionToSunWorldSpace = + glm::normalize(-data.modelTransform.translation); + glm::vec3 directionToSunCameraSpace = + (viewTransform * glm::dvec4(directionToSunWorldSpace, 0)); + data.modelTransform.translation; + programObject->setUniform("modelViewTransform", modelViewTransform); + programObject->setUniform( + "lightDirectionCameraSpace", -directionToSunCameraSpace); + } + + // OpenGL rendering settings + glEnable(GL_DEPTH_TEST); + glEnable(GL_CULL_FACE); + glCullFace(GL_BACK); + + // render + _grid->geometry().drawUsingActiveProgram(); + + _globalGpuLayerManager->deactivate(); + + // disable shader + programObject->deactivate(); + +} + +void ChunkRenderer::renderChunkLocally(const Chunk& chunk, const RenderData& data) { + + ProgramObject* programObject = getActivatedProgramWithTileData( + _localLayerShaderManager, + _localGpuLayerManager, + chunk); + if (programObject == nullptr) { + return; + } + + using namespace glm; + + const Ellipsoid& ellipsoid = chunk.owner().ellipsoid(); + + + if (_layerManager->hasAnyBlendingLayersEnabled()) { + float distanceScaleFactor = chunk.owner().generalProperties().lodScaleFactor * + chunk.owner().ellipsoid().minimumRadius(); + programObject->setUniform("distanceScaleFactor", distanceScaleFactor); + programObject->setUniform("chunkLevel", chunk.tileIndex().level); + } + + // Calculate other uniform variables needed for rendering + dmat4 modelTransform = chunk.owner().modelTransform(); + dmat4 viewTransform = data.camera.combinedViewMatrix(); + dmat4 modelViewTransform = viewTransform * modelTransform; + + std::vector cornerNames = { "p01", "p11", "p00", "p10" }; + std::vector cornersCameraSpace(4); + for (int i = 0; i < 4; ++i) { + Quad q = (Quad)i; + Geodetic2 corner = chunk.surfacePatch().getCorner(q); + glm::dvec3 cornerModelSpace = ellipsoid.cartesianSurfacePosition(corner); + glm::dvec3 cornerCameraSpace = + glm::dvec3(dmat4(modelViewTransform) * glm::dvec4(cornerModelSpace, 1)); + cornersCameraSpace[i] = cornerCameraSpace; + programObject->setUniform(cornerNames[i], vec3(cornerCameraSpace)); + } + + // TODO: Patch normal can be calculated for all corners and then linearly + // interpolated on the GPU to avoid cracks for high altitudes. + vec3 patchNormalCameraSpace = normalize( + cross(cornersCameraSpace[Quad::SOUTH_EAST] - + cornersCameraSpace[Quad::SOUTH_WEST], + cornersCameraSpace[Quad::NORTH_EAST] - + cornersCameraSpace[Quad::SOUTH_WEST])); + + programObject->setUniform("patchNormalCameraSpace", patchNormalCameraSpace); + programObject->setUniform("projectionTransform", data.camera.projectionMatrix()); + + if (_layerManager->layerGroup( + LayerManager::NightLayers).activeLayers().size() > 0 || + _layerManager->layerGroup( + LayerManager::WaterMasks).activeLayers().size() > 0 || + chunk.owner().generalProperties().atmosphereEnabled || + chunk.owner().generalProperties().performShading) + { + glm::vec3 directionToSunWorldSpace = + glm::normalize(-data.modelTransform.translation); + glm::vec3 directionToSunCameraSpace = + (viewTransform * glm::dvec4(directionToSunWorldSpace, 0)); + data.modelTransform.translation; + programObject->setUniform( + "lightDirectionCameraSpace", -directionToSunCameraSpace); + } + + // OpenGL rendering settings + glEnable(GL_DEPTH_TEST); + glEnable(GL_CULL_FACE); + glCullFace(GL_BACK); + + // render + _grid->geometry().drawUsingActiveProgram(); + + _localGpuLayerManager->deactivate(); + + // disable shader + programObject->deactivate(); +} + +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/rendering/chunkrenderer.h b/modules/globebrowsing/rendering/chunkrenderer.h new file mode 100644 index 0000000000..2086f29d2d --- /dev/null +++ b/modules/globebrowsing/rendering/chunkrenderer.h @@ -0,0 +1,103 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___CHUNK_RENDERER___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___CHUNK_RENDERER___H__ + +#include + +namespace ghoul { namespace opengl { + class ProgramObject; +} } + +namespace openspace { + +struct RenderData; + +namespace globebrowsing { + +class Chunk; +class Grid; +class GPULayerManager; +class LayerManager; +class LayerShaderManager; + +class ChunkRenderer { +public: + ChunkRenderer(std::shared_ptr grid, + std::shared_ptr layerManager); + + /** + * Chooses to render a chunk either locally or globally depending on the chunklevel + * of the Chunk. + */ + void renderChunk(const Chunk& chunk, const RenderData& data); + void update(); + +private: + /** + * Chunks can be rendered either globally or locally. Global rendering is performed + * in the model space of the globe. With global rendering, the vertex positions + * of a chunk are calculated in the vertex shader by transforming the geodetic + * coordinates of the chunk to model space coordinates. We can only achieve floating + * point precision by doing this which means that the camera too close to a global + * tile will lead to jagging. We only render global chunks for lower chunk levels. + */ + void renderChunkGlobally(const Chunk& chunk, const RenderData& data); + + /** + * Local rendering of chunks are done using linear interpolation in camera space. + * All four corner points of the chunk are calculated in double precision on the + * CPU and transformed to camera space with double precision matrix transforms. + * These positions can then be cast to floats and uploaded to the vertex shader. + * The vertex shader rendering performs linear interpolation between the four + * corner points to get the resulting chunk. This means that there will be an error + * due to the curvature of the globe. The smaller the patch is (with higher chunk + * levels) the better the approximation becomes. This is why we only render local + * chunks for higher chunk levels. + */ + void renderChunkLocally(const Chunk& chunk, const RenderData& data); + + ghoul::opengl::ProgramObject* getActivatedProgramWithTileData( + std::shared_ptr layeredShaderManager, + std::shared_ptr gpuLayerManager, + const Chunk& chunk); + + // shared pointer to a grid which can be the same for all rendered chunks. + std::shared_ptr _grid; + std::shared_ptr _layerManager; + + // Two different shader programs. One for global and one for local rendering. + std::shared_ptr _globalLayerShaderManager; + std::shared_ptr _localLayerShaderManager; + + // Layered texture uniforms are chached in the uniform ID handles. + std::shared_ptr _globalGpuLayerManager; + std::shared_ptr _localGpuLayerManager; +}; + +} // namespace globebrowsing +} // namespace openspace + +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___CHUNK_RENDERER___H__ diff --git a/modules/globebrowsing/rendering/gpulayermanager.cpp b/modules/globebrowsing/rendering/gpulayermanager.cpp new file mode 100644 index 0000000000..355b0af5ae --- /dev/null +++ b/modules/globebrowsing/rendering/gpulayermanager.cpp @@ -0,0 +1,232 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include +#include +#include + +namespace openspace { +namespace globebrowsing { + +void GPUTileUvTransform::setValue(ProgramObject* programObject, + const TileUvTransform& tileUvTransform) +{ + gpuUvOffset.setValue(programObject, tileUvTransform.uvOffset); + gpuUvScale.setValue(programObject, tileUvTransform.uvScale); +} + +void GPUTileUvTransform::bind(ProgramObject* programObject, const std::string& nameBase) { + gpuUvOffset.bind(programObject, nameBase + "uvOffset"); + gpuUvScale.bind(programObject, nameBase + "uvScale"); +} + +void GPUTileDepthTransform::setValue(ProgramObject* programObject, + const TileDepthTransform& depthTransform) +{ + gpuDepthOffset.setValue(programObject, depthTransform.depthOffset); + gpuDepthScale.setValue(programObject, depthTransform.depthScale); +} + +void GPUTileDepthTransform::bind(ProgramObject* programObject, + const std::string& nameBase) +{ + gpuDepthOffset.bind(programObject, nameBase + "depthOffset"); + gpuDepthScale.bind(programObject, nameBase + "depthScale"); +} + +void GPUChunkTile::setValue(ProgramObject* programObject, const ChunkTile& chunkTile) { + gpuTexture.setValue(programObject, chunkTile.tile.texture); + gpuTileUvTransform.setValue(programObject, chunkTile.uvTransform); +} + +void GPUChunkTile::bind(ProgramObject* programObject, const std::string& nameBase) { + gpuTexture.bind(programObject, nameBase + "textureSampler"); + gpuTileUvTransform.bind(programObject, nameBase + "uvTransform."); +} + +void GPUChunkTile::deactivate() { + gpuTexture.deactivate(); +} + +void GPUChunkTilePile::setValue(ProgramObject* programObject, + const ChunkTilePile& chunkTilePile) +{ + ghoul_assert( + gpuChunkTiles.size() == chunkTilePile.chunkTiles.size(), + "GPU and CPU ChunkTilePile must have same size!" + ); + for (size_t i = 0; i < gpuChunkTiles.size(); ++i) { + gpuChunkTiles[i].setValue(programObject, chunkTilePile.chunkTiles[i]); + } +} + +void GPUChunkTilePile::bind(ProgramObject* programObject, const std::string& nameBase, + int pileSize) +{ + gpuChunkTiles.resize(pileSize); + for (size_t i = 0; i < gpuChunkTiles.size(); ++i) { + std::string nameExtension = "chunkTile" + std::to_string(i) + "."; + gpuChunkTiles[i].bind(programObject, nameBase + nameExtension); + } +} + +void GPUChunkTilePile::deactivate() { + for (auto& gpuChunkTile : gpuChunkTiles) { + gpuChunkTile.deactivate(); + } +} + + +void GPULayerRenderSettings::setValue(ProgramObject* programObject, + const LayerRenderSettings& layerSettings) +{ + gpuOpacity.setValue(programObject, layerSettings.opacity.value()); + gpuGamma.setValue(programObject, layerSettings.gamma.value()); + gpuMultiplier.setValue(programObject, layerSettings.multiplier.value()); +} + +void GPULayerRenderSettings::bind(ProgramObject* programObject, + const std::string& nameBase) +{ + gpuOpacity.bind(programObject, nameBase + "opacity"); + gpuGamma.bind(programObject, nameBase + "gamma"); + gpuMultiplier.bind(programObject, nameBase + "multiplier"); +} + +void GPULayer::setValue(ProgramObject* programObject, const Layer& layer, + const TileIndex& tileIndex, int pileSize) +{ + ChunkTilePile chunkTilePile = layer.getChunkTilePile(tileIndex, pileSize); + gpuChunkTilePile.setValue(programObject, chunkTilePile); + gpuRenderSettings.setValue(programObject, layer.renderSettings()); +} + +void GPULayer::bind(ProgramObject* programObject, const Layer& layer, + const std::string& nameBase, int pileSize) +{ + gpuChunkTilePile.bind(programObject, nameBase + "pile.", pileSize); + gpuRenderSettings.bind(programObject, nameBase + "settings."); +} + +void GPULayer::deactivate() { + gpuChunkTilePile.deactivate(); +} + +void GPUHeightLayer::setValue(ProgramObject* programObject, const Layer& layer, + const TileIndex& tileIndex, int pileSize) +{ + GPULayer::setValue(programObject, layer, tileIndex, pileSize); + gpuDepthTransform.setValue(programObject, layer.tileProvider()->depthTransform()); +} + +void GPUHeightLayer::bind(ProgramObject* programObject, const Layer& layer, + const std::string& nameBase, int pileSize) +{ + GPULayer::bind(programObject, layer, nameBase, pileSize); + gpuDepthTransform.bind(programObject, nameBase + "depthTransform."); +} + +void GPULayerGroup::setValue(ProgramObject* programObject, const LayerGroup& layerGroup, + const TileIndex& tileIndex) +{ + auto& activeLayers = layerGroup.activeLayers(); + ghoul_assert( + activeLayers.size() == gpuActiveLayers.size(), + "GPU and CPU active layers must have same size!" + ); + for (int i = 0; i < activeLayers.size(); ++i) { + gpuActiveLayers[i]->setValue( + programObject, + *activeLayers[i], + tileIndex, + layerGroup.pileSize() + ); + } +} + +void GPULayerGroup::bind(ProgramObject* programObject, const LayerGroup& layerGroup, + const std::string& nameBase, int category) +{ + auto activeLayers = layerGroup.activeLayers(); + gpuActiveLayers.resize(activeLayers.size()); + int pileSize = layerGroup.pileSize(); + for (size_t i = 0; i < gpuActiveLayers.size(); ++i) { + // should maybe a proper GPULayer factory + gpuActiveLayers[i] = (category == LayerManager::HeightLayers) ? + std::make_unique() : + std::make_unique(); + std::string nameExtension = "[" + std::to_string(i) + "]."; + gpuActiveLayers[i]->bind( + programObject, + *activeLayers[i], + nameBase + nameExtension, + pileSize + ); + } +} + +void GPULayerGroup::deactivate() { + for (size_t i = 0; i < gpuActiveLayers.size(); ++i) { + gpuActiveLayers[i]->deactivate(); + } +} + +void GPULayerManager::setValue(ProgramObject* programObject, + const LayerManager& layerManager, + const TileIndex& tileIndex) +{ + auto layerGroups = layerManager.layerGroups(); + for (size_t i = 0; i < layerGroups.size(); ++i) { + gpuLayerGroups[i]->setValue(programObject, *layerGroups[i], tileIndex); + } +} + +void GPULayerManager::bind(ProgramObject* programObject, const LayerManager& layerManager) +{ + auto layerGroups = layerManager.layerGroups(); + if (gpuLayerGroups.size() != layerGroups.size()) { + gpuLayerGroups.resize(layerGroups.size()); + for (auto& gpuLayerGroup : gpuLayerGroups){ + gpuLayerGroup = std::make_unique(); + } + } + + for (size_t i = 0; i < layerGroups.size(); ++i) { + std::string nameBase = LayerManager::LAYER_GROUP_NAMES[i]; + gpuLayerGroups[i]->bind(programObject, *layerGroups[i], nameBase, i); + } +} + +void GPULayerManager::deactivate() { + for (size_t i = 0; i < gpuLayerGroups.size(); ++i) { + gpuLayerGroups[i]->deactivate(); + } +} + +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/rendering/gpulayermanager.h b/modules/globebrowsing/rendering/gpulayermanager.h new file mode 100644 index 0000000000..ec9834a610 --- /dev/null +++ b/modules/globebrowsing/rendering/gpulayermanager.h @@ -0,0 +1,320 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___GPU_LAYER_MANAGER___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___GPU_LAYER_MANAGER___H__ + +#include + +#include + +namespace ghoul { namespace opengl { +class ProgramObject; +}} + +namespace openspace { +namespace globebrowsing { + +struct ChunkTile; +struct ChunkTilePile; +class Layer; +class LayerRenderSettings; +struct TileDepthTransform; +struct TileIndex; +struct TileUvTransform; + +/** + * Manages a GPU representation of a TileUvTransform + */ +class GPUTileUvTransform { +public: + /** + * Sets the value of TileUvTransform to its corresponding + * GPU struct. OBS! Users must ensure bind has been + * called before setting using this method. + */ + void setValue(ProgramObject* programObject, const TileUvTransform& uvTransform); + + /** + * Binds GLSL variables with identifiers starting with + * nameBase within the provided shader program with this object. + * After this method has been called, users may invoke setValue. + */ + void bind(ProgramObject* programObject, const std::string& nameBase); + +private: + GPUData gpuUvOffset; + GPUData gpuUvScale; +}; + + +/** + * Manages a GPU representation of a TileDepthTransform + */ +class GPUTileDepthTransform { +public: + /** + * Sets the value of TileDepthTransform to its corresponding + * GPU struct. OBS! Users must ensure bind has been + * called before setting using this method. + */ + void setValue(ProgramObject* programObject, const TileDepthTransform& depthTransform); + + /** + * Binds GLSL variables with identifiers starting with + * nameBase within the provided shader program with this object. + * After this method has been called, users may invoke setValue. + */ + void bind(ProgramObject* programObject, const std::string& nameBase); + +private: + GPUData gpuDepthOffset; + GPUData gpuDepthScale; +}; + +/** + * Manages a GPU representation of a ChunkTile + */ +class GPUChunkTile { +public: + + /** + * Sets the value of ChunkTile to its corresponding + * GPU struct. OBS! Users must ensure bind has been + * called before setting using this method. + */ + void setValue(ProgramObject* programObject, const ChunkTile& chunkTile); + + /** + * Binds GLSL variables with identifiers starting with + * nameBase within the provided shader program with this object. + * After this method has been called, users may invoke setValue. + */ + void bind(ProgramObject* programObject, const std::string& nameBase); + + /** + * Deactivates any TextureUnits assigned by this object. + * This method should be called after the OpenGL draw call. + */ + void deactivate(); + +private: + GPUTexture gpuTexture; + GPUTileUvTransform gpuTileUvTransform; +}; + +/** + * Manages a GPU representation of a ChunkTilePile + */ +class GPUChunkTilePile{ +public: + + /** + * Sets the value of ChunkTilePile to its corresponding + * GPU struct. OBS! Users must ensure bind has been + * called before setting using this method. + */ + void setValue(ProgramObject* programObject, const ChunkTilePile& chunkTilePile); + + /** + * Binds this object with GLSL variables with identifiers starting + * with nameBase within the provided shader program. + * After this method has been called, users may invoke setValue. + */ + void bind(ProgramObject* programObject, const std::string& nameBase, + int pileSize); + /** + * Deactivates any TextureUnits assigned by this object. + * This method should be called after the OpenGL draw call. + */ + void deactivate(); + +private: + std::vector gpuChunkTiles; +}; + + +class LayerRenderSettings; + +/** + * Manages a GPU representation of a LayerRenderSettings + */ +class GPULayerRenderSettings{ +public: + + /** + * Sets the value of LayerRenderSettings to its corresponding + * GPU struct. OBS! Users must ensure bind has been + * called before setting using this method. + */ + void setValue(ProgramObject* programObject, const LayerRenderSettings& layerSettings); + + /** + * Binds this object with GLSL variables with identifiers starting + * with nameBase within the provided shader program. + * After this method has been called, users may invoke setValue. + */ + void bind(ProgramObject* programObject, const std::string& nameBase); + +private: + GPUData gpuOpacity; + GPUData gpuGamma; + GPUData gpuMultiplier; +}; + + +class Layer; + +/** + * Manages a GPU representation of a Layer + */ +class GPULayer { +public: + + /** + * Sets the value of Layer to its corresponding + * GPU struct. OBS! Users must ensure bind has been + * called before setting using this method. + */ + virtual void setValue(ProgramObject* programObject, const Layer& layer, + const TileIndex& tileIndex, int pileSize); + + /** + * Binds this object with GLSL variables with identifiers starting + * with nameBase within the provided shader program. + * After this method has been called, users may invoke setValue. + */ + virtual void bind(ProgramObject* programObject, const Layer& layer, + const std::string& nameBase, int pileSize); + + /** + * Deactivates any TextureUnits assigned by this object. + * This method should be called after the OpenGL draw call. + */ + virtual void deactivate(); + +private: + GPUChunkTilePile gpuChunkTilePile; + GPULayerRenderSettings gpuRenderSettings; +}; + + +/** + * Manages a GPU representation of a Layer representing + * a height map. + */ +class GPUHeightLayer : public GPULayer { +public: + + /** + * Sets the value of Layer to its corresponding + * GPU struct. OBS! Users must ensure bind has been + * called before setting using this method. + */ + virtual void setValue(ProgramObject* programObject, const Layer& layer, + const TileIndex& tileIndex, int pileSize); + + /** + * Binds this object with GLSL variables with identifiers starting + * with nameBase within the provided shader program. + * After this method has been called, users may invoke setValue. + */ + virtual void bind(ProgramObject* programObject, const Layer& layer, + const std::string& nameBase, int pileSize); + +private: + GPUTileDepthTransform gpuDepthTransform; +}; + +class LayerGroup; + +/** + * Manages a GPU representation of a LayerGroup + */ +class GPULayerGroup{ +public: + + /** + * Sets the value of LayerGroup to its corresponding + * GPU struct. OBS! Users must ensure bind has been + * called before setting using this method. + */ + virtual void setValue(ProgramObject* programObject, const LayerGroup& layerGroup, + const TileIndex& tileIndex); + + /** + * Binds this object with GLSL variables with identifiers starting + * with nameBase within the provided shader program. + * After this method has been called, users may invoke setValue. + */ + virtual void bind(ProgramObject* programObject, const LayerGroup& layerGroup, + const std::string& nameBase, int category); + + /** + * Deactivates any TextureUnits assigned by this object. + * This method should be called after the OpenGL draw call. + */ + virtual void deactivate(); + +private: + std::vector> gpuActiveLayers; +}; + +class LayerManager; + +/** + * Manages a GPU representation of a LayerGroup + */ +class GPULayerManager{ +public: + + /** + * Sets the value of LayerGroup to its corresponding + * GPU struct. OBS! Users must ensure bind has been + * called before setting using this method. + */ + virtual void setValue(ProgramObject* programObject, const LayerManager& layerManager, + const TileIndex& tileIndex); + + /** + * Binds this object with GLSL variables with identifiers starting + * with nameBase within the provided shader program. + * After this method has been called, users may invoke setValue. + */ + virtual void bind(ProgramObject* programObject, const LayerManager& layerManager); + + /** + * Deactivates any TextureUnits assigned by this object. + * This method should be called after the OpenGL draw call. + */ + virtual void deactivate(); + +private: + std::vector> gpuLayerGroups; +}; + +} // namespace globebrowsing +} // namespace openspace + +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___GPU_LAYER_MANAGER___H__ diff --git a/modules/globebrowsing/rendering/layermanager.cpp b/modules/globebrowsing/rendering/layermanager.cpp new file mode 100644 index 0000000000..b4dc908b5a --- /dev/null +++ b/modules/globebrowsing/rendering/layermanager.cpp @@ -0,0 +1,194 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +namespace openspace { +namespace globebrowsing { + +LayerRenderSettings::LayerRenderSettings() + : opacity(properties::FloatProperty("opacity", "opacity", 1.f, 0.f, 1.f)) + , gamma(properties::FloatProperty("gamma", "gamma", 1, 0, 5)) + , multiplier(properties::FloatProperty("multiplier", "multiplier", 1.f, 0.f, 20.f)) +{ + setName("settings"); + + addProperty(opacity); + addProperty(gamma); + addProperty(multiplier); +} + +Layer::Layer(const ghoul::Dictionary& layerDict) + : _enabled(properties::BoolProperty("enabled", "enabled", false)) +{ + std::string layerName = "error!"; + layerDict.getValue("Name", layerName); + setName(layerName); + + _tileProvider = std::shared_ptr( + TileProvider::createFromDictionary(layerDict)); + + // Something else went wrong and no exception was thrown + if (_tileProvider == nullptr) { + throw ghoul::RuntimeError("Unable to create TileProvider '" + name() + "'"); + } + + bool enabled = false; // defaults to false if unspecified + layerDict.getValue("Enabled", enabled); + _enabled.setValue(enabled); + addProperty(_enabled); + + addPropertySubOwner(_renderSettings); +} + +ChunkTilePile Layer::getChunkTilePile(const TileIndex& tileIndex, int pileSize) const { + return std::move(_tileProvider->getChunkTilePile(tileIndex, pileSize)); +} + +LayerGroup::LayerGroup(std::string name) + : _levelBlendingEnabled("blendTileLevels", "blend tile levels", true) +{ + setName(std::move(name)); + addProperty(_levelBlendingEnabled); +} + +LayerGroup::LayerGroup(std::string name, const ghoul::Dictionary& dict) + : LayerGroup(std::move(name)) +{ + for (size_t i = 0; i < dict.size(); i++) { + std::string dictKey = std::to_string(i + 1); + ghoul::Dictionary layerDict = dict.value(dictKey); + + try { + _layers.push_back(std::make_shared(layerDict)); + } + catch (const ghoul::RuntimeError& e) { + LERRORC(e.component, e.message); + continue; + } + //_layers.push_back(std::make_shared(layerDict)); + } + + for (const auto& layer : _layers) { + addPropertySubOwner(layer.get()); + } +} + +void LayerGroup::update() { + _activeLayers.clear(); + + for (const auto& layer : _layers) { + if (layer->enabled()) { + layer->tileProvider()->update(); + _activeLayers.push_back(layer); + } + } +} + +const std::vector>& LayerGroup::layers() const { + return _layers; +} + +const std::vector>& LayerGroup::activeLayers() const { + return _activeLayers; +} + +int LayerGroup::pileSize() const{ + return _levelBlendingEnabled.value() ? 3 : 1; +} + +const char* LayerManager::LAYER_GROUP_NAMES[NUM_LAYER_GROUPS] = { + "HeightLayers", + "ColorLayers", + "ColorOverlays", + "GrayScaleLayers", + "GrayScaleColorOverlays", + "NightLayers", + "WaterMasks" +}; + +LayerManager::LayerManager(const ghoul::Dictionary& layerGroupsDict) { + setName("Layers"); + + if (NUM_LAYER_GROUPS != layerGroupsDict.size()) { + throw ghoul::RuntimeError( + "Number of Layer Groups must be equal to " + NUM_LAYER_GROUPS); + } + + // Create all the categories of tile providers + for (size_t i = 0; i < layerGroupsDict.size(); i++) { + std::string groupName = LayerManager::LAYER_GROUP_NAMES[i]; + ghoul::Dictionary layerGroupDict = + layerGroupsDict.value(groupName); + + _layerGroups.push_back( + std::make_shared(groupName, layerGroupDict)); + } + + for (const auto& layerGroup : _layerGroups) { + addPropertySubOwner(layerGroup.get()); + } +} + +const LayerGroup& LayerManager::layerGroup(size_t groupId) { + return *_layerGroups[groupId]; +} + +const LayerGroup& LayerManager::layerGroup(LayerGroupId groupId) { + return *_layerGroups[groupId]; +} + +bool LayerManager::hasAnyBlendingLayersEnabled() const { + for (const auto& layerGroup : _layerGroups) { + if (layerGroup->layerBlendingEnabled() && layerGroup->activeLayers().size() > 0) { + return true; + } + } + return false; +} + +const std::vector>& LayerManager::layerGroups() const { + return _layerGroups; +} + +void LayerManager::update() { + for (auto& layerGroup : _layerGroups) { + layerGroup->update(); + } +} + +void LayerManager::reset(bool includeDisabled) { + for (auto& layerGroup : _layerGroups) { + for (auto layer : layerGroup->layers()) { + if (layer->enabled() || includeDisabled) { + layer->tileProvider()->reset(); + } + } + } +} + +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/rendering/layermanager.h b/modules/globebrowsing/rendering/layermanager.h new file mode 100644 index 0000000000..71963643a0 --- /dev/null +++ b/modules/globebrowsing/rendering/layermanager.h @@ -0,0 +1,132 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___LAYERMANAGER___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___LAYERMANAGER___H__ + +#include + +#include + +#include +#include + +namespace openspace { +namespace globebrowsing { + +class TileProvider; + +struct LayerRenderSettings : public properties::PropertyOwner { + LayerRenderSettings(); + properties::FloatProperty opacity; + properties::FloatProperty gamma; + properties::FloatProperty multiplier; +}; + +/** + * Simple struct which is used to enable/disable TileProvider + * and associate is with a name. It also holds layer specific information + * which is used in rendering of layer. + */ +class Layer : public properties::PropertyOwner { +public: + Layer(const ghoul::Dictionary& layerDict); + + ChunkTilePile getChunkTilePile(const TileIndex& tileIndex, int pileSize) const; + + bool enabled() const { return _enabled.value(); } + TileProvider* tileProvider() const { return _tileProvider.get(); } + const LayerRenderSettings& renderSettings() const { return _renderSettings; } + +private: + properties::BoolProperty _enabled; + std::shared_ptr _tileProvider; + LayerRenderSettings _renderSettings; +}; + +/** + * Convenience class for dealing with multiple Layers. + */ +struct LayerGroup : public properties::PropertyOwner { + LayerGroup(std::string name); + LayerGroup(std::string name, const ghoul::Dictionary& dict); + + /// Updates all layers tile providers within this group + void update(); + + /// @returns const vector of all layers + const std::vector>& layers() const; + + /// @returns const vector of all active layers + const std::vector>& activeLayers() const; + + /// @returns the size of the pile to be used in rendering of this layer + int pileSize() const; + + bool layerBlendingEnabled() const { return _levelBlendingEnabled.value(); } + +private: + std::vector> _layers; + std::vector> _activeLayers; + + properties::BoolProperty _levelBlendingEnabled; +}; + +/** + * Manages multiple LayerGroups. + */ +class LayerManager : public properties::PropertyOwner { +public: + static const size_t NUM_LAYER_GROUPS = 7; + static const char* LAYER_GROUP_NAMES[NUM_LAYER_GROUPS]; + enum LayerGroupId { + HeightLayers, + ColorLayers, + ColorOverlays, + GrayScaleLayers, + GrayScaleColorOverlays, + NightLayers, + WaterMasks + }; + + LayerManager(const ghoul::Dictionary& textureCategoriesDictionary); + + const LayerGroup& layerGroup(size_t groupId); + const LayerGroup& layerGroup(LayerGroupId); + + bool hasAnyBlendingLayersEnabled() const; + + const std::vector>& layerGroups() const; + + void update(); + void reset(bool includingDisabled = false); + +private: + std::vector> _layerGroups; +}; + +} // namespace globebrowsing +} // namespace openspace + +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___LAYERMANAGER___H__ diff --git a/modules/globebrowsing/rendering/layershadermanager.cpp b/modules/globebrowsing/rendering/layershadermanager.cpp new file mode 100644 index 0000000000..f43b73068a --- /dev/null +++ b/modules/globebrowsing/rendering/layershadermanager.cpp @@ -0,0 +1,140 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include + +#include + +namespace openspace { +namespace globebrowsing { + +bool LayerGroupPreprocessingData::operator==( + const LayerGroupPreprocessingData& other) const { + return lastLayerIdx == other.lastLayerIdx && + layerBlendingEnabled == other.layerBlendingEnabled; +} + +bool LayerShaderPreprocessingData::operator==( + const LayerShaderPreprocessingData& other) const { + if (layeredTextureInfo.size() != other.layeredTextureInfo.size() || + keyValuePairs.size() != other.keyValuePairs.size()) { + return false; + } + else { + bool equal = true; + for (size_t i = 0; i < layeredTextureInfo.size(); i++) { + equal &= (layeredTextureInfo[i] == other.layeredTextureInfo[i]); + } + for (size_t i = 0; i < keyValuePairs.size(); i++) { + equal &= (keyValuePairs[i] == other.keyValuePairs[i]); + } + return equal; + } +} + +LayerShaderManager::LayerShaderManager(const std::string& shaderName, + const std::string& vsPath, + const std::string& fsPath) + : _shaderName(shaderName) + , _vsPath(vsPath) + , _fsPath(fsPath) + , _updatedOnLastCall(false) +{} + +LayerShaderManager::~LayerShaderManager() { + if (_programObject) { + RenderEngine& renderEngine = OsEng.renderEngine(); + renderEngine.removeRenderProgram(_programObject); + _programObject = nullptr; + } +} + +ProgramObject* LayerShaderManager::programObject( + LayerShaderPreprocessingData preprocessingData) +{ + _updatedOnLastCall = false; + if (!(preprocessingData == _preprocessingData) || _programObject == nullptr) { + recompileShaderProgram(preprocessingData); + _updatedOnLastCall = true; + } + return _programObject.get(); +} + +void LayerShaderManager::recompileShaderProgram( + LayerShaderPreprocessingData preprocessingData) +{ + _preprocessingData = preprocessingData; + ghoul::Dictionary shaderDictionary; + + // Different layer types can be height layers or color layers for example. + // These are used differently within the shaders. + auto textureTypes = _preprocessingData.layeredTextureInfo; + for (size_t i = 0; i < textureTypes.size(); i++) { + // lastLayerIndex must be at least 0 for the shader to compile, + // the layer type is inactivated by setting use to false + std::string groupName = LayerManager::LAYER_GROUP_NAMES[i]; + shaderDictionary.setValue( + "lastLayerIndex" + groupName, + glm::max(textureTypes[i].lastLayerIdx, 0) + ); + shaderDictionary.setValue( + "use" + groupName, + textureTypes[i].lastLayerIdx >= 0 + ); + shaderDictionary.setValue( + "blend" + groupName, + textureTypes[i].layerBlendingEnabled + ); + } + + // Other settings such as "useAtmosphere" + auto keyValuePairs = _preprocessingData.keyValuePairs; + for (size_t i = 0; i < keyValuePairs.size(); i++) { + shaderDictionary.setValue(keyValuePairs[i].first, keyValuePairs[i].second); + } + + // Remove old program + OsEng.renderEngine().removeRenderProgram(_programObject); + + _programObject = OsEng.renderEngine().buildRenderProgram( + _shaderName, + _vsPath, + _fsPath, + shaderDictionary + ); + + ghoul_assert(_programObject != nullptr, "Failed to initialize programObject!"); + using IgnoreError = ProgramObject::IgnoreError; + _programObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); +} + +bool LayerShaderManager::updatedOnLastCall() { + return _updatedOnLastCall; +} + +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/rendering/layershadermanager.h b/modules/globebrowsing/rendering/layershadermanager.h new file mode 100644 index 0000000000..4138bdd55b --- /dev/null +++ b/modules/globebrowsing/rendering/layershadermanager.h @@ -0,0 +1,107 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___LAYER_SHADER_MANAGER___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___LAYER_SHADER_MANAGER___H__ + +#include + +#include +#include + +namespace ghoul { +namespace opengl { +class ProgramObject; +} +} +namespace openspace { +namespace globebrowsing { + +/** + * Settings per texture group that contains shader preprocessing information. + */ +struct LayerGroupPreprocessingData { + int lastLayerIdx; + bool layerBlendingEnabled; + bool operator==(const LayerGroupPreprocessingData& other) const; +}; + +/** + * Data needed for shader preprocessing before compiling a layered texture shader + * program. + * + * If a LayerShaderPreprocessingData is compared with another it can + * be determined wheter or not a LayerShaderManager needs to + * recompile its shader program. For each TextureGroup there is + * information about how many layers it has and whether or not to blend the texture + * levels. + */ +struct LayerShaderPreprocessingData { + std::array + layeredTextureInfo; + std::vector > keyValuePairs; + bool operator==(const LayerShaderPreprocessingData& other) const; +}; + +/** + * This class has ownership of an updated shader program for rendering tiles. + */ +class LayerShaderManager { +public: + LayerShaderManager( + const std::string& shaderName, + const std::string& vsPath, + const std::string& fsPath); + ~LayerShaderManager(); + + /** + * Returns a pointer to a ProgramObject for rendering tiles. + * \param preprocessingData determines wherer or not the shader + * program needs to be re-compiled. If preprocessingData is different + * from the last time this function was called the shader program will be + * recompiled before returned. + */ + ProgramObject* programObject( + LayerShaderPreprocessingData preprocessingData); + + bool updatedOnLastCall(); + +private: + + void recompileShaderProgram(LayerShaderPreprocessingData preprocessingData); + + std::unique_ptr _programObject; + LayerShaderPreprocessingData _preprocessingData; + + const std::string _shaderName; + const std::string _vsPath; + const std::string _fsPath; + + bool _updatedOnLastCall; +}; + +} // namespace globebrowsing +} // namespace openspace + +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___LAYER_SHADER_MANAGER___H__ diff --git a/modules/globebrowsing/shaders/globalchunkedlodpatch_fs.glsl b/modules/globebrowsing/shaders/globalchunkedlodpatch_fs.glsl index 9a90381e25..9b1764e690 100644 --- a/modules/globebrowsing/shaders/globalchunkedlodpatch_fs.glsl +++ b/modules/globebrowsing/shaders/globalchunkedlodpatch_fs.glsl @@ -30,7 +30,7 @@ Fragment getFragment() { frag.color = getTileFragColor(); #if SHOW_CHUNK_EDGES - frag.color += patchBorderOverlay(fs_uv, vec3(0,1,0), 0.005); + frag.color += patchBorderOverlay(fs_uv, vec3(0,1,0), 0.02); #endif // SHOW_CHUNK_EDGES frag.depth = fs_position.w; diff --git a/modules/globebrowsing/shaders/globalchunkedlodpatch_vs.glsl b/modules/globebrowsing/shaders/globalchunkedlodpatch_vs.glsl index e30636cd03..f9aefe6daf 100644 --- a/modules/globebrowsing/shaders/globalchunkedlodpatch_vs.glsl +++ b/modules/globebrowsing/shaders/globalchunkedlodpatch_vs.glsl @@ -37,6 +37,7 @@ uniform vec3 radiiSquared; uniform vec2 minLatLon; uniform vec2 lonLatScalingFactor; uniform vec3 cameraPosition; +uniform float chunkMinHeight; layout(location = 1) in vec2 in_uv; @@ -56,9 +57,14 @@ PositionNormalPair globalInterpolation() { void main() { PositionNormalPair pair = globalInterpolation(); - float distToVertexOnEllipsoid = length(pair.position - cameraPosition); + float distToVertexOnEllipsoid = + length(pair.position + pair.normal * chunkMinHeight - cameraPosition); - float levelInterpolationParameter = getLevelInterpolationParameter(chunkLevel, distanceScaleFactor, distToVertexOnEllipsoid); + float levelInterpolationParameter = + getLevelInterpolationParameter( + chunkLevel, + distanceScaleFactor, + distToVertexOnEllipsoid); // use level weight for height sampling, and output to fragment shader levelWeights = getLevelWeights(levelInterpolationParameter); diff --git a/modules/globebrowsing/shaders/localchunkedlodpatch_vs.glsl b/modules/globebrowsing/shaders/localchunkedlodpatch_vs.glsl index 14e26c22a2..901c2c3b67 100644 --- a/modules/globebrowsing/shaders/localchunkedlodpatch_vs.glsl +++ b/modules/globebrowsing/shaders/localchunkedlodpatch_vs.glsl @@ -39,6 +39,7 @@ uniform vec3 p10; uniform vec3 p01; uniform vec3 p11; uniform vec3 patchNormalCameraSpace; +uniform float chunkMinHeight; layout(location = 1) in vec2 in_uv; @@ -62,9 +63,14 @@ void main() { // Calculate desired level based on distance to the vertex on the ellipsoid // Before any heightmapping is done - float distToVertexOnEllipsoid = length(p); - float levelInterpolationParameter = getLevelInterpolationParameter(chunkLevel, distanceScaleFactor, distToVertexOnEllipsoid); - + float distToVertexOnEllipsoid = + length(p + patchNormalCameraSpace * chunkMinHeight); + float levelInterpolationParameter = + getLevelInterpolationParameter( + chunkLevel, + distanceScaleFactor, + distToVertexOnEllipsoid); + // use level weight for height sampling, and output to fragment shader levelWeights = getLevelWeights(levelInterpolationParameter); diff --git a/modules/base/shaders/deltaS_sup_calc_fs.glsl b/modules/globebrowsing/shaders/pointglobe_fs.glsl similarity index 73% rename from modules/base/shaders/deltaS_sup_calc_fs.glsl rename to modules/globebrowsing/shaders/pointglobe_fs.glsl index 68c6d6fe89..539f2bacb3 100644 --- a/modules/base/shaders/deltaS_sup_calc_fs.glsl +++ b/modules/globebrowsing/shaders/pointglobe_fs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * Copyright (c) 2014 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -21,34 +21,34 @@ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ - -#include "atmosphere_common.glsl" + #include "fragment.glsl" -#include "PowerScaling/powerScalingMath.hglsl" -layout(location = 1) out vec4 renderTarget1; +uniform vec3 directionToSunViewSpace; +uniform vec3 positionCameraSpace; -uniform int layer; - -uniform sampler3D deltaSTexture; - -// Rayleigh phase -float phaseFunctionR(const float mu) { - return (3.0 / (16.0 * M_PI)) * (1.0 + mu * mu); -} +in vec4 vs_positionClipSpace; Fragment getFragment() { - float x = gl_FragCoord.x - 0.5; - float y = gl_FragCoord.y - 0.5; - float nu = -1.0 + floor(x / float(RES_MU_S)) / (float(RES_NU) - 1.0) * 2.0; - vec3 uvw = vec3(gl_FragCoord.xy, float(layer) + 0.5) / vec3(ivec3(RES_MU_S * RES_NU, RES_MU, RES_R)); + vec2 pointCoord = (gl_PointCoord.xy - vec2(0.5)) * 2; + pointCoord.y = -pointCoord.y; // y should point up in cam space + if(length(pointCoord) > 1) // Outside of circle radius? + discard; + + // z_coord of sphere + float zCoord = sqrt(1 - pow(length(pointCoord),2)); + + // Light calculations + vec3 normal = normalize(vec3(pointCoord, zCoord)); + float cosTerm = max(dot(directionToSunViewSpace, normal), 0); + + vec3 color = vec3(1,1,1) * 0.7; + vec3 shadedColor = cosTerm * color; - renderTarget1 = vec4(texture(deltaSTexture, uvw).rgb / phaseFunctionR(nu), 1.0); - Fragment frag; - frag.color = vec4(1.0); - frag.depth = 1.0; - + frag.color = vec4(shadedColor,1); + frag.depth = vs_positionClipSpace.w; return frag; -} \ No newline at end of file +} + diff --git a/modules/base/shaders/renderabletrailnew_vs.glsl b/modules/globebrowsing/shaders/pointglobe_vs.glsl similarity index 70% rename from modules/base/shaders/renderabletrailnew_vs.glsl rename to modules/globebrowsing/shaders/pointglobe_vs.glsl index c4bff29a34..041d021d01 100644 --- a/modules/base/shaders/renderabletrailnew_vs.glsl +++ b/modules/globebrowsing/shaders/pointglobe_vs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * Copyright (c) 2014 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -24,35 +24,31 @@ #version __CONTEXT__ -// Attributes -layout(location = 0) in vec3 in_position; - -// Uniforms -uniform mat4 modelViewProjectionTransform; - -uniform int numVertices; -uniform int maxNumVertices; -uniform int subSamples; -uniform float lineFade; -uniform int vertexIDPadding; -uniform float pointSize; - -// Outputs -out vec4 vs_positionScreenSpace; -out float vs_alpha; - #include "PowerScaling/powerScaling_vs.hglsl" +layout(location = 0) in vec3 in_position; + +uniform int windowWidth; +uniform float globeRadius; +uniform mat4 modelViewTransform; +uniform mat4 projectionTransform; +uniform mat4 directionToSunViewSpace; + +out vec4 vs_positionClipSpace; +out vec4 vs_positionCameraSpace; + void main() { - int vertexID = gl_VertexID + vertexIDPadding; - int threshHold = int(lineFade * numVertices); - int nVisibleVertices = min((int(numVertices) - threshHold), maxNumVertices); - vs_alpha = clamp((vertexID - (int(numVertices) - nVisibleVertices)) - / float(nVisibleVertices), 0, 1); + vec4 positionCameraSpace = modelViewTransform * vec4(in_position, 1); + vs_positionClipSpace = projectionTransform * positionCameraSpace; - vec4 positionClipSpace = modelViewProjectionTransform * vec4(in_position, 1); - vs_positionScreenSpace = z_normalization(positionClipSpace); + vs_positionClipSpace = z_normalization(vs_positionClipSpace); - gl_PointSize = (subSamples == 0 || vertexID % subSamples == 0) ? pointSize : pointSize / 2; - gl_Position = vs_positionScreenSpace; + vec4 pointSizeCameraSpace = modelViewTransform * vec4(0,0, in_position.z, 1); + pointSizeCameraSpace.x = globeRadius; + pointSizeCameraSpace.y = globeRadius; + vec4 pointSizeClipSpace = projectionTransform * pointSizeCameraSpace; + vec4 pointSizeNDC = pointSizeClipSpace / pointSizeClipSpace.w; + + gl_PointSize = pointSizeNDC.x * 2 * windowWidth; + gl_Position = vs_positionClipSpace; } \ No newline at end of file diff --git a/modules/globebrowsing/shaders/texturetilemapping.hglsl b/modules/globebrowsing/shaders/texturetilemapping.hglsl index 176d861cb6..ffc8e8ebf8 100644 --- a/modules/globebrowsing/shaders/texturetilemapping.hglsl +++ b/modules/globebrowsing/shaders/texturetilemapping.hglsl @@ -28,52 +28,75 @@ #include <${MODULE_GLOBEBROWSING}/shaders/tile.hglsl> #include <${MODULE_GLOBEBROWSING}/shaders/blending.hglsl> -// First layer type from LayeredTextureShaderProvider is height map -#define NUMLAYERS_HEIGHTMAP #{lastLayerIndexHeightMaps} + 1 -#define USE_HEIGHTMAP #{useHeightMaps} -#define HEIGHTMAP_BLENDING_ENABLED #{blendHeightMaps} +// First layer type from LayerShaderManager is height map +#define NUMLAYERS_HEIGHTMAP #{lastLayerIndexHeightLayers} + 1 +#define USE_HEIGHTMAP #{useHeightLayers} +#define HEIGHTMAP_BLENDING_ENABLED #{blendHeightLayers} -// Second layer type from LayeredTextureShaderProvider is color texture -#define NUMLAYERS_COLORTEXTURE #{lastLayerIndexColorTextures} + 1 -#define USE_COLORTEXTURE #{useColorTextures} -#define COLORTEXTURE_BLENDING_ENABLED #{blendColorTextures} +// Second layer type from LayerShaderManager is color texture +#define NUMLAYERS_COLORTEXTURE #{lastLayerIndexColorLayers} + 1 +#define USE_COLORTEXTURE #{useColorLayers} +#define COLORTEXTURE_BLENDING_ENABLED #{blendColorLayers} - // Third layer type from LayeredTextureShaderProvider is water mask +#define NUMLAYERS_GRAYSCALETEXTURE #{lastLayerIndexGrayScaleLayers} + 1 +#define USE_GRAYSCALETEXTURE #{useGrayScaleLayers} +#define GRAYSCALETEXTURE_BLENDING_ENABLED #{blendGrayScaleLayers} + + // Third layer type from LayerShaderManager is water mask #define NUMLAYERS_WATERMASK #{lastLayerIndexWaterMasks} + 1 #define USE_WATERMASK #{useWaterMasks} #define WATERMASK_BLENDING_ENABLED #{blendWaterMasks} -// Fourth layer type from LayeredTextureShaderProvider is night texture -#define NUMLAYERS_NIGHTTEXTURE #{lastLayerIndexNightTextures} + 1 -#define USE_NIGHTTEXTURE #{useNightTextures} -#define NIGHTTEXTURE_BLENDING_ENABLED #{blendNightTextures} +// Fourth layer type from LayerShaderManager is night texture +#define NUMLAYERS_NIGHTTEXTURE #{lastLayerIndexNightLayers} + 1 +#define USE_NIGHTTEXTURE #{useNightLayers} +#define NIGHTTEXTURE_BLENDING_ENABLED #{blendNightLayers} -// Fifth layer type from LayeredTextureShaderProvider is overlay -#define NUMLAYERS_OVERLAY #{lastLayerIndexOverlays} + 1 -#define USE_OVERLAY #{useOverlays} -#define OVERLAY_BLENDING_ENABLED #{blendOverlays} +// Fifth layer type from LayerShaderManager is overlay +#define NUMLAYERS_OVERLAY #{lastLayerIndexColorOverlays} + 1 +#define USE_OVERLAY #{useColorOverlays} +#define OVERLAY_BLENDING_ENABLED #{blendColorOverlays} -// Sixth layer type from LayeredTextureShaderProvider is grayscale overlay -#define NUMLAYERS_GRAYSCALE_OVERLAY #{lastLayerIndexGrayScaleOverlays} + 1 -#define USE_GRAYSCALE_OVERLAY #{useGrayScaleOverlays} -#define GRAYSCALE_OVERLAY_BLENDING_ENABLED #{blendGrayScaleOverlays} +// Sixth layer type from LayerShaderManager is grayscale overlay +#define NUMLAYERS_GRAYSCALE_OVERLAY #{lastLayerIndexGrayScaleColorOverlays} + 1 +#define USE_GRAYSCALE_OVERLAY #{useGrayScaleColorOverlays} +#define GRAYSCALE_OVERLAY_BLENDING_ENABLED #{blendGrayScaleColorOverlays} // Global constants #define CHUNK_DEFAULT_HEIGHT #{defaultHeight} // Other key value pairs used for settings #define USE_ATMOSPHERE #{useAtmosphere} +#define PERFORM_SHADING #{performShading} #define SHOW_CHUNK_EDGES #{showChunkEdges} #define SHOW_HEIGHT_RESOLUTION #{showHeightResolution} #define SHOW_HEIGHT_INTENSITIES #{showHeightIntensities} +float performLayerSettings(float currentValue, const LayerSettings settings) { + float newValue = currentValue; + + newValue = sign(newValue) * pow(abs(newValue), settings.gamma); + newValue = newValue * settings.multiplier; + newValue = newValue * settings.opacity; + + return newValue; +} + + +vec4 performLayerSettings(vec4 currentValue, const LayerSettings settings) { + vec4 newValue = vec4( + performLayerSettings(currentValue.r, settings), + performLayerSettings(currentValue.g, settings), + performLayerSettings(currentValue.b, settings), + performLayerSettings(currentValue.a, settings)); + + return newValue; +} float calculateUntransformedHeight( vec2 uv, LevelWeights levelWeights, - const Tile heightTiles[NUMLAYERS_HEIGHTMAP], - const Tile heightTilesParent1[NUMLAYERS_HEIGHTMAP], - const Tile heightTilesParent2[NUMLAYERS_HEIGHTMAP]) { + const Layer HeightTextures[NUMLAYERS_HEIGHTMAP]) { float height = 0; @@ -84,12 +107,11 @@ float calculateUntransformedHeight( #endif // HEIGHTMAP_BLENDING_ENABLED - #for i in 0..#{lastLayerIndexHeightMaps} + #for i in 0..#{lastLayerIndexHeightLayers} { - height = - levelWeights.w1 * getTexVal(heightTiles[#{i}], uv).r + - levelWeights.w2 * getTexVal(heightTilesParent1[#{i}], uv).r + - levelWeights.w3 * getTexVal(heightTilesParent2[#{i}], uv).r; + height = getTexVal(HeightTextures[#{i}].pile, levelWeights, uv).r; + + height = performLayerSettings(height, HeightTextures[#{i}].settings); } #endfor return height; @@ -98,9 +120,7 @@ float calculateUntransformedHeight( float calculateHeight( vec2 uv, LevelWeights levelWeights, - const Tile heightTiles[NUMLAYERS_HEIGHTMAP], - const Tile heightTilesParent1[NUMLAYERS_HEIGHTMAP], - const Tile heightTilesParent2[NUMLAYERS_HEIGHTMAP]) { + const Layer HeightTextures[NUMLAYERS_HEIGHTMAP]) { float height = 0; @@ -109,18 +129,17 @@ float calculateHeight( #if !HEIGHTMAP_BLENDING_ENABLED levelWeights = getDefaultLevelWeights(); #endif // HEIGHTMAP_BLENDING_ENABLED - - - #for i in 0..#{lastLayerIndexHeightMaps} - { - float untransformedHeight = - levelWeights.w1 * getTexVal(heightTiles[#{i}], uv).r + - levelWeights.w2 * getTexVal(heightTilesParent1[#{i}], uv).r + - levelWeights.w3 * getTexVal(heightTilesParent2[#{i}], uv).r; - float heightSample = getTransformedTexVal(heightTiles[#{i}].depthTransform, untransformedHeight); - if (heightSample > -100000) + + #for i in 0..#{lastLayerIndexHeightLayers} + { + float untransformedHeight = getTexVal(HeightTextures[#{i}].pile, levelWeights, uv).r; + + float heightSample = getTransformedTexVal(HeightTextures[#{i}].depthTransform, untransformedHeight); + if (heightSample > -100000) { + heightSample = performLayerSettings(heightSample, HeightTextures[#{i}].settings); height = heightSample; + } } #endfor return height; @@ -129,9 +148,7 @@ float calculateHeight( vec4 calculateColor( const vec2 uv, LevelWeights levelWeights, - const Tile colorTiles[NUMLAYERS_COLORTEXTURE], - const Tile colorTilesParent1[NUMLAYERS_COLORTEXTURE], - const Tile colorTilesParent2[NUMLAYERS_COLORTEXTURE]) { + const Layer ColorLayers[NUMLAYERS_COLORTEXTURE]) { vec4 color = vec4(0); @@ -141,12 +158,11 @@ vec4 calculateColor( levelWeights = getDefaultLevelWeights(); #endif // COLORTEXTURE_BLENDING_ENABLED - #for i in 0..#{lastLayerIndexColorTextures} + #for i in 0..#{lastLayerIndexColorLayers} { - vec4 colorSample = - levelWeights.w1 * getTexVal(colorTiles[#{i}], uv) + - levelWeights.w2 * getTexVal(colorTilesParent1[#{i}], uv) + - levelWeights.w3 * getTexVal(colorTilesParent2[#{i}], uv); + vec4 colorSample = getTexVal(ColorLayers[#{i}].pile, levelWeights, uv); + + colorSample = performLayerSettings(colorSample, ColorLayers[#{i}].settings); color = blendOver(color, colorSample); } @@ -155,6 +171,34 @@ vec4 calculateColor( return color; } +vec4 calculateGrayScale( + const vec4 currentColor, + const vec2 uv, + LevelWeights levelWeights, + const Layer GrayScaleLayers[NUMLAYERS_GRAYSCALETEXTURE]) { + + vec4 colorGrayScale = currentColor; + + // The shader compiler will remove unused code when variables are multiplied by + // a constant 0 +#if !GRAYSCALETEXTURE_BLENDING_ENABLED + levelWeights = getDefaultLevelWeights(); +#endif // GRAYSCALE_OVERLAY_BLENDING_ENABLED + + #for i in 0..#{lastLayerIndexGrayScaleLayers} + { + vec4 colorSample = getTexVal(GrayScaleLayers[#{i}].pile, levelWeights, uv); + + colorSample = vec4(colorSample.r, colorSample.r, colorSample.r, 1); + colorSample = performLayerSettings(colorSample, GrayScaleLayers[#{i}].settings); + + colorGrayScale = blendOver(colorGrayScale, colorSample); + } + #endfor + + return colorGrayScale; +} + float gridDots(vec2 uv, vec2 gridResolution){ vec2 uvVertexSpace = fract((gridResolution) * uv) + 0.5; @@ -171,9 +215,9 @@ vec4 calculateDebugColor(vec2 uv, vec4 fragPos, vec2 vertexResolution){ return vec4(0.5 * colorSum, 1); } -float tileResolution(vec2 tileUV, const Tile tile){ - vec2 heightResolution = textureSize(tile.textureSampler, 0); - vec2 uv = TileUVToTextureSamplePosition(tile, tileUV); +float tileResolution(vec2 tileUV, const ChunkTile chunkTile){ + vec2 heightResolution = textureSize(chunkTile.textureSampler, 0); + vec2 uv = TileUVToTextureSamplePosition(chunkTile, tileUV); return gridDots(uv, heightResolution); } @@ -182,9 +226,7 @@ vec4 calculateNight( const vec4 currentColor, const vec2 uv, LevelWeights levelWeights, - const Tile nightTiles[NUMLAYERS_NIGHTTEXTURE], - const Tile nightTilesParent1[NUMLAYERS_NIGHTTEXTURE], - const Tile nightTilesParent2[NUMLAYERS_NIGHTTEXTURE], + const Layer NightLayers[NUMLAYERS_NIGHTTEXTURE], const vec3 ellipsoidNormalCameraSpace, const vec3 lightDirectionCameraSpace) { @@ -196,24 +238,41 @@ vec4 calculateNight( levelWeights = getDefaultLevelWeights(); #endif // NIGHTTEXTURE_BLENDING_ENABLED - #for i in 0..#{lastLayerIndexNightTextures} + #for i in 0..#{lastLayerIndexNightLayers} { - vec4 colorSample = - levelWeights.w1 * getTexVal(nightTiles[#{i}], uv) + - levelWeights.w2 * getTexVal(nightTilesParent1[#{i}], uv) + - levelWeights.w3 * getTexVal(nightTilesParent2[#{i}], uv); + vec4 colorSample = getTexVal(NightLayers[#{i}].pile, levelWeights, uv); + colorSample = performLayerSettings(colorSample, NightLayers[#{i}].settings); nightColor = blendOver(nightColor, colorSample); } #endfor - //float cosineFactor = clamp(dot(-lightDirectionCameraSpace, ellipsoidNormalCameraSpace) * 3, 0, 1); - float shadowLight = 0.1; - float cosineFactor = clamp(dot(-lightDirectionCameraSpace, normalize(ellipsoidNormalCameraSpace)) * 3, -shadowLight, 1) + shadowLight; - - // Blend night color with base color - vec4 color = currentColor * 0.1 + 0.9 * vec4(cosineFactor * currentColor.xyz + (1 - cosineFactor) * vec3(nightColor * nightColor), currentColor.a); + vec3 n = normalize(ellipsoidNormalCameraSpace); + vec3 l = lightDirectionCameraSpace; + + float cosineFactor = clamp(dot(l, normalize(n + 0.15 * l)) * 3 , 0, 1); + + // Blend shaded color with base color + vec4 color = vec4(currentColor.rgb + (cosineFactor) * nightColor.xyz, currentColor.a); + + return color; +} + +vec4 calculateShadedColor( + const vec4 currentColor, + const vec3 ellipsoidNormalCameraSpace, + const vec3 lightDirectionCameraSpace) { + + vec3 shadedColor = currentColor.rgb * 0.05; + + vec3 n = normalize(ellipsoidNormalCameraSpace); + vec3 l = lightDirectionCameraSpace; + + float cosineFactor = pow(clamp(dot(-l, n), 0, 1), 0.8); + + // Blend shaded color with base color + vec4 color = vec4(cosineFactor * currentColor.xyz + (1 - cosineFactor) * shadedColor, currentColor.a); return color; } @@ -221,9 +280,7 @@ vec4 calculateOverlay( const vec4 currentColor, const vec2 uv, LevelWeights levelWeights, - const Tile overlayTiles[NUMLAYERS_OVERLAY], - const Tile overlayTilesParent1[NUMLAYERS_OVERLAY], - const Tile overlayTilesParent2[NUMLAYERS_OVERLAY]) { + const Layer ColorOverlays[NUMLAYERS_OVERLAY]) { vec4 color = currentColor; @@ -233,12 +290,10 @@ vec4 calculateOverlay( levelWeights = getDefaultLevelWeights(); #endif // OVERLAY_BLENDING_ENABLED - #for i in 0..#{lastLayerIndexOverlays} + #for i in 0..#{lastLayerIndexColorOverlays} { - vec4 colorSample = - levelWeights.w1 * getTexVal(overlayTiles[#{i}], uv) + - levelWeights.w2 * getTexVal(overlayTilesParent1[#{i}], uv) + - levelWeights.w3 * getTexVal(overlayTilesParent2[#{i}], uv); + vec4 colorSample = getTexVal(ColorOverlays[#{i}].pile, levelWeights, uv); + colorSample = performLayerSettings(colorSample, ColorOverlays[#{i}].settings); color = blendOver(color, colorSample); } @@ -251,9 +306,7 @@ vec4 calculateGrayScaleOverlay( const vec4 currentColor, const vec2 uv, LevelWeights levelWeights, - const Tile grayscaleOverlayTiles[NUMLAYERS_GRAYSCALE_OVERLAY], - const Tile grayscaleOverlayTilesParent1[NUMLAYERS_GRAYSCALE_OVERLAY], - const Tile grayscaleOverlayTilesParent2[NUMLAYERS_GRAYSCALE_OVERLAY]) { + const Layer GrayScaleColorOverlays[NUMLAYERS_GRAYSCALE_OVERLAY]) { vec4 colorGrayScale = currentColor; @@ -263,14 +316,13 @@ vec4 calculateGrayScaleOverlay( levelWeights = getDefaultLevelWeights(); #endif // GRAYSCALE_OVERLAY_BLENDING_ENABLED - #for i in 0..#{lastLayerIndexGrayScaleOverlays} + #for i in 0..#{lastLayerIndexGrayScaleColorOverlays} { - vec4 colorSample = - levelWeights.w1 * getTexVal(grayscaleOverlayTiles[#{i}], uv) + - levelWeights.w2 * getTexVal(grayscaleOverlayTilesParent1[#{i}], uv) + - levelWeights.w3 * getTexVal(grayscaleOverlayTilesParent2[#{i}], uv); + vec4 colorSample = getTexVal(GrayScaleColorOverlays[#{i}].pile, levelWeights, uv); colorSample = vec4(colorSample.r, colorSample.r, colorSample.r, colorSample.g); + colorSample = performLayerSettings(colorSample, GrayScaleColorOverlays[#{i}].settings); + colorGrayScale = blendOver(colorGrayScale, colorSample); } #endfor @@ -297,9 +349,7 @@ vec4 calculateWater( const vec4 currentColor, const vec2 uv, LevelWeights levelWeights, - const Tile waterTiles[NUMLAYERS_WATERMASK], - const Tile waterTilesParent1[NUMLAYERS_WATERMASK], - const Tile waterTilesParent2[NUMLAYERS_WATERMASK], + const Layer WaterMasks[NUMLAYERS_WATERMASK], const vec3 ellipsoidNormalCameraSpace, const vec3 lightDirectionCameraSpace, const vec3 positionCameraSpace) { @@ -314,10 +364,9 @@ vec4 calculateWater( #for i in 0..#{lastLayerIndexWaterMasks} { - vec4 colorSample = - levelWeights.w1 * getTexVal(waterTiles[#{i}], uv) + - levelWeights.w2 * getTexVal(waterTilesParent1[#{i}], uv) + - levelWeights.w3 * getTexVal(waterTilesParent2[#{i}], uv); + vec4 colorSample = getTexVal(WaterMasks[#{i}].pile, levelWeights, uv); + + colorSample = performLayerSettings(colorSample, WaterMasks[#{i}].settings); waterColor = blendOver(waterColor, colorSample); } @@ -326,7 +375,7 @@ vec4 calculateWater( vec3 directionToFragmentCameraSpace = normalize(positionCameraSpace - vec3(0, 0, 0)); vec3 reflectionDirectionCameraSpace = reflect(lightDirectionCameraSpace, ellipsoidNormalCameraSpace); float cosineFactor = clamp(dot(-reflectionDirectionCameraSpace, directionToFragmentCameraSpace), 0, 1); - cosineFactor = pow(cosineFactor, 30); + cosineFactor = pow(cosineFactor, 100); vec3 specularColor = vec3(1, 1, 1); float specularIntensity = 0.4; diff --git a/modules/globebrowsing/shaders/tile.hglsl b/modules/globebrowsing/shaders/tile.hglsl index cc91d50657..8f390c07ca 100644 --- a/modules/globebrowsing/shaders/tile.hglsl +++ b/modules/globebrowsing/shaders/tile.hglsl @@ -25,6 +25,12 @@ #ifndef TEXTURETILE_HGLSL #define TEXTURETILE_HGLSL +// Must match the values in tiledataset.cpp +// (could be set as shader preprocessing data so that multiple definitions +// are not needed) +#define TILE_PIXEL_START_OFFSET ivec2(-2) +#define TILE_PIXEL_SIZE_DIFFERENCE ivec2(4) + vec4 patchBorderOverlay(vec2 uv, vec3 borderColor, float borderSize) { vec2 uvOffset = uv - vec2(0.5); float thres = 0.5 - borderSize/2; @@ -35,7 +41,7 @@ vec4 patchBorderOverlay(vec2 uv, vec3 borderColor, float borderSize) { ///////////////////////////////////////////////////////////////////// -// Tile Depth Transform // +// ChunkTile Depth Transform // ///////////////////////////////////////////////////////////////////// struct TileDepthTransform { @@ -52,7 +58,7 @@ vec4 getTransformedTexVal(const TileDepthTransform transform, const vec4 val){ } ///////////////////////////////////////////////////////////////////// -// Tile UV Transform // +// ChunkTile UV Transform // ///////////////////////////////////////////////////////////////////// struct TileUvTransform { @@ -62,17 +68,15 @@ struct TileUvTransform { ///////////////////////////////////////////////////////////////////// -// Tile // +// ChunkTile // ///////////////////////////////////////////////////////////////////// -struct Tile { +struct ChunkTile { sampler2D textureSampler; - - TileDepthTransform depthTransform; TileUvTransform uvTransform; }; -vec2 compensateSourceTextureSampling(vec2 startOffset, vec2 sizeDiff, const Tile tile, vec2 tileUV){ - ivec2 resolution = textureSize(tile.textureSampler, 0); +vec2 compensateSourceTextureSampling(vec2 startOffset, vec2 sizeDiff, const ChunkTile chunkTile, vec2 tileUV){ + ivec2 resolution = textureSize(chunkTile.textureSampler, 0); vec2 sourceSize = vec2(resolution) + sizeDiff; vec2 currentSize = vec2(resolution); @@ -81,27 +85,39 @@ vec2 compensateSourceTextureSampling(vec2 startOffset, vec2 sizeDiff, const Tile return tileUV; } -vec2 TileUVToTextureSamplePosition(const Tile tile, vec2 tileUV){ - vec2 uv = tile.uvTransform.uvOffset + tile.uvTransform.uvScale * tileUV; - uv = compensateSourceTextureSampling(vec2(-2), vec2(4), tile, uv); +vec2 TileUVToTextureSamplePosition(const ChunkTile chunkTile, vec2 tileUV){ + vec2 uv = chunkTile.uvTransform.uvOffset + chunkTile.uvTransform.uvScale * tileUV; + uv = compensateSourceTextureSampling(vec2(-2), vec2(4), chunkTile, uv); return uv; } -vec4 getTexVal(const Tile tile, vec2 tileUV){ - vec2 samplePosition = TileUVToTextureSamplePosition(tile, tileUV); - vec4 texVal = texture(tile.textureSampler, samplePosition); +vec4 getTexVal(const ChunkTile chunkTile, vec2 tileUV){ + vec2 samplePosition = TileUVToTextureSamplePosition(chunkTile, tileUV); + vec4 texVal = texture(chunkTile.textureSampler, samplePosition); return texVal; } ///////////////////////////////////////////////////////////////////// -// Multi Level Tile // +// Chunk Tile Pile // ///////////////////////////////////////////////////////////////////// -struct MultiLevelTile { - Tile tile0; - Tile tile1; - Tile tile2; +struct ChunkTilePile { + ChunkTile chunkTile0; + ChunkTile chunkTile1; + ChunkTile chunkTile2; +}; + +struct LayerSettings { + float opacity; + float gamma; + float multiplier; +}; + +struct Layer { + ChunkTilePile pile; + TileDepthTransform depthTransform; + LayerSettings settings; }; struct LevelWeights { @@ -133,12 +149,11 @@ LevelWeights getDefaultLevelWeights(){ } -vec4 getTexVal(const MultiLevelTile multiLevelTile, const LevelWeights w, const vec2 uv){ - return w.w1 * getTexVal(multiLevelTile.tile0, uv) + - w.w2 * getTexVal(multiLevelTile.tile1, uv) + - w.w3 * getTexVal(multiLevelTile.tile2, uv); +vec4 getTexVal(const ChunkTilePile chunkTilePile, const LevelWeights w, const vec2 uv){ + return w.w1 * getTexVal(chunkTilePile.chunkTile0, uv) + + w.w2 * getTexVal(chunkTilePile.chunkTile1, uv) + + w.w3 * getTexVal(chunkTilePile.chunkTile2, uv); } - #endif // TEXTURETILE_HGLSL \ No newline at end of file diff --git a/modules/globebrowsing/shaders/tilefragcolor.hglsl b/modules/globebrowsing/shaders/tilefragcolor.hglsl index 028e2244a3..26fa48c32e 100644 --- a/modules/globebrowsing/shaders/tilefragcolor.hglsl +++ b/modules/globebrowsing/shaders/tilefragcolor.hglsl @@ -34,33 +34,27 @@ // the actual fragment color #if USE_COLORTEXTURE -uniform Tile ColorTextures[NUMLAYERS_COLORTEXTURE]; -uniform Tile ColorTexturesParent1[NUMLAYERS_COLORTEXTURE]; -uniform Tile ColorTexturesParent2[NUMLAYERS_COLORTEXTURE]; +uniform Layer ColorLayers[NUMLAYERS_COLORTEXTURE]; #endif // USE_COLORTEXTURE +#if USE_GRAYSCALETEXTURE +uniform Layer GrayScaleLayers[NUMLAYERS_GRAYSCALETEXTURE]; +#endif // USE_GRAYSCALETEXTURE + #if USE_NIGHTTEXTURE -uniform Tile NightTextures[NUMLAYERS_NIGHTTEXTURE]; -uniform Tile NightTexturesParent1[NUMLAYERS_NIGHTTEXTURE]; -uniform Tile NightTexturesParent2[NUMLAYERS_NIGHTTEXTURE]; +uniform Layer NightLayers[NUMLAYERS_NIGHTTEXTURE]; #endif // USE_NIGHTTEXTURE #if USE_OVERLAY -uniform Tile Overlays[NUMLAYERS_OVERLAY]; -uniform Tile OverlaysParent1[NUMLAYERS_OVERLAY]; -uniform Tile OverlaysParent2[NUMLAYERS_OVERLAY]; +uniform Layer ColorOverlays[NUMLAYERS_OVERLAY]; #endif // USE_OVERLAY #if USE_GRAYSCALE_OVERLAY -uniform Tile GrayScaleOverlays[NUMLAYERS_GRAYSCALE_OVERLAY]; -uniform Tile GrayScaleOverlaysParent1[NUMLAYERS_GRAYSCALE_OVERLAY]; -uniform Tile GrayScaleOverlaysParent2[NUMLAYERS_GRAYSCALE_OVERLAY]; +uniform Layer GrayScaleColorOverlays[NUMLAYERS_GRAYSCALE_OVERLAY]; #endif // USE_GRAYSCALE_OVERLAY #if USE_WATERMASK -uniform Tile WaterMasks[NUMLAYERS_WATERMASK]; -uniform Tile WaterMasksParent1[NUMLAYERS_WATERMASK]; -uniform Tile WaterMasksParent2[NUMLAYERS_WATERMASK]; +uniform Layer WaterMasks[NUMLAYERS_WATERMASK]; #endif // USE_WATERMASK #if SHOW_HEIGHT_RESOLUTION @@ -71,7 +65,7 @@ uniform vec2 vertexResolution; // TODO atmosphere uniforms here #endif // USE_ATMOSPHERE -#if USE_NIGHTTEXTURE || USE_WATERMASK +#if USE_NIGHTTEXTURE || USE_WATERMASK || USE_ATMOSPHERE || PERFORM_SHADING uniform vec3 lightDirectionCameraSpace; #endif @@ -86,16 +80,13 @@ in vec3 positionCameraSpace; in LevelWeights levelWeights; - ///////////////////////////////////////////////////////////////////// // The heightmaps is only used in the fragment shader visually debugging // the alignment and resolution of the heightmaps #if USE_HEIGHTMAP -uniform Tile HeightMaps[NUMLAYERS_HEIGHTMAP]; -uniform Tile HeightMapsParent1[NUMLAYERS_HEIGHTMAP]; -uniform Tile HeightMapsParent2[NUMLAYERS_HEIGHTMAP]; +uniform Layer HeightLayers[NUMLAYERS_HEIGHTMAP]; #endif // USE_HEIGHTMAP float getUntransformedTileVertexHeight(vec2 uv, LevelWeights levelWeights){ @@ -107,7 +98,7 @@ float getUntransformedTileVertexHeight(vec2 uv, LevelWeights levelWeights){ height = calculateUntransformedHeight( uv, levelWeights, // Variable to determine which texture to sample from - HeightMaps, HeightMapsParent1, HeightMapsParent2); // Three textures to sample from + HeightLayers); // Three textures to sample from #endif // USE_HEIGHTMAP @@ -133,11 +124,16 @@ vec4 getTileFragColor(){ color = calculateColor( fs_uv, levelWeights, - ColorTextures, - ColorTexturesParent1, - ColorTexturesParent2); + ColorLayers); #endif // USE_COLORTEXTURE +#if USE_GRAYSCALETEXTURE + color = calculateGrayScale( + color, + fs_uv, + levelWeights, + GrayScaleLayers); +#endif // USE_GRAYSCALETEXTURE #if USE_GRAYSCALE_OVERLAY @@ -145,9 +141,7 @@ vec4 getTileFragColor(){ color, fs_uv, levelWeights, - GrayScaleOverlays, - GrayScaleOverlaysParent1, - GrayScaleOverlaysParent2); + GrayScaleColorOverlays); #endif // USE_COLORTEXTURE @@ -157,8 +151,6 @@ vec4 getTileFragColor(){ fs_uv, levelWeights, WaterMasks, - WaterMasksParent1, - WaterMasksParent2, normalize(ellipsoidNormalCameraSpace), lightDirectionCameraSpace, // Should already be normalized positionCameraSpace); @@ -170,30 +162,39 @@ vec4 getTileFragColor(){ color, fs_uv, levelWeights, - NightTextures, - NightTexturesParent1, - NightTexturesParent2, + NightLayers, normalize(ellipsoidNormalCameraSpace), lightDirectionCameraSpace); // Should already be normalized #endif // USE_NIGHTTEXTURE +#if PERFORM_SHADING + color = calculateShadedColor( + color, + normalize(ellipsoidNormalCameraSpace), + lightDirectionCameraSpace); +#endif // PERFORM_SHADING + #if USE_ATMOSPHERE // Temporary until the real atmosphere code is here //color = color + vec4(0.5,0.5,1,0) * 0.3; // Just to see something for now vec3 n = normalize(ellipsoidNormalCameraSpace); vec3 l = lightDirectionCameraSpace; vec3 c = normalize(positionCameraSpace); - float cosFactor = clamp(dot(-n * 0.9, c), 0, 1); - float shadowLight = 0.3; - float cosFactorLight = max(dot(-l, n), -shadowLight) + shadowLight; - float cosFactorScatter = max(dot(l, n) + shadowLight, 0); + float cosFactor = 1 - clamp(dot(-n * 0.9, c), 0, 1); + cosFactor *= 1.1; + cosFactor -= 0.1; + cosFactor = clamp(cosFactor, 0, 1); + cosFactor = cosFactor + pow(cosFactor, 5); + + float shadowLight = 0.15; + float cosFactorLight = pow(max(dot(-l, n), -shadowLight) + shadowLight, 0.8); + //float cosFactorScatter = pow(max(dot(l, n) + shadowLight, 0), 5); //float cosFactorLight = max(dot(-lightDirectionCameraSpace, normalize(ellipsoidNormalCameraSpace)), 0); - vec3 r = reflect(l, n); - float scatteredLight = pow(clamp(dot(-r,c), 0, 1), 20); - vec3 atmosphereColor = vec3(0.2,0.2,1) * (1 - (cosFactorScatter + scatteredLight)) + (cosFactorScatter + scatteredLight) * vec3(1,0.2,0.2); - color = color + vec4(atmosphereColor,0) * (1 - cosFactor) * cosFactorLight * 0.5; - + //vec3 r = reflect(l, n); + //float scatteredLight = pow(clamp(dot(-r,c), 0, 1), 20); + vec3 atmosphereColor = vec3(0.5,0.5,1) * 2; + color = color + vec4(atmosphereColor,0) * cosFactor * cosFactorLight * 0.5; #endif // USE_ATMOSPHERE #if USE_OVERLAY @@ -201,10 +202,7 @@ vec4 getTileFragColor(){ color, fs_uv, levelWeights, - Overlays, - OverlaysParent1, - OverlaysParent2); - + ColorOverlays); #endif // USE_OVERLAY @@ -225,10 +223,11 @@ vec4 getTileFragColor(){ color += 0.0001*calculateDebugColor(fs_uv, fs_position, vertexResolution); #if USE_HEIGHTMAP color.r = min(color.r, 0.8); - color.r += tileResolution(fs_uv, HeightMaps[0]) > 0.9 ? 1 : 0; + color.r += tileResolution(fs_uv, HeightLayers[0].pile.chunkTile0) > 0.9 ? 1 : 0; #endif #endif + return color; } diff --git a/modules/globebrowsing/shaders/tilevertexheight.hglsl b/modules/globebrowsing/shaders/tilevertexheight.hglsl index 6ea6003dcc..ac4e4d4bf1 100644 --- a/modules/globebrowsing/shaders/tilevertexheight.hglsl +++ b/modules/globebrowsing/shaders/tilevertexheight.hglsl @@ -31,9 +31,7 @@ #if USE_HEIGHTMAP -uniform Tile HeightMaps[NUMLAYERS_HEIGHTMAP]; -uniform Tile HeightMapsParent1[NUMLAYERS_HEIGHTMAP]; -uniform Tile HeightMapsParent2[NUMLAYERS_HEIGHTMAP]; +uniform Layer HeightLayers[NUMLAYERS_HEIGHTMAP]; #endif // USE_HEIGHTMAP uniform int xSegments; @@ -52,7 +50,7 @@ float getUntransformedTileVertexHeight(vec2 uv, LevelWeights levelWeights){ height = calculateUntransformedHeight( uv, levelWeights, // Variable to determine which texture to sample from - HeightMaps, HeightMapsParent1, HeightMapsParent2); // Three textures to sample from + HeightLayers); // Three textures to sample from #endif // USE_HEIGHTMAP @@ -69,13 +67,51 @@ float getTileVertexHeight(vec2 uv, LevelWeights levelWeights){ height = calculateHeight( uv, levelWeights, // Variable to determine which texture to sample from - HeightMaps, HeightMapsParent1, HeightMapsParent2); // Three textures to sample from + HeightLayers); // Three textures to sample from #endif // USE_HEIGHTMAP return height; } +// This function is currently not correct +vec3 getTileVertexNormal( + vec2 uv, + LevelWeights levelWeights, + vec3 ellipsoidNormal) { + vec3 normal = ellipsoidNormal; + +#if USE_HEIGHTMAP + float sampleDelta = 1.0 / xSegments; + + float heightCenter = calculateHeight( + uv, + levelWeights, + HeightLayers); + float heightOffsetX = calculateHeight( + uv + vec2(sampleDelta, 0.0), + levelWeights, + HeightLayers); + float heightOffsetY = calculateHeight( + uv + vec2(0.0, sampleDelta), + levelWeights, + HeightLayers); + + vec3 e0 = normalize(cross(vec3(0,0,1), ellipsoidNormal)); + vec3 e1 = cross(ellipsoidNormal, e0); + vec3 e2 = ellipsoidNormal; + + vec3 v0 = e0 * sampleDelta * 3000000 + e2 * heightOffsetX; + vec3 v1 = e1 * sampleDelta * 3000000 + e2 * heightOffsetY; + + vec3 n = cross(v0, v1); + + normal = normalize(n); + +#endif // USE_HEIGHTMAP + return normal; +} + bool tileVertexIsSkirtVertex(){ int vertexIDx = gl_VertexID % (xSegments + 3); int vertexIDy = gl_VertexID / (xSegments + 3); diff --git a/modules/globebrowsing/tile/asynctilereader.cpp b/modules/globebrowsing/tile/asynctilereader.cpp index fe523b8442..e79744ab33 100644 --- a/modules/globebrowsing/tile/asynctilereader.cpp +++ b/modules/globebrowsing/tile/asynctilereader.cpp @@ -1,183 +1,151 @@ - /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ - - -#include -#include // abspath -#include +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ #include -#include + +#include #include +namespace openspace { +namespace globebrowsing { -#include - -namespace { - const std::string _loggerCat = "AsyncTextureDataProvider"; +void TileLoadJob::execute() { + _rawTile = _tileDataset->readTileData(_chunkIndex); } +std::shared_ptr TileLoadJob::product() const { + return _rawTile; +} +DiskCachedTileLoadJob::DiskCachedTileLoadJob( + std::shared_ptr textureDataProvider, + const TileIndex& tileIndex, + std::shared_ptr tdc, + CacheMode m) + : TileLoadJob(textureDataProvider, tileIndex) + , _tileDiskCache(tdc) + , _mode(m) +{} -namespace openspace { +void DiskCachedTileLoadJob::execute() { + _rawTile = nullptr; - void TileLoadJob::execute() { - _tileIOResult = _tileDataset->readTileData(_chunkIndex); - } - - - - - DiskCachedTileLoadJob::DiskCachedTileLoadJob(std::shared_ptr textureDataProvider, - const ChunkIndex& chunkIndex, std::shared_ptr tdc, CacheMode m) - : TileLoadJob(textureDataProvider, chunkIndex) - , _tileDiskCache(tdc) - , _mode(m) - { - - } - - DiskCachedTileLoadJob::DiskCachedTileLoadJob(std::shared_ptr textureDataProvider, - const ChunkIndex& chunkIndex, std::shared_ptr tdc, const std::string cacheMode) - : TileLoadJob(textureDataProvider, chunkIndex) - , _tileDiskCache(tdc) - { - if (cacheMode == "Disabled") _mode = CacheMode::Disabled; - else if (cacheMode == "ReadOnly") _mode = CacheMode::ReadOnly; - else if (cacheMode == "ReadAndWrite") _mode = CacheMode::ReadAndWrite; - else if (cacheMode == "WriteOnly") _mode = CacheMode::WriteOnly; - else if (cacheMode == "CacheHitsOnly") _mode = CacheMode::CacheHitsOnly; - } - - - - void DiskCachedTileLoadJob::execute() { - _tileIOResult = nullptr; - - switch (_mode) { + switch (_mode) { case CacheMode::Disabled: - _tileIOResult = _tileDataset->readTileData(_chunkIndex); + _rawTile = _tileDataset->readTileData(_chunkIndex); break; case CacheMode::ReadOnly: - _tileIOResult = _tileDiskCache->get(_chunkIndex); - if (_tileIOResult == nullptr) { - _tileIOResult = _tileDataset->readTileData(_chunkIndex); + _rawTile = _tileDiskCache->get(_chunkIndex); + if (_rawTile == nullptr) { + _rawTile = _tileDataset->readTileData(_chunkIndex); } break; case CacheMode::ReadAndWrite: - _tileIOResult = _tileDiskCache->get(_chunkIndex); - if (_tileIOResult == nullptr) { - _tileIOResult = _tileDataset->readTileData(_chunkIndex); - _tileDiskCache->put(_chunkIndex, _tileIOResult); + _rawTile = _tileDiskCache->get(_chunkIndex); + if (_rawTile == nullptr) { + _rawTile = _tileDataset->readTileData(_chunkIndex); + _tileDiskCache->put(_chunkIndex, _rawTile); } break; case CacheMode::WriteOnly: - _tileIOResult = _tileDataset->readTileData(_chunkIndex); - _tileDiskCache->put(_chunkIndex, _tileIOResult); + _rawTile = _tileDataset->readTileData(_chunkIndex); + _tileDiskCache->put(_chunkIndex, _rawTile); break; case CacheMode::CacheHitsOnly: - _tileIOResult = _tileDiskCache->get(_chunkIndex); - if (_tileIOResult == nullptr) { - TileIOResult res = TileIOResult::createDefaultRes(); - res.chunkIndex = _chunkIndex; - _tileIOResult = std::make_shared(res); + _rawTile = _tileDiskCache->get(_chunkIndex); + if (_rawTile == nullptr) { + RawTile res = RawTile::createDefaultRes(); + res.tileIndex = _chunkIndex; + _rawTile = std::make_shared(res); } break; - } - - } +} +AsyncTileDataProvider::AsyncTileDataProvider(std::shared_ptr tileDataset, + std::shared_ptr pool) + : _tileDataset(tileDataset) + , _concurrentJobManager(pool) +{} +std::shared_ptr AsyncTileDataProvider::getTextureDataProvider() const { + return _tileDataset; +} - AsyncTileDataProvider::AsyncTileDataProvider( - std::shared_ptr tileDataset, - std::shared_ptr pool) - : _tileDataset(tileDataset) - , _concurrentJobManager(pool) - { +bool AsyncTileDataProvider::enqueueTileIO(const TileIndex& tileIndex) { + if (satisfiesEnqueueCriteria(tileIndex)) { + auto job = std::make_shared(_tileDataset, tileIndex); + //auto job = std::make_shared(_tileDataset, tileIndex, tileDiskCache, "ReadAndWrite"); + _concurrentJobManager.enqueueJob(job); + _enqueuedTileRequests[tileIndex.hashKey()] = tileIndex; + return true; } + return false; +} - AsyncTileDataProvider::~AsyncTileDataProvider() { - +std::vector> AsyncTileDataProvider::getRawTiles() { + std::vector> readyResults; + while (_concurrentJobManager.numFinishedJobs() > 0) { + readyResults.push_back(_concurrentJobManager.popFinishedJob()->product()); } + return readyResults; +} +bool AsyncTileDataProvider::satisfiesEnqueueCriteria(const TileIndex& tileIndex) const { + // only allow tile to be enqueued if it's not already enqueued + //return _futureTileIOResults.find(tileIndex.hashKey()) == _futureTileIOResults.end(); + return _enqueuedTileRequests.find(tileIndex.hashKey()) == _enqueuedTileRequests.end(); - std::shared_ptr AsyncTileDataProvider::getTextureDataProvider() const { - return _tileDataset; +} + +void AsyncTileDataProvider::reset() { + //_futureTileIOResults.clear(); + //_threadPool->stop(ghoul::ThreadPool::RunRemainingTasks::No); + //_threadPool->start(); + _enqueuedTileRequests.clear(); + _concurrentJobManager.reset(); + while (_concurrentJobManager.numFinishedJobs() > 0) { + _concurrentJobManager.popFinishedJob(); } + getTextureDataProvider()->reset(); +} - bool AsyncTileDataProvider::enqueueTileIO(const ChunkIndex& chunkIndex) { - if (satisfiesEnqueueCriteria(chunkIndex)) { - auto job = std::make_shared(_tileDataset, chunkIndex); - //auto job = std::make_shared(_tileDataset, chunkIndex, tileDiskCache, "ReadAndWrite"); - _concurrentJobManager.enqueueJob(job); - _enqueuedTileRequests[chunkIndex.hashKey()] = chunkIndex; +void AsyncTileDataProvider::clearRequestQueue() { + //_threadPool->clearRemainingTasks(); + //_futureTileIOResults.clear(); + _concurrentJobManager.clearEnqueuedJobs(); + _enqueuedTileRequests.clear(); +} - return true; - } - return false; - } +float AsyncTileDataProvider::noDataValueAsFloat() { + return _tileDataset->noDataValueAsFloat(); +} - std::vector> AsyncTileDataProvider::getTileIOResults() { - std::vector> readyResults; - while (_concurrentJobManager.numFinishedJobs() > 0) { - readyResults.push_back(_concurrentJobManager.popFinishedJob()->product()); - } - return readyResults; - } - - - bool AsyncTileDataProvider::satisfiesEnqueueCriteria(const ChunkIndex& chunkIndex) const { - // only allow tile to be enqueued if it's not already enqueued - //return _futureTileIOResults.find(chunkIndex.hashKey()) == _futureTileIOResults.end(); - return _enqueuedTileRequests.find(chunkIndex.hashKey()) == _enqueuedTileRequests.end(); - - } - - void AsyncTileDataProvider::reset() { - //_futureTileIOResults.clear(); - //_threadPool->stop(ghoul::ThreadPool::RunRemainingTasks::No); - //_threadPool->start(); - _enqueuedTileRequests.clear(); - _concurrentJobManager.reset(); - while (_concurrentJobManager.numFinishedJobs() > 0) { - _concurrentJobManager.popFinishedJob(); - } - getTextureDataProvider()->reset(); - } - - void AsyncTileDataProvider::clearRequestQueue() { - //_threadPool->clearRemainingTasks(); - //_futureTileIOResults.clear(); - _concurrentJobManager.clearEnqueuedJobs(); - _enqueuedTileRequests.clear(); - } - -} // namespace openspace +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/tile/asynctilereader.h b/modules/globebrowsing/tile/asynctilereader.h index 7b9b95994e..748c95c62d 100644 --- a/modules/globebrowsing/tile/asynctilereader.h +++ b/modules/globebrowsing/tile/asynctilereader.h @@ -1,158 +1,110 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ - -#ifndef __ASYNC_TILE_DATA_PROVIDER_H__ -#define __ASYNC_TILE_DATA_PROVIDER_H__ - -//#include - -#include - -#include +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___ASYNC_TILE_DATA_PROVIDER___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___ASYNC_TILE_DATA_PROVIDER___H__ #include -#include -//#include +#include -#include - - -#include -#include #include -#include - - namespace openspace { +namespace globebrowsing { - struct LoadJob : public Job { - virtual void execute() = 0; - virtual std::shared_ptr product() = 0; +class TileDataset; + +struct LoadJob : public Job { + virtual void execute() = 0; + virtual std::shared_ptr product() const = 0; +}; + +struct TileLoadJob : LoadJob { + TileLoadJob(std::shared_ptr textureDataProvider, + const TileIndex& tileIndex) + : _tileDataset(textureDataProvider) + , _chunkIndex(tileIndex) + {} + + virtual ~TileLoadJob() = default; + + virtual void execute() override; + + virtual std::shared_ptr product() const override; + +protected: + TileIndex _chunkIndex; + std::shared_ptr _tileDataset; + std::shared_ptr _rawTile; +}; + +class TileDiskCache; + +struct DiskCachedTileLoadJob : public TileLoadJob { + enum CacheMode { + Disabled, + ReadOnly, + ReadAndWrite, + WriteOnly, + CacheHitsOnly, }; - - - struct TileLoadJob : LoadJob { - - TileLoadJob(std::shared_ptr textureDataProvider, - const ChunkIndex& chunkIndex) - : _tileDataset(textureDataProvider) - , _chunkIndex(chunkIndex) - { + DiskCachedTileLoadJob(std::shared_ptr textureDataProvider, + const TileIndex& tileIndex, std::shared_ptr tdc, + CacheMode cacheMode = CacheMode::ReadOnly); - } + void execute() override; - virtual ~TileLoadJob() { } +protected: + std::shared_ptr _tileDiskCache; + CacheMode _mode; +}; - virtual void execute(); +class AsyncTileDataProvider { +public: + AsyncTileDataProvider(std::shared_ptr textureDataProvider, + std::shared_ptr pool); - virtual std::shared_ptr product() { - return _tileIOResult; - } - - - protected: - - ChunkIndex _chunkIndex; - std::shared_ptr _tileDataset; - std::shared_ptr _tileIOResult; - }; - - - - - class TileDiskCache; - - struct DiskCachedTileLoadJob : public TileLoadJob { - enum CacheMode { - Disabled, - ReadOnly, - ReadAndWrite, - WriteOnly, - CacheHitsOnly, - }; + bool enqueueTileIO(const TileIndex& tileIndex); + std::vector> getRawTiles(); - DiskCachedTileLoadJob(std::shared_ptr textureDataProvider, - const ChunkIndex& chunkIndex, std::shared_ptr tdc, - const std::string cacheMode); + void reset(); + void clearRequestQueue(); - DiskCachedTileLoadJob(std::shared_ptr textureDataProvider, - const ChunkIndex& chunkIndex, std::shared_ptr tdc, - CacheMode cacheMode = CacheMode::ReadOnly); - - virtual void execute(); - - protected: - - std::shared_ptr _tileDiskCache; - CacheMode _mode; - - }; - - - - - class AsyncTileDataProvider { - public: - - AsyncTileDataProvider(std::shared_ptr textureDataProvider, - std::shared_ptr pool); - - ~AsyncTileDataProvider(); - - - bool enqueueTileIO(const ChunkIndex& chunkIndex); - std::vector> getTileIOResults(); - - void reset(); - void clearRequestQueue(); - - std::shared_ptr getTextureDataProvider() const; - - protected: - - virtual bool satisfiesEnqueueCriteria(const ChunkIndex&) const; - - private: - - - - std::shared_ptr _tileDataset; - ConcurrentJobManager _concurrentJobManager; - std::unordered_map _enqueuedTileRequests; - - - }; + std::shared_ptr getTextureDataProvider() const; + float noDataValueAsFloat(); +protected: + virtual bool satisfiesEnqueueCriteria(const TileIndex&) const; +private: + std::shared_ptr _tileDataset; + ConcurrentJobManager _concurrentJobManager; + std::unordered_map _enqueuedTileRequests; +}; +} // namespace globebrowsing } // namespace openspace - - - - -#endif // __ASYNC_TILE_DATA_PROVIDER_H__ \ No newline at end of file +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___ASYNC_TILE_DATA_PROVIDER___H__ diff --git a/modules/globebrowsing/tile/chunktile.h b/modules/globebrowsing/tile/chunktile.h new file mode 100644 index 0000000000..05f765c449 --- /dev/null +++ b/modules/globebrowsing/tile/chunktile.h @@ -0,0 +1,49 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___CHUNKTILE___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___CHUNKTILE___H__ + +#include +#include + +#include + +namespace openspace { +namespace globebrowsing { + +struct ChunkTile { + Tile tile; + TileUvTransform uvTransform; + TileDepthTransform depthTransform; +}; + +struct ChunkTilePile { + std::vector chunkTiles; +}; + +} // namespace globebrowsing +} // namespace openspace + +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___CHUNKTILE___H__ diff --git a/modules/globebrowsing/tile/layeredtextures.cpp b/modules/globebrowsing/tile/layeredtextures.cpp deleted file mode 100644 index 906d23986c..0000000000 --- a/modules/globebrowsing/tile/layeredtextures.cpp +++ /dev/null @@ -1,49 +0,0 @@ -/***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ - -#include - - -namespace { - const std::string _loggerCat = "LayeredTextures"; -} - - -namespace openspace { - - - const size_t LayeredTextures::NUM_TEXTURE_CATEGORIES; - const size_t LayeredTextures::MAX_NUM_TEXTURES_PER_CATEGORY; - - const std::string LayeredTextures::TEXTURE_CATEGORY_NAMES[NUM_TEXTURE_CATEGORIES] = - { - "ColorTextures", - "GrayScaleOverlays", - "NightTextures", - "WaterMasks", - "Overlays", - "HeightMaps", - }; - -} // namespace openspace diff --git a/modules/globebrowsing/tile/layeredtextureshaderprovider.cpp b/modules/globebrowsing/tile/layeredtextureshaderprovider.cpp deleted file mode 100644 index a7af680705..0000000000 --- a/modules/globebrowsing/tile/layeredtextureshaderprovider.cpp +++ /dev/null @@ -1,239 +0,0 @@ -/***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ - -#include - -#include -#include - -#include "ghoul/misc/dictionary.h" - -#include - -namespace { - const std::string _loggerCat = "LayeredTextureShaderProvider"; -} - -namespace openspace { - - const std::string LayeredTextureInfo::glslKeyPrefixes[NUM_SETTINGS_PER_CATEGORY] = - { - "lastLayerIndex", - "use", - "blend", - }; - - bool LayeredTextureInfo::operator==(const LayeredTextureInfo& other) const - { - return - lastLayerIdx == other.lastLayerIdx && - layerBlendingEnabled == other.layerBlendingEnabled; - } - - bool LayeredTexturePreprocessingData::operator==( - const LayeredTexturePreprocessingData& other) const - { - - if (layeredTextureInfo.size() != other.layeredTextureInfo.size() || - keyValuePairs.size() != other.keyValuePairs.size()) { - return false; - } - else - { - bool equal = true; - for (size_t i = 0; i < layeredTextureInfo.size(); i++) { - equal = equal && (layeredTextureInfo[i] == other.layeredTextureInfo[i]); - } - for (size_t i = 0; i < keyValuePairs.size(); i++) { - equal = equal && (keyValuePairs[i] == other.keyValuePairs[i]); - } - return equal; - } - } - - LayeredTextureShaderProvider::LayeredTextureShaderProvider( - const std::string& shaderName, - const std::string& vsPath, - const std::string& fsPath) - : _shaderName(shaderName) - , _vsPath(vsPath) - , _fsPath(fsPath) - , _updatedOnLastCall(false) - { - - } - - LayeredTextureShaderProvider::~LayeredTextureShaderProvider() - { - if (_programObject) { - RenderEngine& renderEngine = OsEng.renderEngine(); - renderEngine.removeRenderProgram(_programObject); - _programObject = nullptr; - } - } - - ProgramObject* LayeredTextureShaderProvider::getUpdatedShaderProgram( - LayeredTexturePreprocessingData preprocessingData) - { - _updatedOnLastCall = false; - if (!(preprocessingData == _preprocessingData) || _programObject == nullptr) { - recompileShaderProgram(preprocessingData); - _updatedOnLastCall = true; - } - return _programObject.get(); - } - - void LayeredTextureShaderProvider::recompileShaderProgram( - LayeredTexturePreprocessingData preprocessingData) - { - _preprocessingData = preprocessingData; - ghoul::Dictionary shaderDictionary; - - - // Different texture types can be height maps or color texture for example. - // These are used differently within the shaders. - auto textureTypes = _preprocessingData.layeredTextureInfo; - for (size_t i = 0; i < textureTypes.size(); i++) { - // lastLayerIndex must be at least 0 for the shader to compile, - // the layer type is inactivated by setting use to false - shaderDictionary.setValue( - LayeredTextureInfo::glslKeyPrefixes[ - LayeredTextureInfo::GlslKeyPrefixes::lastLayerIndex] + - LayeredTextures::TEXTURE_CATEGORY_NAMES[i], - glm::max(textureTypes[i].lastLayerIdx, 0)); - shaderDictionary.setValue( - LayeredTextureInfo::glslKeyPrefixes[ - LayeredTextureInfo::GlslKeyPrefixes::use] + - LayeredTextures::TEXTURE_CATEGORY_NAMES[i], - textureTypes[i].lastLayerIdx >= 0); - shaderDictionary.setValue( - LayeredTextureInfo::glslKeyPrefixes[ - LayeredTextureInfo::GlslKeyPrefixes::blend] + - LayeredTextures::TEXTURE_CATEGORY_NAMES[i], - textureTypes[i].layerBlendingEnabled); - } - - // Other settings such as "useAtmosphere" - auto keyValuePairs = _preprocessingData.keyValuePairs; - for (size_t i = 0; i < keyValuePairs.size(); i++) { - shaderDictionary.setValue(keyValuePairs[i].first, keyValuePairs[i].second); - } - - // Remove old program - OsEng.renderEngine().removeRenderProgram(_programObject); - - _programObject = OsEng.renderEngine().buildRenderProgram( - _shaderName, - _vsPath, - _fsPath, - shaderDictionary); - - ghoul_assert(_programObject != nullptr, "Failed to initialize programObject!"); - using IgnoreError = ProgramObject::IgnoreError; - _programObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); - } - - bool LayeredTextureShaderProvider::updatedOnLastCall() { - return _updatedOnLastCall; - } - - - const std::string LayeredTextureShaderUniformIdHandler::glslTileDataNames[ - NUM_TILE_DATA_VARIABLES] = - { - "textureSampler", - "depthTransform.depthScale", - "depthTransform.depthOffset", - "uvTransform.uvOffset", - "uvTransform.uvScale" - }; - - const std::string LayeredTextureShaderUniformIdHandler::blendLayerSuffixes[ - NUM_BLEND_TEXTURES] = - { - "", - "Parent1", - "Parent2", - }; - - LayeredTextureShaderUniformIdHandler::LayeredTextureShaderUniformIdHandler() - { - - } - - LayeredTextureShaderUniformIdHandler::~LayeredTextureShaderUniformIdHandler() - { - - } - - void LayeredTextureShaderUniformIdHandler::updateIdsIfNecessary( - LayeredTextureShaderProvider* shaderProvider) - { - if (shaderProvider->updatedOnLastCall()) - { - _shaderProvider = shaderProvider; - // Ignore errors since this loops through even uniforms that does not exist. - _shaderProvider->_programObject->setIgnoreUniformLocationError( - ProgramObject::IgnoreError::Yes); - for (size_t i = 0; i < LayeredTextures::NUM_TEXTURE_CATEGORIES; i++) - { - for (size_t j = 0; j < NUM_BLEND_TEXTURES; j++) - { - for (size_t k = 0; k < LayeredTextures::MAX_NUM_TEXTURES_PER_CATEGORY; - k++) - { - for (size_t l = 0; l < NUM_TILE_DATA_VARIABLES; l++) - { - _tileUniformIds[i][j][k][l] = - _shaderProvider->_programObject->uniformLocation( - LayeredTextures::TEXTURE_CATEGORY_NAMES[i] + - blendLayerSuffixes[j] + - "[" + std::to_string(k) + "]." + - glslTileDataNames[l]); - } - } - } - } - // Reset ignore errors - _shaderProvider->_programObject->setIgnoreUniformLocationError( - ProgramObject::IgnoreError::No); - } - } - - GLint LayeredTextureShaderUniformIdHandler::getId( - LayeredTextures::TextureCategory category, - size_t blendLayer, - size_t layerIndex, - GlslTileDataId tileDataId) - { - return _tileUniformIds[category][blendLayer][layerIndex][tileDataId]; - } - - - ProgramObject& LayeredTextureShaderUniformIdHandler::programObject() - { - return *_shaderProvider->_programObject; - } - -} // namespace openspace diff --git a/modules/globebrowsing/tile/layeredtextureshaderprovider.h b/modules/globebrowsing/tile/layeredtextureshaderprovider.h deleted file mode 100644 index 841afd7ace..0000000000 --- a/modules/globebrowsing/tile/layeredtextureshaderprovider.h +++ /dev/null @@ -1,215 +0,0 @@ -/***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ - -#ifndef __LAYERED_TEXTURE_SHADER_PROVIDER__ -#define __LAYERED_TEXTURE_SHADER_PROVIDER__ - -#include - -#include "ghoul/opengl/programobject.h" - -#include -#include -#include - -////////////////////////////////////////////////////////////////////////////////////////// -// LAYERED TEXTURE SHADER PROVIDER // -////////////////////////////////////////////////////////////////////////////////////////// - -namespace openspace { - using namespace ghoul::opengl; - - class LayeredTextureShaderUniformIdHandler; - - /** - * Settings per texture category that contains shader preprocessing information. - */ - struct LayeredTextureInfo - { - static const size_t NUM_SETTINGS_PER_CATEGORY = 3; - enum GlslKeyPrefixes - { - lastLayerIndex, - use, - blend, - }; - static const std::string glslKeyPrefixes[NUM_SETTINGS_PER_CATEGORY]; - - int lastLayerIdx; - bool layerBlendingEnabled; - - bool operator==(const LayeredTextureInfo& other) const; - }; - - /** - * Data needed for shader preprocessing before compiling a layered texture shader - * program. - * - * If a LayeredTexturePreprocessingData is compared with another it can - * be determined wheter or not a LayeredTextureShaderProvider needs to - * recompile its shader program. For each TextureCategory there is - * information about how many layers it has and whether or not to blend the texture - * levels. - */ - struct LayeredTexturePreprocessingData - { - std::array - layeredTextureInfo; - std::vector > keyValuePairs; - bool operator==(const LayeredTexturePreprocessingData& other) const; - }; - - /** - * This class has ownership of an updated shader program for rendering tiles. - */ - class LayeredTextureShaderProvider - { - public: - LayeredTextureShaderProvider( - const std::string& shaderName, - const std::string& vsPath, - const std::string& fsPath); - ~LayeredTextureShaderProvider(); - - /** - * Returns a pointer to a ProgramObject for rendering tiles. - * \param preprocessingData determines wherer or not the shader - * program needs to be re-compiled. If preprocessingData is different - * from the last time this function was called the shader program will be - * recompiled before returned. - */ - ProgramObject* getUpdatedShaderProgram( - LayeredTexturePreprocessingData preprocessingData); - - bool updatedOnLastCall(); - private: - friend class LayeredTextureShaderUniformIdHandler; - void recompileShaderProgram(LayeredTexturePreprocessingData preprocessingData); - - std::unique_ptr _programObject; - LayeredTexturePreprocessingData _preprocessingData; - - const std::string _shaderName; - const std::string _vsPath; - const std::string _fsPath; - - bool _updatedOnLastCall; - }; - - /** - * This class caches OpenGL uniform IDs for LayeredTextureShaderProviders. - */ - class LayeredTextureShaderUniformIdHandler - { - public: - static const size_t NUM_TILE_DATA_VARIABLES = 5; - static const size_t NUM_BLEND_TEXTURES = 3; - - /** - * Each texture can have these uniform variables associated with it in the shader - * code. - * - * textureSampler is the actual texture that can be sampled in the - * shader program. The associated GLSL type is sampler2D. - * depthTransform_depthScale specifies the scale part of the depth - * transform. Useful for height maps. The associated GLSL type is - * float. - * depthTransform_depthOffset specifies the offset part of the depth - * transform. Useful for height maps. The associated GLSL type is - * float. - * uvTransform_uvOffset specifies an offset that can be used when - * sampling from the texture. The associated GLSL type is vec2. - * uvTransform_uvScale specifies a scale that can be used when - * sampling from the texture. The associated GLSL type is vec2. - * - * The corresponding struct in GLSL code for storing these data is a - * Tile. The names of the uniforms are the ones specified in - * glslTileDataNames. - */ - enum GlslTileDataId { - textureSampler, - depthTransform_depthScale, - depthTransform_depthOffset, - uvTransform_uvOffset, - uvTransform_uvScale, - }; - - /** - * These suffixes are used when naming Tiles in GLSL code. The names - * of the Tiles is one of - * LayeredTextures::TEXTURE_CATEGORY_NAMES followed by the suffixes - * defined in blendLayerSuffixes. - */ - enum BlendLayerSuffixes { - none, - Parent1, - Parent2, - }; - - LayeredTextureShaderUniformIdHandler(); - ~LayeredTextureShaderUniformIdHandler(); - void updateIdsIfNecessary(LayeredTextureShaderProvider* shaderProvider); - - /** - * \param category can be one of the categories specified in - * LayeredTextures::TextureCategory. - * \param blendLayer can have a value between 0 and - * NUM_BLEND_TEXTURES and specified that it is the uniform of that - * specific blend layer that is requested. - * \param layerIndex should have a value between 0 and - * LayeredTextures::MAX_NUM_TEXTURES_PER_CATEGORY - 1 and will specify - * which of the texture layers that is requested. - * \param tileDataId specifies what variable for the texture that - * should be returned. It can have any of the values specified in - * GlslTileDataId. - * - * \returns an OpenGL uniform ID for the specified arguments. If the uniform does - * not exist in the shader program it returns -1. - */ - GLint getId( - LayeredTextures::TextureCategory category, - size_t blendLayer, - size_t layerIndex, - GlslTileDataId tileDataId); - ProgramObject& programObject(); - private: - static const std::string glslTileDataNames[NUM_TILE_DATA_VARIABLES]; - static const std::string blendLayerSuffixes[NUM_BLEND_TEXTURES]; - - std::array< - std::array< - std::array< - std::array< - GLint, - NUM_TILE_DATA_VARIABLES>, - LayeredTextures::MAX_NUM_TEXTURES_PER_CATEGORY>, - NUM_BLEND_TEXTURES>, - LayeredTextures::NUM_TEXTURE_CATEGORIES> - _tileUniformIds; - - LayeredTextureShaderProvider* _shaderProvider; - }; -} // namespace openspace - -#endif // __LAYERED_TEXTURE_SHADER_PROVIDER__ \ No newline at end of file diff --git a/modules/globebrowsing/tile/pixelregion.cpp b/modules/globebrowsing/tile/pixelregion.cpp index 6e2e3bf942..9649803e41 100644 --- a/modules/globebrowsing/tile/pixelregion.cpp +++ b/modules/globebrowsing/tile/pixelregion.cpp @@ -1,297 +1,274 @@ - /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ #include -#include #include -#include - - - - - -namespace { - const std::string _loggerCat = "PixelRegion"; -} - - - namespace openspace { - +namespace globebrowsing { +PixelRegion::PixelRegion(const PixelCoordinate& pixelStart, + const PixelRange& numberOfPixels) + : start(pixelStart) + , numPixels(numberOfPixels) +{} - PixelRegion::PixelRegion() - : start(0) - , numPixels(0) - { +PixelRegion::PixelRegion(const PixelRegion& o) + : start(o.start) + , numPixels(o.numPixels) +{} - } - - PixelRegion::PixelRegion(const PixelRegion& o) - : start(o.start) - , numPixels(o.numPixels) - { - - } - - PixelRegion::PixelRegion(const PixelCoordinate& pixelStart, const PixelRange& numberOfPixels) - : start(pixelStart) - , numPixels(numberOfPixels) - { - - } - - - - - ////////////////////////////////////////////////////////////////////////////////// - // Mutators // - ////////////////////////////////////////////////////////////////////////////////// - - void PixelRegion::setSide(Side side, int pos) { - switch (side) { - case LEFT: setLeft(pos); break; - case TOP: setTop(pos); break; - case RIGHT: setRight(pos); break; - case BOTTOM: setBottom(pos); break; - } - } - - void PixelRegion::setLeft(int x) { - numPixels.x += (start.x - x); - start.x = x; - } - - void PixelRegion::setTop(int p) { - numPixels.y += (start.y - p); - start.y = p; - } - - void PixelRegion::setRight(int x) { - numPixels.x = x - start.x; - } - - void PixelRegion::setBottom(int y) { - numPixels.y = y - start.y; - } - - - void PixelRegion::align(Side side, int pos) { - switch (side) { - case LEFT: alignLeft(pos); break; - case TOP: alignTop(pos); break; - case RIGHT: alignRight(pos); break; - case BOTTOM: alignBottom(pos); break; - } - } - - void PixelRegion::alignLeft(int x) { - start.x = x; - } - - void PixelRegion::alignTop(int y) { - start.y = y; - } - - void PixelRegion::alignRight(int x) { - start.x = x - numPixels.x; - } - - void PixelRegion::alignBottom(int y) { - start.y = y - numPixels.y; - } - - - - void PixelRegion::scale(const glm::dvec2& s) { - start = PixelCoordinate(glm::round(s * glm::dvec2(start))); - numPixels = PixelCoordinate(glm::round(s * glm::dvec2(numPixels))); - } - - void PixelRegion::scale(double s) { - scale(glm::dvec2(s)); - } - - void PixelRegion::downscalePow2(int exponent, PixelCoordinate wrt) { - start += wrt; - start.x >>= exponent; - start.y >>= exponent; - numPixels.x >>= exponent; - numPixels.y >>= exponent; - start -= wrt; - } - - void PixelRegion::upscalePow2(int exponent, PixelCoordinate wrt) { - start += wrt; - start.x <<= exponent; - start.y <<= exponent; - numPixels.x <<= exponent; - numPixels.y <<= exponent; - start -= wrt; - } - - - - void PixelRegion::move(Side side, int amount) { - switch (side) { - case LEFT: start.x -= amount; break; - case TOP: start.y -= amount; break; - case RIGHT: start.x += amount; break; - case BOTTOM: start.y += amount; break; - } - } - - void PixelRegion::pad(const PixelRegion& padding) { - start += padding.start; - numPixels += padding.numPixels; - } - - void PixelRegion::clampTo(const PixelRegion& boundingRegion) { - start = glm::max(start, boundingRegion.start); - numPixels = glm::min(end(), boundingRegion.end()) - start; - } - - void PixelRegion::forceNumPixelToDifferByNearestMultipleOf(unsigned int multiple) { - ghoul_assert(multiple > 0, "multiple must be 1 or larger"); - int sizeDiff = numPixels.x - numPixels.y; - if (std::abs(sizeDiff) > 0) { - if (sizeDiff > 0) { - numPixels.y += sizeDiff % multiple; - } - else { - numPixels.x += std::abs(sizeDiff) % multiple; - } - } - } - - void PixelRegion::roundUpNumPixelToNearestMultipleOf(unsigned int multiple) { - ghoul_assert(multiple > 0, "multiple must be 1 or larger"); - numPixels.x += numPixels.x % multiple; - numPixels.y += numPixels.y % multiple; - } - - void PixelRegion::roundDownToQuadratic() { - if (numPixels.x < numPixels.y) { - numPixels.y = numPixels.x; - } - else if (numPixels.x > numPixels.y) { - numPixels.x = numPixels.y; - } - } - - PixelRegion PixelRegion::globalCut(Side side, int p) { - if (!lineIntersect(side, p)) { - return PixelRegion({ 0, 0 }, { 0, 0 }); - } - - PixelRegion cutOff(*this); - int cutSize = 0; - switch (side) { +void PixelRegion::setSide(Side side, int pos) { + switch (side) { case LEFT: - setLeft(p); - cutOff.setRight(p - cutSize); + setLeft(pos); break; case TOP: - setTop(p); - cutOff.setBottom(p - cutSize); + setTop(pos); break; case RIGHT: - setRight(p); - cutOff.setLeft(p + cutSize); + setRight(pos); break; case BOTTOM: - setBottom(p); - cutOff.setTop(p + cutSize); + setBottom(pos); break; + } +} + +void PixelRegion::setLeft(int x) { + numPixels.x += (start.x - x); + start.x = x; +} + +void PixelRegion::setTop(int p) { + numPixels.y += (start.y - p); + start.y = p; +} + +void PixelRegion::setRight(int x) { + numPixels.x = x - start.x; +} + +void PixelRegion::setBottom(int y) { + numPixels.y = y - start.y; +} + +void PixelRegion::align(Side side, int pos) { + switch (side) { + case LEFT: + alignLeft(pos); + break; + case TOP: + alignTop(pos); + break; + case RIGHT: + alignRight(pos); + break; + case BOTTOM: + alignBottom(pos); + break; + } +} + +void PixelRegion::alignLeft(int x) { + start.x = x; +} + +void PixelRegion::alignTop(int y) { + start.y = y; +} + +void PixelRegion::alignRight(int x) { + start.x = x - numPixels.x; +} + +void PixelRegion::alignBottom(int y) { + start.y = y - numPixels.y; +} + +void PixelRegion::scale(const glm::dvec2& s) { + start = PixelCoordinate(glm::round(s * glm::dvec2(start))); + numPixels = PixelCoordinate(glm::round(s * glm::dvec2(numPixels))); +} + +void PixelRegion::scale(double s) { + scale(glm::dvec2(s)); +} + +void PixelRegion::downscalePow2(int exponent, PixelCoordinate wrt) { + start += wrt; + start.x >>= exponent; + start.y >>= exponent; + numPixels.x >>= exponent; + numPixels.y >>= exponent; + start -= wrt; +} + +void PixelRegion::upscalePow2(int exponent, PixelCoordinate wrt) { + start += wrt; + start.x <<= exponent; + start.y <<= exponent; + numPixels.x <<= exponent; + numPixels.y <<= exponent; + start -= wrt; +} + +void PixelRegion::move(Side side, int amount) { + switch (side) { + case LEFT: + start.x -= amount; + break; + case TOP: + start.y -= amount; + break; + case RIGHT: + start.x += amount; + break; + case BOTTOM: + start.y += amount; + break; + } +} + +void PixelRegion::pad(const PixelRegion& padding) { + start += padding.start; + numPixels += padding.numPixels; +} + +void PixelRegion::clampTo(const PixelRegion& boundingRegion) { + start = glm::max(start, boundingRegion.start); + numPixels = glm::min(end(), boundingRegion.end()) - start; +} + +void PixelRegion::forceNumPixelToDifferByNearestMultipleOf(unsigned int multiple) { + ghoul_assert(multiple > 0, "multiple must be 1 or larger"); + int sizeDiff = numPixels.x - numPixels.y; + if (std::abs(sizeDiff) > 0) { + if (sizeDiff > 0) { + numPixels.y += sizeDiff % multiple; } - return cutOff; - } - - PixelRegion PixelRegion::localCut(Side side, int p) { - if (p < 1) { - return PixelRegion({ 0, 0 }, { 0, 0 }); - } - else return globalCut(side, edge(side) - edgeDirectionSign(side) * p); - } - - - ////////////////////////////////////////////////////////////////////////////////// - // Accessors // - ////////////////////////////////////////////////////////////////////////////////// - - int PixelRegion::area() const { - return numPixels.x * numPixels.y; - } - - - int PixelRegion::edge(Side side) const { - switch (side) { - case LEFT: return start.x; - case TOP: return start.y; - case RIGHT: return start.x + numPixels.x; - case BOTTOM: return start.y + numPixels.y; + else { + numPixels.x += std::abs(sizeDiff) % multiple; } } +} - int PixelRegion::edgeDirectionSign(Side side) const { - return side < RIGHT ? -1 : 1; +void PixelRegion::roundUpNumPixelToNearestMultipleOf(unsigned int multiple) { + ghoul_assert(multiple > 0, "multiple must be 1 or larger"); + numPixels.x += numPixels.x % multiple; + numPixels.y += numPixels.y % multiple; +} + +void PixelRegion::roundDownToQuadratic() { + if (numPixels.x < numPixels.y) { + numPixels.y = numPixels.x; + } + else if (numPixels.x > numPixels.y) { + numPixels.x = numPixels.y; + } +} + +PixelRegion PixelRegion::globalCut(Side side, int p) { + if (!lineIntersect(side, p)) { + return PixelRegion({ 0, 0 }, { 0, 0 }); } - PixelCoordinate PixelRegion::end() const { - return start + numPixels; + PixelRegion cutOff(*this); + int cutSize = 0; + switch (side) { + case LEFT: + setLeft(p); + cutOff.setRight(p - cutSize); + break; + case TOP: + setTop(p); + cutOff.setBottom(p - cutSize); + break; + case RIGHT: + setRight(p); + cutOff.setLeft(p + cutSize); + break; + case BOTTOM: + setBottom(p); + cutOff.setTop(p + cutSize); + break; } + return cutOff; +} - ////////////////////////////////////////////////////////////////////////////////// - // Comparators // - ////////////////////////////////////////////////////////////////////////////////// +PixelRegion PixelRegion::localCut(Side side, int p) { + if (p < 1) { + return PixelRegion({ 0, 0 }, { 0, 0 }); + } + else { + return globalCut(side, edge(side) - edgeDirectionSign(side) * p); + } +} +int PixelRegion::area() const { + return numPixels.x * numPixels.y; +} - bool PixelRegion::lineIntersect(Side side, int p) { - switch (side) - { - case openspace::PixelRegion::LEFT: - case openspace::PixelRegion::RIGHT: +int PixelRegion::edge(Side side) const { + switch (side) { + case LEFT: return start.x; + case TOP: return start.y; + case RIGHT: return start.x + numPixels.x; + case BOTTOM: return start.y + numPixels.y; + } +} + +int PixelRegion::edgeDirectionSign(Side side) const { + return side < RIGHT ? -1 : 1; +} + +PixelCoordinate PixelRegion::end() const { + return start + numPixels; +} + +bool PixelRegion::lineIntersect(Side side, int p) { + switch (side) { + case PixelRegion::LEFT: + case PixelRegion::RIGHT: return start.x <= p && p <= (start.x + numPixels.x); - case openspace::PixelRegion::TOP: - case openspace::PixelRegion::BOTTOM: + case PixelRegion::TOP: + case PixelRegion::BOTTOM: return start.y <= p && p <= (start.y + numPixels.y); - } } +} - bool PixelRegion::isInside(const PixelRegion& r) const { - PixelCoordinate e = end(); - PixelCoordinate re = r.end(); - return r.start.x <= start.x && e.x <= re.x - && r.start.y <= start.y && e.y <= re.y; - } +bool PixelRegion::isInside(const PixelRegion& r) const { + PixelCoordinate e = end(); + PixelCoordinate re = r.end(); + return r.start.x <= start.x && e.x <= re.x && r.start.y <= start.y && e.y <= re.y; +} - bool PixelRegion::equals(const PixelRegion& r) const { - return start == r.start && numPixels == r.numPixels; - } +bool PixelRegion::equals(const PixelRegion& r) const { + return start == r.start && numPixels == r.numPixels; +} - -} // namespace openspace +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/tile/pixelregion.h b/modules/globebrowsing/tile/pixelregion.h index 77ce7cfb35..84fbca1d0d 100644 --- a/modules/globebrowsing/tile/pixelregion.h +++ b/modules/globebrowsing/tile/pixelregion.h @@ -1,129 +1,106 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __PIXEL_REGION_H__ -#define __PIXEL_REGION_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___PIXELREGION___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___PIXELREGION___H__ #include namespace openspace { +namespace globebrowsing { - typedef glm::ivec2 PixelCoordinate; - typedef glm::ivec2 PixelRange; +using PixelCoordinate = glm::ivec2; +using PixelRange= glm::ivec2; - struct PixelRegion { - - enum Side { - LEFT = 0, TOP, RIGHT, BOTTOM, - }; - - PixelRegion(); - PixelRegion(const PixelRegion& o); - PixelRegion(const PixelCoordinate& pixelStart, const PixelRange& numberOfPixels); - - - ////////////////////////////////////////////////////////////////////////////////// - // Mutators // - ////////////////////////////////////////////////////////////////////////////////// - - /** - * Sets one of the sides of the pixel region the specified position. This changes - * the number of pixels in the region. - * - * Example: side = LEFT and pos 16: - * set start.x = 16 and keep the end position the same. - */ - void setSide(Side side, int pos); - void setLeft(int x); - void setTop(int p); - void setRight(int x); - void setBottom(int y); - - /** - * Aligns one the sides of the pixel regino to the specified position. This does - * not change the number of pixels within the region. - * - * Example: Side = left and pos = 16: - * start.x = 16 and keep the size the same - */ - void align(Side side, int pos); - void alignLeft(int x); - void alignTop(int y); - void alignRight(int x); - void alignBottom(int y); - - - void scale(const glm::dvec2& s); - void scale(double s); - void downscalePow2(int exponent, PixelCoordinate wrt = {0,0}); - void upscalePow2(int exponent, PixelCoordinate wrt = { 0,0 }); - - void move(Side side, int amount); - void pad(const PixelRegion& padding); - void clampTo(const PixelRegion& boundingRegion); - - void forceNumPixelToDifferByNearestMultipleOf(unsigned int multiple); - void roundUpNumPixelToNearestMultipleOf(unsigned int multiple); - void roundDownToQuadratic(); - - - PixelRegion globalCut(Side side, int globalPos); - PixelRegion localCut(Side side, int localPos); - - - ////////////////////////////////////////////////////////////////////////////////// - // Accessors // - ////////////////////////////////////////////////////////////////////////////////// - - int area() const; - int edge(Side side) const; - int edgeDirectionSign(Side side) const; - PixelCoordinate end() const; - - - ////////////////////////////////////////////////////////////////////////////////// - // Comparators // - ////////////////////////////////////////////////////////////////////////////////// - - bool lineIntersect(Side side, int p); - bool isInside(const PixelRegion& r) const; - bool equals(const PixelRegion& r) const; - - - ////////////////////////////////////////////////////////////////////////////////// - // Members // - ////////////////////////////////////////////////////////////////////////////////// - - PixelCoordinate start; - PixelRange numPixels; +struct PixelRegion { + enum Side { + LEFT = 0, + TOP, + RIGHT, + BOTTOM }; + PixelRegion(const PixelRegion& o); + PixelRegion(const PixelCoordinate& pixelStart = PixelCoordinate(0, 0), + const PixelRange& numberOfPixels = PixelRange(0, 0)); + + /** + * Sets one of the sides of the pixel region the specified position. This changes + * the number of pixels in the region. + * + * Example: side = LEFT and pos 16: + * set start.x = 16 and keep the end position the same. + */ + void setSide(Side side, int pos); + void setLeft(int x); + void setTop(int p); + void setRight(int x); + void setBottom(int y); + + /** + * Aligns one the sides of the pixel regino to the specified position. This does + * not change the number of pixels within the region. + * + * Example: Side = left and pos = 16: + * start.x = 16 and keep the size the same + */ + void align(Side side, int pos); + void alignLeft(int x); + void alignTop(int y); + void alignRight(int x); + void alignBottom(int y); + + void scale(const glm::dvec2& s); + void scale(double s); + void downscalePow2(int exponent, PixelCoordinate wrt = {0,0}); + void upscalePow2(int exponent, PixelCoordinate wrt = { 0,0 }); + void move(Side side, int amount); + void pad(const PixelRegion& padding); + void clampTo(const PixelRegion& boundingRegion); + void forceNumPixelToDifferByNearestMultipleOf(unsigned int multiple); + void roundUpNumPixelToNearestMultipleOf(unsigned int multiple); + void roundDownToQuadratic(); + PixelRegion globalCut(Side side, int globalPos); + PixelRegion localCut(Side side, int localPos); + + int area() const; + int edge(Side side) const; + int edgeDirectionSign(Side side) const; + PixelCoordinate end() const; + + bool lineIntersect(Side side, int p); + bool isInside(const PixelRegion& r) const; + bool equals(const PixelRegion& r) const; + + PixelCoordinate start; + PixelRange numPixels; +}; + +} // namespace globebrowsing } // namespace openspace - - -#endif // __PIXEL_REGION_H__ \ No newline at end of file +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___PIXELREGION___H__ diff --git a/modules/globebrowsing/tile/tile.cpp b/modules/globebrowsing/tile/tile.cpp index a7489dfe60..0ef46ef91e 100644 --- a/modules/globebrowsing/tile/tile.cpp +++ b/modules/globebrowsing/tile/tile.cpp @@ -1,72 +1,176 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#include +#include -#include +#include namespace { const std::string _loggerCat = "Tile"; } - namespace openspace { +namespace globebrowsing { - const Tile Tile::TileUnavailable = {nullptr, nullptr, Tile::Status::Unavailable }; - +void TileMetaData::serialize(std::ostream& os) { + os << maxValues.size() << std::endl; + for (float f : maxValues) { + os << f << " "; + } + os << std::endl; + for (float f : minValues) { + os << f << " "; + } + os << std::endl; +} - Tile Tile::createPlainTile(const glm::uvec2& size, const glm::uvec4& color) { - using namespace ghoul::opengl; - - // Create pixel data - int numBytes = size.x * size.y * 4 * 1; - char* pixels = new char[numBytes]; - size_t numPixels = size.x * size.y; - size_t i = 0; - for (size_t p = 0; p < numPixels; p++){ - pixels[i++] = color.r; - pixels[i++] = color.g; - pixels[i++] = color.b; - pixels[i++] = color.a; - } - - // Create ghoul texture - auto texture = std::make_shared(glm::uvec3(size, 1)); - texture->setDataOwnership(Texture::TakeOwnership::Yes); - texture->setPixelData(pixels); - texture->uploadTexture(); - texture->setFilter(ghoul::opengl::Texture::FilterMode::Linear); - - // Create tile - Tile tile; - tile.status = Tile::Status::OK; - tile.preprocessData = nullptr; - tile.texture = texture; - - return tile; +TileMetaData TileMetaData::deserialize(std::istream& is) { + TileMetaData res; + int n; is >> n; + res.maxValues.resize(n); + for (int i = 0; i < n; i++) { + is >> res.maxValues[i]; + } + res.minValues.resize(n); + for (int i = 0; i < n; i++) { + is >> res.minValues[i]; } + return std::move(res); +} +RawTile::RawTile() + : imageData(nullptr) + , dimensions(0, 0, 0) + , tileMetaData(nullptr) + , tileIndex(0, 0, 0) + , error(CE_None) + , nBytesImageData(0) +{} + +RawTile RawTile::createDefaultRes() { + RawTile defaultRes; + int w = 8; + int h = 8; + defaultRes.dimensions = glm::uvec3(w, h, 1); + defaultRes.nBytesImageData = w * h * 1 * 3 * 4; // assume max 3 channels, max 4 bytes per pixel + defaultRes.imageData = new char[defaultRes.nBytesImageData]; + std::fill_n((char*)defaultRes.imageData, defaultRes.nBytesImageData, 0); + return std::move(defaultRes); +} -} // namespace openspace +void RawTile::serializeMetaData(std::ostream& os) { + os << dimensions.x << " " << dimensions.y << " " << dimensions.z << std::endl; + os << tileIndex.x << " " << tileIndex.y << " " << tileIndex.level << std::endl; + os << error << std::endl; + + // preprocess data + os << (tileMetaData != nullptr) << std::endl; + if (tileMetaData != nullptr) { + tileMetaData->serialize(os); + } + + os << nBytesImageData << std::endl; +} + +RawTile RawTile::deserializeMetaData(std::istream& is) { + RawTile res; + is >> res.dimensions.x >> res.dimensions.y >> res.dimensions.z; + is >> res.tileIndex.x >> res.tileIndex.y >> res.tileIndex.level; + int err; is >> err; res.error = (CPLErr) err; + + res.tileMetaData = nullptr; + bool hastileMetaData; + is >> hastileMetaData; + if (hastileMetaData) { + TileMetaData tileMetaData = TileMetaData::deserialize(is); + res.tileMetaData = std::make_shared(tileMetaData); + } + + is >> res.nBytesImageData; + + char binaryDataSeparator; + is >> binaryDataSeparator; // not used + + char* buffer = new char[res.nBytesImageData](); + return std::move(res); +} + +const Tile Tile::TileUnavailable = {nullptr, nullptr, Tile::Status::Unavailable }; + +Tile Tile::createPlainTile(const glm::uvec2& size, const glm::uvec4& color) { + using namespace ghoul::opengl; + + // Create pixel data + int numBytes = size.x * size.y * 4 * 1; + char* pixels = new char[numBytes]; + size_t numPixels = size.x * size.y; + size_t i = 0; + for (size_t p = 0; p < numPixels; p++){ + pixels[i++] = color.r; + pixels[i++] = color.g; + pixels[i++] = color.b; + pixels[i++] = color.a; + } + + // Create ghoul texture + auto texture = std::make_shared(glm::uvec3(size, 1)); + texture->setDataOwnership(Texture::TakeOwnership::Yes); + texture->setPixelData(pixels); + texture->uploadTexture(); + texture->setFilter(ghoul::opengl::Texture::FilterMode::Linear); + + // Create tile + Tile tile; + tile.status = Tile::Status::OK; + tile.metaData = nullptr; + tile.texture = texture; + + return tile; +} + +glm::vec2 Tile::compensateSourceTextureSampling(glm::vec2 startOffset, glm::vec2 sizeDiff, + glm::uvec2 resolution, glm::vec2 tileUV) +{ + glm::vec2 sourceSize = glm::vec2(resolution) + sizeDiff; + glm::vec2 currentSize = glm::vec2(resolution); + glm::vec2 sourceToCurrentSize = currentSize / sourceSize; + tileUV = sourceToCurrentSize * (tileUV - startOffset / sourceSize); + return tileUV; +} + +glm::vec2 Tile::TileUvToTextureSamplePosition(const TileUvTransform uvTransform, + glm::vec2 tileUV, glm::uvec2 resolution) +{ + glm::vec2 uv = uvTransform.uvOffset + uvTransform.uvScale * tileUV; + uv = compensateSourceTextureSampling( + TileDataset::tilePixelStartOffset, + TileDataset::tilePixelSizeDifference, + resolution, + uv); + return uv; +} + +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/tile/tile.h b/modules/globebrowsing/tile/tile.h index 159fc855df..dc478a93d5 100644 --- a/modules/globebrowsing/tile/tile.h +++ b/modules/globebrowsing/tile/tile.h @@ -1,102 +1,143 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __TILE_H__ -#define __TILE_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___TILE___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___TILE___H__ -#include // Texture +#include -#include // TilePreprocessData +#include +#include +#include +#include namespace openspace { +namespace globebrowsing { + +struct TileMetaData { + std::vector maxValues; + std::vector minValues; + std::vector hasMissingData; + + void serialize(std::ostream& s); + static TileMetaData deserialize(std::istream& s); +}; + +struct TextureFormat { + ghoul::opengl::Texture::Format ghoulFormat; + GLuint glFormat; +}; - using namespace ghoul::opengl; +using namespace ghoul::opengl; + +struct RawTile { + RawTile(); + + char* imageData; + glm::uvec3 dimensions; + std::shared_ptr tileMetaData; + TileIndex tileIndex; + CPLErr error; + size_t nBytesImageData; + + void serializeMetaData(std::ostream& s); + static RawTile deserializeMetaData(std::istream& s); + + static RawTile createDefaultRes(); +}; + +struct TileUvTransform { + glm::vec2 uvOffset; + glm::vec2 uvScale; +}; + +/** + * Defines a status and may have a Texture and TileMetaData + */ +struct Tile { + std::shared_ptr texture; + std::shared_ptr metaData; /** - * Defines a status and may have a Texture and PreprocessData - */ - struct Tile { - std::shared_ptr texture; - std::shared_ptr preprocessData; - - - /** - * Describe if this Tile is good for usage (OK) or otherwise - * the reason why it is not. - */ - enum class Status { - /** - * E.g when texture data is not currently in memory. - * texture and preprocessData are both null - */ - Unavailable, - - /** - * Can be set by TileProviders if the requested - * ChunkIndex is undefined for that particular - * provider. - * texture and preprocessData are both null - */ - OutOfRange, - - /** - * An IO Error happend - * texture and preprocessData are both null - */ - IOError, - - /** - * The Texture is uploaded to the GPU and good for usage. - * texture is defined. preprocessData may be defined. - */ - OK - } status; - - - /** - * Instantiates a new tile with a single color. - * - * \param size The size of texture to be created - * \param color defined RGBA values in range 0-255. - * - * \returns a Tile with status OK and the a texture - * with the requested size and color + * Describe if this Tile is good for usage (OK) or otherwise + * the reason why it is not. + */ + enum class Status { + /** + * E.g when texture data is not currently in memory. + * texture and tileMetaData are both null */ - static Tile createPlainTile(const glm::uvec2& size, const glm::uvec4& color); + Unavailable, /** - * A tile with status unavailable that any user can return to - * indicate that a tile was unavailable. - */ - static const Tile TileUnavailable; + * Can be set by TileProviders if the requested + * TileIndex is undefined for that particular + * provider. + * texture and metaData are both null + */ + OutOfRange, - }; + /** + * An IO Error happend + * texture and metaData are both null + */ + IOError, -} // namespace openspace + /** + * The Texture is uploaded to the GPU and good for usage. + * texture is defined. metaData may be defined. + */ + OK + } status; + + /** + * Instantiates a new tile with a single color. + * + * \param size The size of texture to be created + * \param color defined RGBA values in range 0-255. + * + * \returns a Tile with status OK and the a texture + * with the requested size and color + */ + static Tile createPlainTile(const glm::uvec2& size, const glm::uvec4& color); + + static glm::vec2 compensateSourceTextureSampling(glm::vec2 startOffset, + glm::vec2 sizeDiff, glm::uvec2 resolution, glm::vec2 tileUV); + + static glm::vec2 TileUvToTextureSamplePosition(const TileUvTransform uvTransform, + glm::vec2 tileUV, glm::uvec2 resolution); + + /** + * A tile with status unavailable that any user can return to + * indicate that a tile was unavailable. + */ + static const Tile TileUnavailable; +}; + +} // namespace globebrowsing +} // namespace openspace - - -#endif // __TILE_H__ \ No newline at end of file +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___TILE___H__ diff --git a/modules/globebrowsing/tile/tiledataset.cpp b/modules/globebrowsing/tile/tiledataset.cpp index 4c2d0bc781..0cc2912cea 100644 --- a/modules/globebrowsing/tile/tiledataset.cpp +++ b/modules/globebrowsing/tile/tiledataset.cpp @@ -1,26 +1,31 @@ - /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + + +#include #include #include @@ -29,728 +34,800 @@ #include // abspath #include -#include +#include #include -#include + #include #include - #include #include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include namespace { const std::string _loggerCat = "TileDataset"; } - - namespace openspace { +namespace globebrowsing { - std::ostream& operator<<(std::ostream& os, const openspace::PixelRegion& pr) { - return os << pr.start.x << ", " << pr.start.y << " with size " << pr.numPixels.x << ", " << pr.numPixels.y; - } +std::ostream& operator<<(std::ostream& os, const PixelRegion& pr) { + return os << pr.start.x << ", " << pr.start.y << " with size " << pr.numPixels.x << ", " << pr.numPixels.y; +} - ////////////////////////////////////////////////////////////////////////////////// - // Tile Data Layout // - ////////////////////////////////////////////////////////////////////////////////// +TileDataLayout::TileDataLayout() {} - TileDataLayout::TileDataLayout() { +TileDataLayout::TileDataLayout(GDALDataset* dataSet, GLuint preferredGlType) { + // Assume all raster bands have the same data type + gdalType =preferredGlType != 0 ? + TileDataType::getGdalDataType(preferredGlType) : + dataSet->GetRasterBand(1)->GetRasterDataType(); - } - - TileDataLayout::TileDataLayout(GDALDataset* dataSet, GLuint preferredGlType) { - // Assume all raster bands have the same data type - gdalType = preferredGlType != 0 ? TileDataType::getGdalDataType(preferredGlType) : dataSet->GetRasterBand(1)->GetRasterDataType(); - glType = TileDataType::getOpenGLDataType(gdalType); - numRasters = dataSet->GetRasterCount(); - bytesPerDatum = TileDataType::numberOfBytes(gdalType); - bytesPerPixel = bytesPerDatum * numRasters; - textureFormat = TileDataType::getTextureFormat(numRasters, gdalType); - } + glType = TileDataType::getOpenGLDataType(gdalType); + numRasters = dataSet->GetRasterCount(); + bytesPerDatum = TileDataType::numberOfBytes(gdalType); + bytesPerPixel = bytesPerDatum * numRasters; + textureFormat = TileDataType::getTextureFormat(numRasters, gdalType); +} +IODescription IODescription::cut(PixelRegion::Side side, int pos) { + PixelRegion readPreCut = read.region; + PixelRegion writePreCut = write.region; + glm::dvec2 ratio; + ratio.x = write.region.numPixels.x / (double) read.region.numPixels.x; + ratio.y = write.region.numPixels.y / (double) read.region.numPixels.y; - IODescription IODescription::cut(PixelRegion::Side side, int pos) { - PixelRegion readPreCut = read.region; - PixelRegion writePreCut = write.region; + double ratioRatio = ratio.x / ratio.y; - glm::dvec2 ratio; - ratio.x = write.region.numPixels.x / (double) read.region.numPixels.x; - ratio.y = write.region.numPixels.y / (double) read.region.numPixels.y; + //ghoul_assert(glm::abs(ratioRatio - 1.0) < 0.01, "Different read/write aspect ratio!"); - double ratioRatio = ratio.x / ratio.y; + IODescription whatCameOff = *this; + whatCameOff.read.region = read.region.globalCut(side, pos); - //ghoul_assert(glm::abs(ratioRatio - 1.0) < 0.01, "Different read/write aspect ratio!"); - - IODescription whatCameOff = *this; - whatCameOff.read.region = read.region.globalCut(side, pos); - - PixelRange cutSize = whatCameOff.read.region.numPixels; - PixelRange localWriteCutSize = ratio * glm::dvec2(cutSize); + PixelRange cutSize = whatCameOff.read.region.numPixels; + PixelRange localWriteCutSize = ratio * glm::dvec2(cutSize); - - if (cutSize.x == 0 || cutSize.y == 0) { - ghoul_assert(read.region.equals(readPreCut), "Read region should not have been modified"); - ghoul_assert(write.region.equals(writePreCut), "Write region should not have been modified"); - } - - int localWriteCutPos = (side % 2 == 0) ? localWriteCutSize.x : localWriteCutSize.y; - whatCameOff.write.region = write.region.localCut(side, localWriteCutPos); - - return whatCameOff; + if (cutSize.x == 0 || cutSize.y == 0) { + ghoul_assert( + read.region.equals(readPreCut), + "Read region should not have been modified" + ); + ghoul_assert( + write.region.equals(writePreCut), + "Write region should not have been modified" + ); } + int localWriteCutPos = (side % 2 == 0) ? localWriteCutSize.x : localWriteCutSize.y; + whatCameOff.write.region = write.region.localCut(side, localWriteCutPos); + return whatCameOff; +} +const glm::ivec2 TileDataset::tilePixelStartOffset = glm::ivec2(-2); +const glm::ivec2 TileDataset::tilePixelSizeDifference = glm::ivec2(4); - - - - ////////////////////////////////////////////////////////////////////////////////// - // Tile Dataset // - ////////////////////////////////////////////////////////////////////////////////// - - const glm::ivec2 TileDataset::tilePixelStartOffset = glm::ivec2(-2); - const glm::ivec2 TileDataset::tilePixelSizeDifference = glm::ivec2(4); - - const PixelRegion TileDataset::padding = PixelRegion(tilePixelStartOffset, tilePixelSizeDifference); +const PixelRegion TileDataset::padding = PixelRegion( + tilePixelStartOffset, + tilePixelSizeDifference +); - bool TileDataset::GdalHasBeenInitialized = false; +bool TileDataset::GdalHasBeenInitialized = false; +TileDataset::TileDataset(const std::string& gdalDatasetDesc, const Configuration& config) + : _config(config) + , hasBeenInitialized(false) +{ + _initData = { "", gdalDatasetDesc, config.minimumTilePixelSize, config.dataType }; + ensureInitialized(); + _initData.initDirectory = CPLGetCurrentDir(); +} - - TileDataset::TileDataset(const std::string& gdalDatasetDesc, const Configuration& config) - : _config(config) - , hasBeenInitialized(false) - { - - _initData = { "", gdalDatasetDesc, config.minimumTilePixelSize, config.dataType }; - ensureInitialized(); - _initData.initDirectory = CPLGetCurrentDir(); +void TileDataset::reset() { + _cached._maxLevel = -1; + if (_dataset != nullptr) { + GDALClose((GDALDatasetH)_dataset); } - - void TileDataset::reset() { - _cached._maxLevel = -1; - if (_dataset != nullptr) { - GDALClose((GDALDatasetH)_dataset); - } + initialize(); +} + +float TileDataset::noDataValueAsFloat() { + float noDataValue; + if (_dataset && _dataset->GetRasterBand(1)) { + noDataValue = _dataset->GetRasterBand(1)->GetNoDataValue();; + } + else { + noDataValue = std::numeric_limits::min(); + } + return noDataValue; +} + +void TileDataset::ensureInitialized() { + if (!hasBeenInitialized) { initialize(); + hasBeenInitialized = true; } - void TileDataset::ensureInitialized() { - if (!hasBeenInitialized) { - initialize(); - hasBeenInitialized = true; +} + +void TileDataset::initialize() { + gdalEnsureInitialized(); + + _dataset = gdalDataset(_initData.gdalDatasetDesc); + + //Do any other initialization needed for the TileDataset + _dataLayout = TileDataLayout(_dataset, _initData.dataType); + _depthTransform = calculateTileDepthTransform(); + _cached._tileLevelDifference = calculateTileLevelDifference(_initData.minimumPixelSize); +} + +void TileDataset::gdalEnsureInitialized() { + if (!GdalHasBeenInitialized) { + GDALAllRegister(); + CPLSetConfigOption( + "GDAL_DATA", + absPath("${MODULE_GLOBEBROWSING}/gdal_data").c_str() + ); + setGdalProxyConfiguration(); + GdalHasBeenInitialized = true; + } +} + +void TileDataset::setGdalProxyConfiguration() { + ghoul::Dictionary proxySettings; + bool proxyEnabled = OsEng.configurationManager().getValue( + ConfigurationManager::KeyHttpProxy, proxySettings + ); + if (proxyEnabled) { + std::string proxyAddress, proxyPort, proxyUser, proxyPassword, proxyAuth; + + bool success = proxySettings.getValue( + ConfigurationManager::PartHttpProxyAddress, + proxyAddress + ); + success &= proxySettings.getValue( + ConfigurationManager::PartHttpProxyPort, + proxyPort + ); + proxySettings.getValue( + ConfigurationManager::PartHttpProxyAuthentication, + proxyAuth + ); + + std::string proxyAuthString = "BASIC"; + if (proxyAuth == "basic" || proxyAuth == "") { + proxyAuthString = "BASIC"; + } else if (proxyAuth == "ntlm") { + proxyAuthString = "NTLM"; + } else if (proxyAuth == "digest") { + proxyAuthString = "DIGEST"; + } else if (proxyAuth == "any") { + proxyAuthString = "ANY"; + } else { + success = false; } - } + bool userAndPassword = proxySettings.getValue( + ConfigurationManager::PartHttpProxyUser, + proxyUser + ); + userAndPassword &= proxySettings.getValue( + ConfigurationManager::PartHttpProxyPassword, + proxyPassword + ); - void TileDataset::initialize() { - gdalEnsureInitialized(); - - _dataset = gdalDataset(_initData.gdalDatasetDesc); - - //Do any other initialization needed for the TileDataset - _dataLayout = TileDataLayout(_dataset, _initData.dataType); - _depthTransform = calculateTileDepthTransform(); - _cached._tileLevelDifference = calculateTileLevelDifference(_initData.minimumPixelSize); - - LDEBUG(_initData.gdalDatasetDesc << " - " << _cached._tileLevelDifference); - } - - void TileDataset::gdalEnsureInitialized() { - if (!GdalHasBeenInitialized) { - GDALAllRegister(); - CPLSetConfigOption("GDAL_DATA", absPath("${MODULE_GLOBEBROWSING}/gdal_data").c_str()); - GdalHasBeenInitialized = true; + if (success) { + std::string proxy = proxyAddress + ":" + proxyPort; + CPLSetConfigOption("GDAL_HTTP_PROXY", proxy.c_str()); + LDEBUG("Using proxy server " << proxy); + if (userAndPassword) { + std::string proxyUserPwd = proxyUser + ":" + proxyPassword; + CPLSetConfigOption("GDAL_HTTP_PROXYUSERPWD", proxyUserPwd.c_str()); + CPLSetConfigOption("GDAL_HTTP_PROXYAUTH", proxyAuthString.c_str()); + LDEBUG("Using authentication method: " << proxyAuthString); + } + } else { + LERROR("Invalid proxy settings for GDAL"); } + } else { + LDEBUG("Setting up GDAL without proxy server"); } +} - GDALDataset* TileDataset::gdalDataset(const std::string& gdalDatasetDesc) { - GDALDataset* dataset = (GDALDataset *)GDALOpen(gdalDatasetDesc.c_str(), GA_ReadOnly); +GDALDataset* TileDataset::gdalDataset(const std::string& gdalDatasetDesc) { + GDALDataset* dataset = (GDALDataset *)GDALOpen(gdalDatasetDesc.c_str(), GA_ReadOnly); + if (!dataset) { + using namespace ghoul::filesystem; + std::string correctedPath = FileSystem::ref().pathByAppendingComponent( + _initData.initDirectory, gdalDatasetDesc + ); + dataset = (GDALDataset *)GDALOpen(correctedPath.c_str(), GA_ReadOnly); if (!dataset) { - std::string correctedPath = ghoul::filesystem::FileSystem::ref().pathByAppendingComponent(_initData.initDirectory, gdalDatasetDesc); - dataset = (GDALDataset *)GDALOpen(correctedPath.c_str(), GA_ReadOnly); - if (!dataset) { - throw ghoul::RuntimeError("Failed to load dataset:\n" + gdalDatasetDesc); - } + throw ghoul::RuntimeError("Failed to load dataset:\n" + gdalDatasetDesc); } + } - const std::string originalDriverName = dataset->GetDriverName(); + // Commenting away the following for now since it is not supported for older + // versions of GDAL. Only used for debug info. + /* + const std::string originalDriverName = dataset->GetDriverName(); - if (originalDriverName != "WMS") { - LDEBUG(" " << originalDriverName); - LDEBUG(" " << dataset->GetGCPProjection()); - LDEBUG(" " << dataset->GetProjectionRef()); + if (originalDriverName != "WMS") { + LDEBUG(" " << originalDriverName); + LDEBUG(" " << dataset->GetGCPProjection()); + LDEBUG(" " << dataset->GetProjectionRef()); - GDALDriver* driver = dataset->GetDriver(); - char** metadata = driver->GetMetadata(); - for (int i = 0; metadata[i] != nullptr; i++) { - LDEBUG(" " << metadata[i]); - } - - const char* in_memory = ""; - //GDALDataset* vrtDataset = driver->CreateCopy(in_memory, dataset, false, nullptr, nullptr, nullptr); + GDALDriver* driver = dataset->GetDriver(); + char** metadata = driver->GetMetadata(); + for (int i = 0; metadata[i] != nullptr; i++) { + LDEBUG(" " << metadata[i]); } + + const char* in_memory = ""; + //GDALDataset* vrtDataset = driver->CreateCopy(in_memory, dataset, false, nullptr, nullptr, nullptr); + } + */ + + return dataset; +} + +TileDataset::~TileDataset() { + delete _dataset; +} + +std::shared_ptr TileDataset::readTileData(TileIndex tileIndex) { + ensureInitialized(); + IODescription io = getIODescription(tileIndex); + CPLErr worstError = CPLErr::CE_None; + + // Build the RawTile from the data we querred + std::shared_ptr rawTile = std::make_shared(); + rawTile->imageData = readImageData(io, worstError); + rawTile->error = worstError; + rawTile->tileIndex = tileIndex; + rawTile->dimensions = glm::uvec3(io.write.region.numPixels, 1); + rawTile->nBytesImageData = io.write.totalNumBytes; - - return dataset; + if (_config.doPreProcessing) { + rawTile->tileMetaData = getTileMetaData(rawTile, io.write.region); + rawTile->error = std::max(rawTile->error, postProcessErrorCheck(rawTile, io)); } + return rawTile; +} - TileDataset::~TileDataset() { - delete _dataset; +std::shared_ptr TileDataset::defaultTileData() { + ensureInitialized(); + PixelRegion pixelRegion = { PixelCoordinate(0, 0), PixelRange(16, 16) }; + std::shared_ptr rawTile = std::make_shared(); + rawTile->tileIndex = { 0, 0, 0 }; + rawTile->dimensions = glm::uvec3(pixelRegion.numPixels, 1); + rawTile->nBytesImageData = + rawTile->dimensions.x * rawTile->dimensions.y * _dataLayout.bytesPerPixel; + rawTile->imageData = new char[rawTile->nBytesImageData]; + for (size_t i = 0; i < rawTile->nBytesImageData; ++i) { + rawTile->imageData[i] = 0; } - - - - - ////////////////////////////////////////////////////////////////////////////////// - // Public interface // - ////////////////////////////////////////////////////////////////////////////////// - - std::shared_ptr TileDataset::readTileData(ChunkIndex chunkIndex) { - ensureInitialized(); - IODescription io = getIODescription(chunkIndex); - CPLErr worstError = CPLErr::CE_None; - - // Build the Tile IO Result from the data we queride - std::shared_ptr result = std::make_shared(); - result->imageData = readImageData(io, worstError); - result->error = worstError; - result->chunkIndex = chunkIndex; - result->dimensions = glm::uvec3(io.write.region.numPixels, 1); - result->nBytesImageData = io.write.totalNumBytes; + rawTile->error = CPLErr::CE_None; - if (_config.doPreProcessing) { - result->preprocessData = preprocess(result, io.write.region); - result->error = std::max(result->error, postProcessErrorCheck(result, io)); - } - - return result; + if (_config.doPreProcessing) { + rawTile->tileMetaData = getTileMetaData(rawTile, pixelRegion); + //rawTile->error = std::max(rawTile->error, postProcessErrorCheck(rawTile, io)); } + return rawTile; +} - std::shared_ptr TileDataset::defaultTileData() { - ensureInitialized(); - PixelRegion pixelRegion = { PixelCoordinate(0, 0), PixelRange(16, 16) }; - std::shared_ptr result = std::make_shared(); - result->chunkIndex = { 0, 0, 0 }; - result->dimensions = glm::uvec3(pixelRegion.numPixels, 1); - result->nBytesImageData = result->dimensions.x * result->dimensions.y * _dataLayout.bytesPerPixel; - result->imageData = new char[result->nBytesImageData]; - for (size_t i = 0; i < result->nBytesImageData; ++i) { - result->imageData[i] = 0; +int TileDataset::maxChunkLevel() { + ensureInitialized(); + if (_cached._maxLevel < 0) { + int numOverviews = _dataset->GetRasterBand(1)->GetOverviewCount(); + _cached._maxLevel = -_cached._tileLevelDifference; + if (numOverviews > 0) { + _cached._maxLevel += numOverviews - 1; } - result->error = CPLErr::CE_None; + } + return _cached._maxLevel; +} + +TileDepthTransform TileDataset::getDepthTransform() { + ensureInitialized(); + return _depthTransform; +} + +const TileDataLayout& TileDataset::getDataLayout() { + ensureInitialized(); + return _dataLayout; +} + +int TileDataset::calculateTileLevelDifference(int minimumPixelSize) { + GDALRasterBand* firstBand = _dataset->GetRasterBand(1); + GDALRasterBand* maxOverview; + int numOverviews = firstBand->GetOverviewCount(); + int sizeLevel0; + if (numOverviews <= 0) { // No overviews. Use first band. + maxOverview = firstBand; + } + else { // Pick the highest overview. + maxOverview = firstBand->GetOverview(numOverviews - 1); + } + sizeLevel0 = maxOverview->GetXSize(); + double diff = log2(minimumPixelSize) - log2(sizeLevel0); + return diff; +} + +TileDepthTransform TileDataset::calculateTileDepthTransform() { + GDALRasterBand* firstBand = _dataset->GetRasterBand(1); - if (_config.doPreProcessing) { - result->preprocessData = preprocess(result, pixelRegion); - //result->error = std::max(result->error, postProcessErrorCheck(result, io)); - } + bool isFloat = + (_dataLayout.gdalType == GDT_Float32 || _dataLayout.gdalType == GDT_Float64); + double maximumValue = + isFloat ? 1.0 : TileDataType::getMaximumValue(_dataLayout.gdalType); - return result; - } + TileDepthTransform transform; + transform.depthOffset = firstBand->GetOffset(); + transform.depthScale = firstBand->GetScale() * maximumValue; + return transform; +} - int TileDataset::maxChunkLevel() { - ensureInitialized(); - if (_cached._maxLevel < 0) { - int numOverviews = _dataset->GetRasterBand(1)->GetOverviewCount(); - _cached._maxLevel = -_cached._tileLevelDifference; - if (numOverviews > 0) { - _cached._maxLevel += numOverviews - 1; - } - } - return _cached._maxLevel; - } +bool TileDataset::gdalHasOverviews() const { + return _dataset->GetRasterBand(1)->GetOverviewCount() > 0; +} - TileDepthTransform TileDataset::getDepthTransform() { - ensureInitialized(); - return _depthTransform; - } +int TileDataset::gdalOverview(const PixelRange& regionSizeOverviewZero) const { + GDALRasterBand* firstBand = _dataset->GetRasterBand(1); - const TileDataLayout& TileDataset::getDataLayout() { - ensureInitialized(); - return _dataLayout; - } + int minNumPixels0 = glm::min(regionSizeOverviewZero.x, regionSizeOverviewZero.y); - - - - - ////////////////////////////////////////////////////////////////////////////////// - // Initialization // - ////////////////////////////////////////////////////////////////////////////////// - - int TileDataset::calculateTileLevelDifference(int minimumPixelSize) { - GDALRasterBand* firstBand = _dataset->GetRasterBand(1); - GDALRasterBand* maxOverview; - int numOverviews = firstBand->GetOverviewCount(); - int sizeLevel0; - if (numOverviews <= 0) { // No overviews. Use first band. - maxOverview = firstBand; - } - else { // Pick the highest overview. - maxOverview = firstBand->GetOverview(numOverviews - 1); - } - sizeLevel0 = maxOverview->GetXSize(); - double diff = log2(minimumPixelSize) - log2(sizeLevel0); - return diff; - } - - TileDepthTransform TileDataset::calculateTileDepthTransform() { - GDALRasterBand* firstBand = _dataset->GetRasterBand(1); - // Floating point types does not have a fix maximum or minimum value and - // can not be normalized when sampling a texture. Hence no rescaling is needed. - bool isFloat = (_dataLayout.gdalType == GDT_Float32 || _dataLayout.gdalType == GDT_Float64); - double maximumValue = isFloat ? 1.0 : TileDataType::getMaximumValue(_dataLayout.gdalType); - - TileDepthTransform transform; - transform.depthOffset = firstBand->GetOffset(); - transform.depthScale = firstBand->GetScale() * maximumValue; - return transform; - } - - - - - - ////////////////////////////////////////////////////////////////////////////////// - // GDAL helper methods // - ////////////////////////////////////////////////////////////////////////////////// - - - bool TileDataset::gdalHasOverviews() const { - return _dataset->GetRasterBand(1)->GetOverviewCount() > 0; - } - - int TileDataset::gdalOverview(const PixelRange& regionSizeOverviewZero) const { - GDALRasterBand* firstBand = _dataset->GetRasterBand(1); - - int minNumPixels0 = glm::min(regionSizeOverviewZero.x, regionSizeOverviewZero.y); - - int overviews = firstBand->GetOverviewCount(); - GDALRasterBand* maxOverview = overviews ? firstBand->GetOverview(overviews - 1) : firstBand; + int overviews = firstBand->GetOverviewCount(); + GDALRasterBand* maxOverview = + overviews ? firstBand->GetOverview(overviews - 1) : firstBand; - int sizeLevel0 = maxOverview->GetXSize(); - // The dataset itself may not have overviews but even if it does not, an overview - // for the data region can be calculated and possibly be used to sample greater - // Regions of the original dataset. - int ov = std::log2(minNumPixels0) - std::log2(sizeLevel0 + 1) - _cached._tileLevelDifference; - ov = glm::clamp(ov, 0, overviews - 1); + int sizeLevel0 = maxOverview->GetXSize(); + // The dataset itself may not have overviews but even if it does not, an overview + // for the data region can be calculated and possibly be used to sample greater + // Regions of the original dataset. + int ov = std::log2(minNumPixels0) - std::log2(sizeLevel0 + 1) - + _cached._tileLevelDifference; + ov = glm::clamp(ov, 0, overviews - 1); - return ov; + return ov; +} + +int TileDataset::gdalOverview(const TileIndex& tileIndex) const { + int overviews = _dataset->GetRasterBand(1)->GetOverviewCount(); + int ov = overviews - (tileIndex.level + _cached._tileLevelDifference + 1); + return glm::clamp(ov, 0, overviews - 1); +} + +int TileDataset::gdalVirtualOverview(const TileIndex& tileIndex) const { + int overviews = _dataset->GetRasterBand(1)->GetOverviewCount(); + int ov = overviews - (tileIndex.level + _cached._tileLevelDifference + 1); + return ov; +} + +PixelRegion TileDataset::gdalPixelRegion(GDALRasterBand* rasterBand) const { + PixelRegion gdalRegion; + gdalRegion.start.x = 0; + gdalRegion.start.y = 0; + gdalRegion.numPixels.x = rasterBand->GetXSize(); + gdalRegion.numPixels.y = rasterBand->GetYSize(); + return gdalRegion; +} + +PixelRegion TileDataset::gdalPixelRegion(const GeodeticPatch& geodeticPatch) const { + Geodetic2 nwCorner = geodeticPatch.getCorner(Quad::NORTH_WEST); + Geodetic2 swCorner = geodeticPatch.getCorner(Quad::SOUTH_EAST); + PixelCoordinate pixelStart = geodeticToPixel(nwCorner); + PixelCoordinate pixelEnd = geodeticToPixel(swCorner); + PixelRegion gdalRegion(pixelStart, pixelEnd - pixelStart); + return gdalRegion; +} + +GDALRasterBand* TileDataset::gdalRasterBand(int overview, int raster) const { + GDALRasterBand* rasterBand = _dataset->GetRasterBand(raster); + int numberOfOverviews = rasterBand->GetOverviewCount(); + rasterBand = gdalHasOverviews() ? rasterBand->GetOverview(overview) : rasterBand; + ghoul_assert(rasterBand != nullptr, "Rasterband is null"); + return rasterBand; +} + +std::array TileDataset::getGeoTransform() const { + std::array padfTransform; + CPLErr err = _dataset->GetGeoTransform(&padfTransform[0]); + if (err == CE_Failure) { + GeodeticPatch globalCoverage(Geodetic2(0,0), Geodetic2(M_PI / 2, M_PI)); + padfTransform[1] = Angle::fromRadians( + globalCoverage.size().lon).asDegrees() / _dataset->GetRasterXSize(); + padfTransform[5] = -Angle::fromRadians( + globalCoverage.size().lat).asDegrees() / _dataset->GetRasterYSize(); + padfTransform[0] = Angle::fromRadians( + globalCoverage.getCorner(Quad::NORTH_WEST).lon).asDegrees(); + padfTransform[3] = Angle::fromRadians( + globalCoverage.getCorner(Quad::NORTH_WEST).lat).asDegrees(); + padfTransform[2] = 0; + padfTransform[4] = 0; } + return padfTransform; +} - int TileDataset::gdalOverview(const ChunkIndex& chunkIndex) const { - int overviews = _dataset->GetRasterBand(1)->GetOverviewCount(); - int ov = overviews - (chunkIndex.level + _cached._tileLevelDifference + 1); - return glm::clamp(ov, 0, overviews - 1); - } - - - int TileDataset::gdalVirtualOverview(const ChunkIndex& chunkIndex) const { - int overviews = _dataset->GetRasterBand(1)->GetOverviewCount(); - int ov = overviews - (chunkIndex.level + _cached._tileLevelDifference + 1); - return ov; - } - - PixelRegion TileDataset::gdalPixelRegion(GDALRasterBand* rasterBand) const { - PixelRegion gdalRegion; - gdalRegion.start.x = 0; - gdalRegion.start.y = 0; - gdalRegion.numPixels.x = rasterBand->GetXSize(); - gdalRegion.numPixels.y = rasterBand->GetYSize(); - return gdalRegion; - } - - PixelRegion TileDataset::gdalPixelRegion(const GeodeticPatch& geodeticPatch) const { - Geodetic2 nwCorner = geodeticPatch.getCorner(Quad::NORTH_WEST); - Geodetic2 swCorner = geodeticPatch.getCorner(Quad::SOUTH_EAST); - PixelCoordinate pixelStart = geodeticToPixel(nwCorner); - PixelCoordinate pixelEnd = geodeticToPixel(swCorner); - PixelRegion gdalRegion(pixelStart, pixelEnd - pixelStart); - return gdalRegion; - } - - GDALRasterBand* TileDataset::gdalRasterBand(int overview, int raster) const { - GDALRasterBand* rasterBand = _dataset->GetRasterBand(raster); - int numberOfOverviews = rasterBand->GetOverviewCount(); - rasterBand = gdalHasOverviews() ? rasterBand->GetOverview(overview) : rasterBand; - ghoul_assert(rasterBand != nullptr, "Rasterband is null"); - return rasterBand; - } - - - - - - ////////////////////////////////////////////////////////////////////////////////// - // ReadTileData helper functions // - ////////////////////////////////////////////////////////////////////////////////// - - PixelCoordinate TileDataset::geodeticToPixel(const Geodetic2& geo) const { - - double padfTransform[6]; - CPLErr err = _dataset->GetGeoTransform(padfTransform); - - ghoul_assert(err != CE_Failure, "Failed to get transform"); - - Scalar Y = Angle::fromRadians(geo.lat).asDegrees(); - Scalar X = Angle::fromRadians(geo.lon).asDegrees(); - - // convert from pixel and line to geodetic coordinates - // Xp = padfTransform[0] + P*padfTransform[1] + L*padfTransform[2]; - // Yp = padfTransform[3] + P*padfTransform[4] + L*padfTransform[5]; - - // <=> - double* a = &(padfTransform[0]); - double* b = &(padfTransform[3]); - - // Xp = a[0] + P*a[1] + L*a[2]; - // Yp = b[0] + P*b[1] + L*b[2]; - - // <=> - double divisor = (a[2] * b[1] - a[1] * b[2]); - ghoul_assert(divisor != 0.0, "Division by zero!"); - //ghoul_assert(a[2] != 0.0, "a2 must not be zero!"); - double P = (a[0] * b[2] - a[2] * b[0] + a[2] * Y - b[2] * X) / divisor; - double L = (-a[0] * b[1] + a[1] * b[0] - a[1] * Y + b[1] * X) / divisor; - // ref: https://www.wolframalpha.com/input/?i=X+%3D+a0+%2B+a1P+%2B+a2L,+Y+%3D+b0+%2B+b1P+%2B+b2L,+solve+for+P+and+L - - double Xp = a[0] + P*a[1] + L*a[2]; - double Yp = b[0] + P*b[1] + L*b[2]; - - ghoul_assert(abs(X - Xp) < 1e-10, "inverse should yield X as before"); - ghoul_assert(abs(Y - Yp) < 1e-10, "inverse should yield Y as before"); - - return PixelCoordinate(glm::round(P), glm::round(L)); - } - - Geodetic2 TileDataset::pixelToGeodetic(const PixelCoordinate& p) const { - double padfTransform[6]; - CPLErr err = _dataset->GetGeoTransform(padfTransform); - ghoul_assert(err != CE_Failure, "Failed to get transform"); - Geodetic2 geodetic; - geodetic.lon = padfTransform[0] + p.x * padfTransform[1] + p.y * padfTransform[2]; - geodetic.lat = padfTransform[3] + p.x * padfTransform[4] + p.y * padfTransform[5]; - return geodetic; - } - - IODescription TileDataset::getIODescription(const ChunkIndex& chunkIndex) const { - IODescription io; - io.read.region = gdalPixelRegion(chunkIndex); - - if (gdalHasOverviews()) { - int overview = gdalOverview(chunkIndex); - io.read.overview = overview; - io.read.region.downscalePow2(overview + 1); - io.write.region = io.read.region; - io.read.region.pad(padding); - } - else { - io.read.overview = 0; - io.write.region = io.read.region; - int virtualOverview = gdalVirtualOverview(chunkIndex); - io.write.region.downscalePow2(virtualOverview + 1); - PixelRegion scaledPadding = padding; - - scaledPadding.upscalePow2(std::max(virtualOverview + 1, 0)); - io.read.region.pad(scaledPadding); - } - - // For correct sampling in height dataset, we need to pad the texture tile - io.write.region.pad(padding); - PixelRange preRound = io.write.region.numPixels; - io.write.region.roundDownToQuadratic(); - io.write.region.roundUpNumPixelToNearestMultipleOf(2); - if (preRound != io.write.region.numPixels) { - LDEBUG(chunkIndex << " | " << preRound.x << ", " << preRound.y << " --> " << io.write.region.numPixels.x << ", " << io.write.region.numPixels.y); - } - - - io.write.region.start = PixelCoordinate(0, 0); // write region starts in origin - io.write.bytesPerLine = _dataLayout.bytesPerPixel * io.write.region.numPixels.x; - io.write.totalNumBytes = io.write.bytesPerLine * io.write.region.numPixels.y; - - return io; - } - - char* TileDataset::readImageData(IODescription& io, CPLErr& worstError) const { - // allocate memory for the image - char* imageData = new char[io.write.totalNumBytes]; - - // Read the data (each rasterband is a separate channel) - for (size_t i = 0; i < _dataLayout.numRasters; i++) { - GDALRasterBand* rasterBand = gdalRasterBand(io.read.overview, i + 1); - - // The final destination pointer is offsetted by one datum byte size - // for every raster (or data channel, i.e. R in RGB) - char* dataDestination = imageData + (i * _dataLayout.bytesPerDatum); - - CPLErr err = repeatedRasterIO(rasterBand, io, dataDestination); - - // CE_None = 0, CE_Debug = 1, CE_Warning = 2, CE_Failure = 3, CE_Fatal = 4 - worstError = std::max(worstError, err); - } - - // GDAL reads pixel lines top to bottom, we want the opposit - return imageData; - } - - CPLErr TileDataset::repeatedRasterIO(GDALRasterBand* rasterBand, const IODescription& fullIO, char* dataDestination, int depth) const { - std::string spaces = " "; - std::string indentation = spaces.substr(0, 2 * depth); - - CPLErr worstError = CPLErr::CE_None; - - // NOTE: - // Ascii graphics illustrates the implementation details of this method, for one - // specific case. Even though the illustrated case is specific, readers can - // hopefully find it useful to get the general idea. - - // Make a copy of the full IO desription as we will have to modify it - IODescription io = fullIO; - PixelRegion gdalRegion = gdalPixelRegion(rasterBand); - - - // Example: - // We have an io description that defines a WRITE and a READ region. - // In this case the READ region extends outside of the defined gdal region, - // meaning we will have to do wrapping - - - // io.write.region io.read.region - // | | - // V V - // +-------+ +-------+ - // | | | |--------+ - // | | | | | - // | | | | | - // +-------+ +-------+ | - // | | <-- gdalRegion - // | | - // +--------------+ - - - //LDEBUG(indentation << "-"); - //LDEBUG(indentation << "repeated read: " << io.read.region); - //LDEBUG(indentation << "repeated write: " << io.write.region); - - bool didCutOff = false; - - if (!io.read.region.isInside(gdalRegion)) { - // Loop through each side: left, top, right, bottom - for (int i = 0; i < 4; ++i) { - - // Example: - // We are currently considering the left side of the pixel region - PixelRegion::Side side = (PixelRegion::Side) i; - IODescription cutoff = io.cut(side, gdalRegion.edge(side)); - - // Example: - // We cut off the left part that was outside the gdal region, and we now - // have an additional io description for the cut off region. - // Note that the cut-method used above takes care of the corresponding - // WRITE region for us. - - // cutoff.write.region cutoff.read.region - // | io.write.region | io.read.region - // | | | | - // V V V V - // +-+-----+ +-+-----+ - // | | | | | |--------+ - // | | | | | | | - // | | | | | | | - // +-+-----+ +-+-----+ | - // | | <-- gdalRegion - // | | - // +--------------+ - - if (cutoff.read.region.area() > 0) { - didCutOff = true; - - // Wrap by repeating - PixelRegion::Side oppositeSide = (PixelRegion::Side) ((i + 2) % 4); - - cutoff.read.region.align(oppositeSide, gdalRegion.edge(oppositeSide)); - - // Example: - // The cut off region is wrapped to the opposite side of the region, - // i.e. "repeated". Note that we don't want WRITE region to change, - // we're only wrapping the READ region. - - // cutoff.write.region io.read.region cutoff.read.region - // | io.write.region | | - // | | V V - // V V +-----+ +-+ - // +-+-----+ | |------| | - // | | | | | | | - // | | | | | | | - // | | | +-----+ +-+ - // +-+-----+ | | <-- gdalRegion - // | | - // +--------------+ - - // Example: - // The cutoff region has been repeated along one of its sides, but - // as we can see in this example, it still has a top part outside the - // defined gdal region. This is handled through recursion. - CPLErr err = repeatedRasterIO(rasterBand, cutoff, dataDestination, depth + 1); - - worstError = std::max(worstError, err); - } - } - } - - //if (depth == 0) { - //LDEBUG(indentation << "main rasterIO read: " << io.read.region); - //LDEBUG(indentation << "main rasterIO write: " << io.write.region); - //} - - else if (worstError > CPLErr::CE_None) { - LDEBUG(indentation << "Error reading padding: " << worstError); - } +PixelCoordinate TileDataset::geodeticToPixel(const Geodetic2& geo) const { + std::array padfTransform = getGeoTransform(); - CPLErr err = rasterIO(rasterBand, io, dataDestination); + double Y = Angle::fromRadians(geo.lat).asDegrees(); + double X = Angle::fromRadians(geo.lon).asDegrees(); + + // convert from pixel and line to geodetic coordinates + // Xp = padfTransform[0] + P*padfTransform[1] + L*padfTransform[2]; + // Yp = padfTransform[3] + P*padfTransform[4] + L*padfTransform[5]; + + // <=> + double* a = &(padfTransform[0]); + double* b = &(padfTransform[3]); + + // Xp = a[0] + P*a[1] + L*a[2]; + // Yp = b[0] + P*b[1] + L*b[2]; + + // <=> + double divisor = (a[2] * b[1] - a[1] * b[2]); + ghoul_assert(divisor != 0.0, "Division by zero!"); + //ghoul_assert(a[2] != 0.0, "a2 must not be zero!"); + double P = (a[0] * b[2] - a[2] * b[0] + a[2] * Y - b[2] * X) / divisor; + double L = (-a[0] * b[1] + a[1] * b[0] - a[1] * Y + b[1] * X) / divisor; + // ref: https://www.wolframalpha.com/input/?i=X+%3D+a0+%2B+a1P+%2B+a2L,+Y+%3D+b0+%2B+b1P+%2B+b2L,+solve+for+P+and+L + + double Xp = a[0] + P*a[1] + L*a[2]; + double Yp = b[0] + P*b[1] + L*b[2]; + + ghoul_assert(abs(X - Xp) < 1e-10, "inverse should yield X as before"); + ghoul_assert(abs(Y - Yp) < 1e-10, "inverse should yield Y as before"); + + return PixelCoordinate(glm::round(P), glm::round(L)); +} + +Geodetic2 TileDataset::pixelToGeodetic(const PixelCoordinate& p) const { + std::array padfTransform = getGeoTransform(); + Geodetic2 geodetic; + // Should be using radians and not degrees? + geodetic.lon = padfTransform[0] + p.x * padfTransform[1] + p.y * padfTransform[2]; + geodetic.lat = padfTransform[3] + p.x * padfTransform[4] + p.y * padfTransform[5]; + return geodetic; +} + +IODescription TileDataset::getIODescription(const TileIndex& tileIndex) const { + IODescription io; + io.read.region = gdalPixelRegion(tileIndex); + + if (gdalHasOverviews()) { + int overview = gdalOverview(tileIndex); + io.read.overview = overview; + io.read.region.downscalePow2(overview + 1); + io.write.region = io.read.region; + io.read.region.pad(padding); + } + else { + io.read.overview = 0; + io.write.region = io.read.region; + int virtualOverview = gdalVirtualOverview(tileIndex); + io.write.region.downscalePow2(virtualOverview + 1); + PixelRegion scaledPadding = padding; + + scaledPadding.upscalePow2(std::max(virtualOverview + 1, 0)); + io.read.region.pad(scaledPadding); + } + + // For correct sampling in height dataset, we need to pad the texture tile + io.write.region.pad(padding); + PixelRange preRound = io.write.region.numPixels; + io.write.region.roundDownToQuadratic(); + io.write.region.roundUpNumPixelToNearestMultipleOf(2); + if (preRound != io.write.region.numPixels) { + LDEBUG(tileIndex << " | " << preRound.x << ", " << preRound.y << " --> " << io.write.region.numPixels.x << ", " << io.write.region.numPixels.y); + } + + io.write.region.start = PixelCoordinate(0, 0); // write region starts in origin + io.write.bytesPerLine = _dataLayout.bytesPerPixel * io.write.region.numPixels.x; + io.write.totalNumBytes = io.write.bytesPerLine * io.write.region.numPixels.y; + + return io; +} + +char* TileDataset::readImageData(IODescription& io, CPLErr& worstError) const { + // allocate memory for the image + char* imageData = new char[io.write.totalNumBytes]; + + // Read the data (each rasterband is a separate channel) + for (size_t i = 0; i < _dataLayout.numRasters; i++) { + GDALRasterBand* rasterBand = gdalRasterBand(io.read.overview, i + 1); + + // The final destination pointer is offsetted by one datum byte size + // for every raster (or data channel, i.e. R in RGB) + char* dataDestination = imageData + (i * _dataLayout.bytesPerDatum); + + CPLErr err = repeatedRasterIO(rasterBand, io, dataDestination); + + // CE_None = 0, CE_Debug = 1, CE_Warning = 2, CE_Failure = 3, CE_Fatal = 4 worstError = std::max(worstError, err); - - // The return error from a repeated rasterIO is ONLY based on the main region, - // which in the usual case will cover the main area of the patch anyway - - - - return err; } - CPLErr TileDataset::rasterIO(GDALRasterBand* rasterBand, const IODescription& io, char* dataDestination) const { - PixelRegion gdalRegion = gdalPixelRegion(rasterBand); + // GDAL reads pixel lines top to bottom, we want the opposit + return imageData; +} - ghoul_assert(io.read.region.isInside(gdalRegion), "write region of bounds!"); +CPLErr TileDataset::repeatedRasterIO(GDALRasterBand* rasterBand, const IODescription& fullIO, char* dataDestination, int depth) const { + std::string spaces = " "; + std::string indentation = spaces.substr(0, 2 * depth); - ghoul_assert(io.write.region.start.x >= 0 && io.write.region.start.y >= 0, "Invalid write region"); + CPLErr worstError = CPLErr::CE_None; - PixelCoordinate end = io.write.region.end(); - size_t largestIndex = (end.y - 1) * io.write.bytesPerLine + (end.x - 1) * _dataLayout.bytesPerPixel; - ghoul_assert(largestIndex <= io.write.totalNumBytes, "Invalid write region"); + // NOTE: + // Ascii graphics illustrates the implementation details of this method, for one + // specific case. Even though the illustrated case is specific, readers can + // hopefully find it useful to get the general idea. + + // Make a copy of the full IO desription as we will have to modify it + IODescription io = fullIO; + PixelRegion gdalRegion = gdalPixelRegion(rasterBand); - char * dataDest = dataDestination; - - // OBS! GDAL reads pixels top to bottom, but we want our pixels bottom to top. - // Therefore, we increment the destination pointer to the last line on in the - // buffer, and the we specify in the rasterIO call that we want negative line - // spacing. Doing this compensates the flipped Y axis - dataDest += (io.write.totalNumBytes - io.write.bytesPerLine); - - // handle requested write region - dataDest -= io.write.region.start.y * io.write.bytesPerLine; // note -= since flipped y axis - dataDest += io.write.region.start.x * _dataLayout.bytesPerPixel; - - - return rasterBand->RasterIO( - GF_Read, - io.read.region.start.x, // Begin read x - io.read.region.start.y, // Begin read y - io.read.region.numPixels.x, // width to read x - io.read.region.numPixels.y, // width to read y - dataDest, // Where to put data - io.write.region.numPixels.x, // width to write x in destination - io.write.region.numPixels.y, // width to write y in destination - _dataLayout.gdalType, // Type - _dataLayout.bytesPerPixel, // Pixel spacing - -io.write.bytesPerLine); // Line spacing - } + // Example: + // We have an io description that defines a WRITE and a READ region. + // In this case the READ region extends outside of the defined gdal region, + // meaning we will have to do wrapping - std::shared_ptr TileDataset::preprocess(std::shared_ptr result, const PixelRegion& region) const { - size_t bytesPerLine = _dataLayout.bytesPerPixel * region.numPixels.x; - size_t totalNumBytes = bytesPerLine * region.numPixels.y; + // io.write.region io.read.region + // | | + // V V + // +-------+ +-------+ + // | | | |--------+ + // | | | | | + // | | | | | + // +-------+ +-------+ | + // | | <-- gdalRegion + // | | + // +--------------+ - TilePreprocessData* preprocessData = new TilePreprocessData(); - preprocessData->maxValues.resize(_dataLayout.numRasters); - preprocessData->minValues.resize(_dataLayout.numRasters); - preprocessData->hasMissingData.resize(_dataLayout.numRasters); - - std::vector noDataValues; - noDataValues.resize(_dataLayout.numRasters); - for (size_t c = 0; c < _dataLayout.numRasters; c++) { - preprocessData->maxValues[c] = -FLT_MAX; - preprocessData->minValues[c] = FLT_MAX; - preprocessData->hasMissingData[c] = false; - noDataValues[c] = _dataset->GetRasterBand(1)->GetNoDataValue(); + //LDEBUG(indentation << "-"); + //LDEBUG(indentation << "repeated read: " << io.read.region); + //LDEBUG(indentation << "repeated write: " << io.write.region); + + bool didCutOff = false; + + if (!io.read.region.isInside(gdalRegion)) { + // Loop through each side: left, top, right, bottom + for (int i = 0; i < 4; ++i) { + + // Example: + // We are currently considering the left side of the pixel region + PixelRegion::Side side = (PixelRegion::Side) i; + IODescription cutoff = io.cut(side, gdalRegion.edge(side)); + + // Example: + // We cut off the left part that was outside the gdal region, and we now + // have an additional io description for the cut off region. + // Note that the cut-method used above takes care of the corresponding + // WRITE region for us. + + // cutoff.write.region cutoff.read.region + // | io.write.region | io.read.region + // | | | | + // V V V V + // +-+-----+ +-+-----+ + // | | | | | |--------+ + // | | | | | | | + // | | | | | | | + // +-+-----+ +-+-----+ | + // | | <-- gdalRegion + // | | + // +--------------+ + + if (cutoff.read.region.area() > 0) { + didCutOff = true; + + // Wrap by repeating + PixelRegion::Side oppositeSide = (PixelRegion::Side) ((i + 2) % 4); + + cutoff.read.region.align(oppositeSide, gdalRegion.edge(oppositeSide)); + + // Example: + // The cut off region is wrapped to the opposite side of the region, + // i.e. "repeated". Note that we don't want WRITE region to change, + // we're only wrapping the READ region. + + // cutoff.write.region io.read.region cutoff.read.region + // | io.write.region | | + // | | V V + // V V +-----+ +-+ + // +-+-----+ | |------| | + // | | | | | | | + // | | | | | | | + // | | | +-----+ +-+ + // +-+-----+ | | <-- gdalRegion + // | | + // +--------------+ + + // Example: + // The cutoff region has been repeated along one of its sides, but + // as we can see in this example, it still has a top part outside the + // defined gdal region. This is handled through recursion. + CPLErr err = repeatedRasterIO(rasterBand, cutoff, dataDestination, depth + 1); + + worstError = std::max(worstError, err); + } } - + } + else if (worstError > CPLErr::CE_None) { + LDEBUG(indentation << "Error reading padding: " << worstError); + } + CPLErr err = rasterIO(rasterBand, io, dataDestination); + worstError = std::max(worstError, err); - float noDataValue = _dataset->GetRasterBand(1)->GetNoDataValue(); + // The return error from a repeated rasterIO is ONLY based on the main region, + // which in the usual case will cover the main area of the patch anyway - for (size_t y = 0; y < region.numPixels.y; y++) { - size_t yi = (region.numPixels.y - 1 - y) * bytesPerLine; - size_t i = 0; - for (size_t x = 0; x < region.numPixels.x; x++) { - - for (size_t c = 0; c < _dataLayout.numRasters; c++) { - float val = TileDataType::interpretFloat(_dataLayout.gdalType, &(result->imageData[yi + i])); - if (val != noDataValue) { - preprocessData->maxValues[c] = std::max(val, preprocessData->maxValues[c]); - preprocessData->minValues[c] = std::min(val, preprocessData->minValues[c]); - } - else { - preprocessData->hasMissingData[c] = true; - } - i += _dataLayout.bytesPerDatum; + return err; +} + +CPLErr TileDataset::rasterIO(GDALRasterBand* rasterBand, const IODescription& io, + char* dataDestination) const +{ + PixelRegion gdalRegion = gdalPixelRegion(rasterBand); + + ghoul_assert(io.read.region.isInside(gdalRegion), "write region of bounds!"); + ghoul_assert( + io.write.region.start.x >= 0 && io.write.region.start.y >= 0, + "Invalid write region" + ); + + PixelCoordinate end = io.write.region.end(); + size_t largestIndex = + (end.y - 1) * io.write.bytesPerLine + (end.x - 1) * _dataLayout.bytesPerPixel; + ghoul_assert(largestIndex <= io.write.totalNumBytes, "Invalid write region"); + + char* dataDest = dataDestination; + + // OBS! GDAL reads pixels top to bottom, but we want our pixels bottom to top. + // Therefore, we increment the destination pointer to the last line on in the + // buffer, and the we specify in the rasterIO call that we want negative line + // spacing. Doing this compensates the flipped Y axis + dataDest += (io.write.totalNumBytes - io.write.bytesPerLine); + + // handle requested write region + dataDest -= io.write.region.start.y * io.write.bytesPerLine; // note -= since flipped y axis + dataDest += io.write.region.start.x * _dataLayout.bytesPerPixel; + + return rasterBand->RasterIO( + GF_Read, + io.read.region.start.x, // Begin read x + io.read.region.start.y, // Begin read y + io.read.region.numPixels.x, // width to read x + io.read.region.numPixels.y, // width to read y + dataDest, // Where to put data + io.write.region.numPixels.x, // width to write x in destination + io.write.region.numPixels.y, // width to write y in destination + _dataLayout.gdalType, // Type + _dataLayout.bytesPerPixel, // Pixel spacing + -io.write.bytesPerLine // Line spacing + ); +} + +std::shared_ptr TileDataset::getTileMetaData( + std::shared_ptr rawTile, + const PixelRegion& region) const +{ + size_t bytesPerLine = _dataLayout.bytesPerPixel * region.numPixels.x; + size_t totalNumBytes = bytesPerLine * region.numPixels.y; + + TileMetaData* preprocessData = new TileMetaData(); + preprocessData->maxValues.resize(_dataLayout.numRasters); + preprocessData->minValues.resize(_dataLayout.numRasters); + preprocessData->hasMissingData.resize(_dataLayout.numRasters); + + std::vector noDataValues; + noDataValues.resize(_dataLayout.numRasters); + + for (size_t c = 0; c < _dataLayout.numRasters; c++) { + preprocessData->maxValues[c] = -FLT_MAX; + preprocessData->minValues[c] = FLT_MAX; + preprocessData->hasMissingData[c] = false; + noDataValues[c] = _dataset->GetRasterBand(1)->GetNoDataValue(); + } + + for (size_t y = 0; y < region.numPixels.y; y++) { + size_t yi = (region.numPixels.y - 1 - y) * bytesPerLine; + size_t i = 0; + for (size_t x = 0; x < region.numPixels.x; x++) { + for (size_t c = 0; c < _dataLayout.numRasters; c++) { + float noDataValue = _dataset->GetRasterBand(c + 1)->GetNoDataValue(); + float val = TileDataType::interpretFloat( + _dataLayout.gdalType, + &(rawTile->imageData[yi + i]) + ); + if (val != noDataValue) { + preprocessData->maxValues[c] = std::max( + val, + preprocessData->maxValues[c] + ); + preprocessData->minValues[c] = std::min( + val, + preprocessData->minValues[c] + ); } + else { + preprocessData->hasMissingData[c] = true; + } + i += _dataLayout.bytesPerDatum; } } - - for (size_t c = 0; c < _dataLayout.numRasters; c++) { - if (preprocessData->maxValues[c] > 8800.0f) { - //LDEBUG("Bad preprocess data: " << preprocessData->maxValues[c] << " at " << region.chunkIndex); - } - } - - return std::shared_ptr(preprocessData); } - CPLErr TileDataset::postProcessErrorCheck(std::shared_ptr result, const IODescription& io) const{ - int success; - - double missingDataValue = gdalRasterBand(io.read.overview)->GetNoDataValue(&success); - if (!success) { - missingDataValue = 32767; // missing data value for TERRAIN.wms. Should be specified in xml + for (size_t c = 0; c < _dataLayout.numRasters; c++) { + if (preprocessData->maxValues[c] > 8800.0f) { + //LDEBUG("Bad preprocess data: " << preprocessData->maxValues[c] << " at " << region.tileIndex); } - - bool hasMissingData = false; - - for (size_t c = 0; c < _dataLayout.numRasters; c++) { - hasMissingData |= result->preprocessData->maxValues[c] == missingDataValue; - } - - bool onHighLevel = result->chunkIndex.level > 6; - if (hasMissingData && onHighLevel) { - return CE_Fatal; - } - // ugly test for heightmap overlay - if (_dataLayout.textureFormat.ghoulFormat == Texture::Format::RG) { - // check the alpha - if (result->preprocessData->maxValues[1] == 0.0 - && result->preprocessData->minValues[1] == 0.0) - { - //return CE_Warning; - } - } - return CE_None; } + return std::shared_ptr(preprocessData); +} -} // namespace openspace +CPLErr TileDataset::postProcessErrorCheck(std::shared_ptr rawTile, + const IODescription& io) const +{ + int success; + + double missingDataValue = gdalRasterBand(io.read.overview)->GetNoDataValue(&success); + if (!success) { + // missing data value for TERRAIN.wms. Should be specified in XML + missingDataValue = 32767; + } + + bool hasMissingData = false; + + for (size_t c = 0; c < _dataLayout.numRasters; c++) { + hasMissingData |= rawTile->tileMetaData->maxValues[c] == missingDataValue; + } + + bool onHighLevel = rawTile->tileIndex.level > 6; + if (hasMissingData && onHighLevel) { + return CE_Fatal; + } + // ugly test for heightmap overlay + if (_dataLayout.textureFormat.ghoulFormat == Texture::Format::RG) { + // check the alpha + if (rawTile->tileMetaData->maxValues[1] == 0.0 + && rawTile->tileMetaData->minValues[1] == 0.0) + { + //return CE_Warning; + } + } + return CE_None; +} + +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/tile/tiledataset.h b/modules/globebrowsing/tile/tiledataset.h index 303c32a13b..96b7c4dcc9 100644 --- a/modules/globebrowsing/tile/tiledataset.h +++ b/modules/globebrowsing/tile/tiledataset.h @@ -1,198 +1,198 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __TILE_DATASET_H__ -#define __TILE_DATASET_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___TILE_DATASET___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___TILE_DATASET___H__ -#include -#include -#include -#include -#include - - -#include -#include -#include - -#include +#include +#include +#include #include -#include +#include +#include + +#include +#include + +class GDALDataset; +class GDALRasterBand; namespace openspace { +namespace globebrowsing { - struct TileDataLayout { - TileDataLayout(); - TileDataLayout(GDALDataset* dataSet, GLuint preferredGlType); +class GeodeticPatch; - GDALDataType gdalType; - GLuint glType; +struct TileDataLayout { + TileDataLayout(); + TileDataLayout(GDALDataset* dataSet, GLuint preferredGlType); - size_t bytesPerDatum; - size_t numRasters; - size_t bytesPerPixel; + GDALDataType gdalType; + GLuint glType; - TextureFormat textureFormat; + size_t bytesPerDatum; + size_t numRasters; + size_t bytesPerPixel; + + TextureFormat textureFormat; +}; + +struct IODescription { + struct ReadData { + int overview; + PixelRegion region; + } read; + + struct WriteData { + PixelRegion region; + size_t bytesPerLine; + size_t totalNumBytes; + } write; + + IODescription cut(PixelRegion::Side side, int pos); +}; + +class TileDataset { +public: + struct Configuration { + bool doPreProcessing; + int minimumTilePixelSize; + GLuint dataType = 0; // default = no datatype reinterpretation }; - struct IODescription { - struct ReadData { - int overview; - PixelRegion region; - } read; + /** + * Opens a GDALDataset in readonly mode and calculates meta data required for + * reading tile using a TileIndex. + * + * \param gdalDatasetDesc - A path to a specific file or raw XML describing the dataset + * \param minimumPixelSize - minimum number of pixels per side per tile requested + * \param datatype - datatype for storing pixel data in requested tile + */ + TileDataset(const std::string& gdalDatasetDesc, const Configuration& config); - struct WriteData { - PixelRegion region; - size_t bytesPerLine; - size_t totalNumBytes; - } write; + ~TileDataset(); - IODescription cut(PixelRegion::Side side, int pos); - }; + ////////////////////////////////////////////////////////////////////////////////// + // Public interface // + ////////////////////////////////////////////////////////////////////////////////// + std::shared_ptr readTileData(TileIndex tileIndex); + std::shared_ptr defaultTileData(); + int maxChunkLevel(); + TileDepthTransform getDepthTransform(); + const TileDataLayout& getDataLayout(); + void reset(); + float noDataValueAsFloat(); + + + const static glm::ivec2 tilePixelStartOffset; + const static glm::ivec2 tilePixelSizeDifference; + const static PixelRegion padding; // same as the two above + + +private: + + ////////////////////////////////////////////////////////////////////////////////// + // Initialization // + ////////////////////////////////////////////////////////////////////////////////// + + void initialize(); + void ensureInitialized(); + TileDepthTransform calculateTileDepthTransform(); + int calculateTileLevelDifference(int minimumPixelSize); + + + ////////////////////////////////////////////////////////////////////////////////// + // GDAL helper methods // + ////////////////////////////////////////////////////////////////////////////////// + + void gdalEnsureInitialized(); + void setGdalProxyConfiguration(); + GDALDataset* gdalDataset(const std::string& gdalDatasetDesc); + bool gdalHasOverviews() const; + int gdalOverview(const PixelRange& baseRegionSize) const; + int gdalOverview(const TileIndex& tileIndex) const; + int gdalVirtualOverview(const TileIndex& tileIndex) const; + PixelRegion gdalPixelRegion(const GeodeticPatch& geodeticPatch) const; + PixelRegion gdalPixelRegion(GDALRasterBand* rasterBand) const; + GDALRasterBand* gdalRasterBand(int overview, int raster = 1) const; + + + ////////////////////////////////////////////////////////////////////////////////// + // ReadTileData helper functions // + ////////////////////////////////////////////////////////////////////////////////// + + /** + Returns the geo transform from raster space to projection coordinates as defined + by GDAL. + + If the transform is not available, the function returns a transform to map + the pixel coordinates to cover the whole geodetic lat long space. + */ + std::array getGeoTransform() const; + + PixelCoordinate geodeticToPixel(const Geodetic2& geo) const; + Geodetic2 pixelToGeodetic(const PixelCoordinate& p) const; + IODescription getIODescription(const TileIndex& tileIndex) const; + char* readImageData(IODescription& io, CPLErr& worstError) const; + CPLErr rasterIO(GDALRasterBand* rasterBand, const IODescription& io, char* dst) const; + CPLErr repeatedRasterIO(GDALRasterBand* rasterBand, const IODescription& io, char* dst, int depth = 0) const; + std::shared_ptr getTileMetaData(std::shared_ptr result, const PixelRegion& region) const; + CPLErr postProcessErrorCheck(std::shared_ptr ioResult, const IODescription& io) const; - using namespace ghoul::opengl; - using namespace ghoul::filesystem; - - - class TileDataset { - public: - - struct Configuration { - bool doPreProcessing; - int minimumTilePixelSize; - GLuint dataType = 0; // default = no datatype reinterpretation - }; + ////////////////////////////////////////////////////////////////////////////////// + // Member variables // + ////////////////////////////////////////////////////////////////////////////////// + // init data + struct InitData { + std::string initDirectory; + std::string gdalDatasetDesc; + int minimumPixelSize; + GLuint dataType; + } _initData; - /** - * Opens a GDALDataset in readonly mode and calculates meta data required for - * reading tile using a ChunkIndex. - * - * \param gdalDatasetDesc - A path to a specific file or raw XML describing the dataset - * \param minimumPixelSize - minimum number of pixels per side per tile requested - * \param datatype - datatype for storing pixel data in requested tile - */ - TileDataset(const std::string& gdalDatasetDesc, const Configuration& config); + struct Cached { + int _maxLevel = -1; + double _tileLevelDifference; + } _cached; - ~TileDataset(); + const Configuration _config; - ////////////////////////////////////////////////////////////////////////////////// - // Public interface // - ////////////////////////////////////////////////////////////////////////////////// - std::shared_ptr readTileData(ChunkIndex chunkIndex); - std::shared_ptr defaultTileData(); - int maxChunkLevel(); - TileDepthTransform getDepthTransform(); - const TileDataLayout& getDataLayout(); - void reset(); - - - const static glm::ivec2 tilePixelStartOffset; - const static glm::ivec2 tilePixelSizeDifference; - const static PixelRegion padding; // same as the two above - - - private: - - ////////////////////////////////////////////////////////////////////////////////// - // Initialization // - ////////////////////////////////////////////////////////////////////////////////// - - void initialize(); - void ensureInitialized(); - TileDepthTransform calculateTileDepthTransform(); - int calculateTileLevelDifference(int minimumPixelSize); - - - ////////////////////////////////////////////////////////////////////////////////// - // GDAL helper methods // - ////////////////////////////////////////////////////////////////////////////////// - - void gdalEnsureInitialized(); - GDALDataset* gdalDataset(const std::string& gdalDatasetDesc); - bool gdalHasOverviews() const; - int gdalOverview(const PixelRange& baseRegionSize) const; - int gdalOverview(const ChunkIndex& chunkIndex) const; - int gdalVirtualOverview(const ChunkIndex& chunkIndex) const; - PixelRegion gdalPixelRegion(const GeodeticPatch& geodeticPatch) const; - PixelRegion gdalPixelRegion(GDALRasterBand* rasterBand) const; - GDALRasterBand* gdalRasterBand(int overview, int raster = 1) const; - - - ////////////////////////////////////////////////////////////////////////////////// - // ReadTileData helper functions // - ////////////////////////////////////////////////////////////////////////////////// - - PixelCoordinate geodeticToPixel(const Geodetic2& geo) const; - Geodetic2 pixelToGeodetic(const PixelCoordinate& p) const; - IODescription getIODescription(const ChunkIndex& chunkIndex) const; - char* readImageData(IODescription& io, CPLErr& worstError) const; - CPLErr rasterIO(GDALRasterBand* rasterBand, const IODescription& io, char* dst) const; - CPLErr repeatedRasterIO(GDALRasterBand* rasterBand, const IODescription& io, char* dst, int depth = 0) const; - std::shared_ptr preprocess(std::shared_ptr result, const PixelRegion& region) const; - CPLErr postProcessErrorCheck(std::shared_ptr ioResult, const IODescription& io) const; - - - - ////////////////////////////////////////////////////////////////////////////////// - // Member variables // - ////////////////////////////////////////////////////////////////////////////////// - - // init data - struct InitData { - std::string initDirectory; - std::string gdalDatasetDesc; - int minimumPixelSize; - GLuint dataType; - } _initData; - - struct Cached { - int _maxLevel = -1; - double _tileLevelDifference; - } _cached; - - const Configuration _config; - - - GDALDataset* _dataset; - TileDepthTransform _depthTransform; - TileDataLayout _dataLayout; - - static bool GdalHasBeenInitialized; - bool hasBeenInitialized; - }; - + GDALDataset* _dataset; + TileDepthTransform _depthTransform; + TileDataLayout _dataLayout; + static bool GdalHasBeenInitialized; + bool hasBeenInitialized; +}; +} // namespace globebrowsing } // namespace openspace - - -#endif // __TILE_DATASET_H__ \ No newline at end of file +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___TILE_DATASET___H__ diff --git a/modules/globebrowsing/tile/tiledatatype.cpp b/modules/globebrowsing/tile/tiledatatype.cpp index 726cf2e17e..5f1b8e798d 100644 --- a/modules/globebrowsing/tile/tiledatatype.cpp +++ b/modules/globebrowsing/tile/tiledatatype.cpp @@ -22,6 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ +#include + #include #include @@ -29,10 +31,6 @@ #include // abspath #include - -#include - - #include #include @@ -40,163 +38,245 @@ #include #include - - - - namespace { - const std::string _loggerCat = "TileIOResult"; + const std::string _loggerCat = "RawTile"; } - - namespace openspace { - float TileDataType::interpretFloat(GDALDataType gdalType, const char* src) { - switch (gdalType) { - case GDT_Byte: return static_cast(*reinterpret_cast(src)); - case GDT_UInt16: return static_cast(*reinterpret_cast(src)); - case GDT_Int16: return static_cast(*reinterpret_cast(src)); - case GDT_UInt32: return static_cast(*reinterpret_cast(src)); - case GDT_Int32: return static_cast(*reinterpret_cast(src)); - case GDT_Float32: return static_cast(*reinterpret_cast(src)); - case GDT_Float64: return static_cast(*reinterpret_cast(src)); +namespace globebrowsing { + +float TileDataType::interpretFloat(GDALDataType gdalType, const char* src) { + switch (gdalType) { + case GDT_Byte: + return static_cast(*reinterpret_cast(src)); + case GDT_UInt16: + return static_cast(*reinterpret_cast(src)); + case GDT_Int16: + return static_cast(*reinterpret_cast(src)); + case GDT_UInt32: + return static_cast(*reinterpret_cast(src)); + case GDT_Int32: + return static_cast(*reinterpret_cast(src)); + case GDT_Float32: + return static_cast(*reinterpret_cast(src)); + case GDT_Float64: + return static_cast(*reinterpret_cast(src)); default: - LERROR("Unknown data type"); ghoul_assert(false, "Unknown data type"); - return -1.0; } - } +} - - - size_t TileDataType::numberOfBytes(GDALDataType gdalType) { - switch (gdalType) { - case GDT_Byte: return sizeof(GLubyte); - case GDT_UInt16: return sizeof(GLushort); - case GDT_Int16: return sizeof(GLshort); - case GDT_UInt32: return sizeof(GLuint); - case GDT_Int32: return sizeof(GLint); - case GDT_Float32: return sizeof(GLfloat); - case GDT_Float64: return sizeof(GLdouble); +size_t TileDataType::numberOfBytes(GDALDataType gdalType) { + switch (gdalType) { + case GDT_Byte: + return sizeof(GLubyte); + case GDT_UInt16: + return sizeof(GLushort); + case GDT_Int16: + return sizeof(GLshort); + case GDT_UInt32: + return sizeof(GLuint); + case GDT_Int32: + return sizeof(GLint); + case GDT_Float32: + return sizeof(GLfloat); + case GDT_Float64: + return sizeof(GLdouble); default: - LERROR("Unknown data type"); ghoul_assert(false, "Unknown data type"); - return -1; - } - } - size_t TileDataType::getMaximumValue(GDALDataType gdalType) { - switch (gdalType) { - case GDT_Byte: return 1 << 8; - case GDT_UInt16: return 1 << 16; - case GDT_Int16: return 1 << 15; - case GDT_UInt32: return 1 << 32; - case GDT_Int32: return 1 << 31; + } +} + +size_t TileDataType::getMaximumValue(GDALDataType gdalType) { + switch (gdalType) { + case GDT_Byte: + return 1 << 8; + case GDT_UInt16: + return 1 << 16; + case GDT_Int16: + return 1 << 15; + case GDT_UInt32: + return 1 << 32; + case GDT_Int32: + return 1 << 31; default: - LERROR("Unknown data type"); - return -1; - } + ghoul_assert(false, "Unknown data type"); + } +} +TextureFormat TileDataType::getTextureFormat( + int rasterCount, GDALDataType gdalType) +{ + TextureFormat format; - TextureFormat TileDataType::getTextureFormat( - int rasterCount, GDALDataType gdalType) - { - TextureFormat format; - - switch (rasterCount) { + switch (rasterCount) { case 1: // Red format.ghoulFormat = Texture::Format::Red; switch (gdalType) { - case GDT_Byte: format.glFormat = GL_R8; break; - case GDT_UInt16: format.glFormat = GL_R16UI; break; - case GDT_Int16: format.glFormat = GL_R16_SNORM; break; - case GDT_UInt32: format.glFormat = GL_R32UI; break; - case GDT_Int32: format.glFormat = GL_R32I; break; - case GDT_Float32: format.glFormat = GL_R32F; break; - //case GDT_Float64: format.glFormat = GL_RED; break; // No representation of 64 bit float? - default: LERROR("GDAL data type unknown to OpenGL: " << gdalType); + case GDT_Byte: + format.glFormat = GL_R8; + break; + case GDT_UInt16: + format.glFormat = GL_R16UI; + break; + case GDT_Int16: + format.glFormat = GL_R16_SNORM; + break; + case GDT_UInt32: + format.glFormat = GL_R32UI; + break; + case GDT_Int32: + format.glFormat = GL_R32I; + break; + case GDT_Float32: + format.glFormat = GL_R32F; + break; + // No representation of 64 bit float? + //case GDT_Float64: + // format.glFormat = GL_RED; + // break; + default: + LERROR("GDAL data type unknown to OpenGL: " << gdalType); } break; case 2: format.ghoulFormat = Texture::Format::RG; switch (gdalType) { - case GDT_Byte: format.glFormat = GL_RG8; break; - case GDT_UInt16: format.glFormat = GL_RG16UI; break; - case GDT_Int16: format.glFormat = GL_RG16_SNORM; break; - case GDT_UInt32: format.glFormat = GL_RG32UI; break; - case GDT_Int32: format.glFormat = GL_RG32I; break; - case GDT_Float32: format.glFormat = GL_RG32F; break; - case GDT_Float64: format.glFormat = GL_RED; break; // No representation of 64 bit float? - default: LERROR("GDAL data type unknown to OpenGL: " << gdalType); + case GDT_Byte: + format.glFormat = GL_RG8; + break; + case GDT_UInt16: + format.glFormat = GL_RG16UI; + break; + case GDT_Int16: + format.glFormat = GL_RG16_SNORM; + break; + case GDT_UInt32: + format.glFormat = GL_RG32UI; + break; + case GDT_Int32: + format.glFormat = GL_RG32I; + break; + case GDT_Float32: + format.glFormat = GL_RG32F; + break; + case GDT_Float64: + format.glFormat = GL_RED; + break; + default: + LERROR("GDAL data type unknown to OpenGL: " << gdalType); } break; case 3: format.ghoulFormat = Texture::Format::RGB; switch (gdalType) { - case GDT_Byte: format.glFormat = GL_RGB8; break; - case GDT_UInt16: format.glFormat = GL_RGB16UI; break; - case GDT_Int16: format.glFormat = GL_RGB16_SNORM; break; - case GDT_UInt32: format.glFormat = GL_RGB32UI; break; - case GDT_Int32: format.glFormat = GL_RGB32I; break; - case GDT_Float32: format.glFormat = GL_RGB32F; break; - // case GDT_Float64: format.glFormat = GL_RED; break;// No representation of 64 bit float? - default: LERROR("GDAL data type unknown to OpenGL: " << gdalType); + case GDT_Byte: + format.glFormat = GL_RGB8; + break; + case GDT_UInt16: + format.glFormat = GL_RGB16UI; + break; + case GDT_Int16: + format.glFormat = GL_RGB16_SNORM; + break; + case GDT_UInt32: + format.glFormat = GL_RGB32UI; + break; + case GDT_Int32: + format.glFormat = GL_RGB32I; + break; + case GDT_Float32: + format.glFormat = GL_RGB32F; + break; + // No representation of 64 bit float? + //case GDT_Float64: + // format.glFormat = GL_RED; + // break; + default: + LERROR("GDAL data type unknown to OpenGL: " << gdalType); } break; case 4: format.ghoulFormat = Texture::Format::RGBA; switch (gdalType) { - case GDT_Byte: format.glFormat = GL_RGBA8; break; - case GDT_UInt16: format.glFormat = GL_RGBA16UI; break; - case GDT_Int16: format.glFormat = GL_RGB16_SNORM; break; - case GDT_UInt32: format.glFormat = GL_RGBA32UI; break; - case GDT_Int32: format.glFormat = GL_RGBA32I; break; - case GDT_Float32: format.glFormat = GL_RGBA32F; break; - case GDT_Float64: format.glFormat = GL_RED; break; // No representation of 64 bit float? - default: LERROR("GDAL data type unknown to OpenGL: " << gdalType); + case GDT_Byte: + format.glFormat = GL_RGBA8; + break; + case GDT_UInt16: + format.glFormat = GL_RGBA16UI; + break; + case GDT_Int16: + format.glFormat = GL_RGB16_SNORM; + break; + case GDT_UInt32: + format.glFormat = GL_RGBA32UI; + break; + case GDT_Int32: + format.glFormat = GL_RGBA32I; + break; + case GDT_Float32: + format.glFormat = GL_RGBA32F; + break; + // No representation of 64 bit float? + //case GDT_Float64: + // format.glFormat = GL_RED; + // break; + default: + LERROR("GDAL data type unknown to OpenGL: " << gdalType); } break; default: LERROR("Unknown number of channels for OpenGL texture: " << rasterCount); break; - } - return format; } + return format; +} - - - - - - GLuint TileDataType::getOpenGLDataType(GDALDataType gdalType) { - switch (gdalType) { - case GDT_Byte: return GL_UNSIGNED_BYTE; - case GDT_UInt16: return GL_UNSIGNED_SHORT; - case GDT_Int16: return GL_SHORT; - case GDT_UInt32: return GL_UNSIGNED_INT; - case GDT_Int32: return GL_INT; - case GDT_Float32: return GL_FLOAT; - case GDT_Float64: return GL_DOUBLE; +GLuint TileDataType::getOpenGLDataType(GDALDataType gdalType) { + switch (gdalType) { + case GDT_Byte: + return GL_UNSIGNED_BYTE; + case GDT_UInt16: + return GL_UNSIGNED_SHORT; + case GDT_Int16: + return GL_SHORT; + case GDT_UInt32: + return GL_UNSIGNED_INT; + case GDT_Int32: + return GL_INT; + case GDT_Float32: + return GL_FLOAT; + case GDT_Float64: + return GL_DOUBLE; default: LERROR("GDAL data type unknown to OpenGL: " << gdalType); return GL_UNSIGNED_BYTE; - } } +} - GDALDataType TileDataType::getGdalDataType(GLuint glType) { - switch (glType) { - case GL_UNSIGNED_BYTE: return GDT_Byte; - case GL_UNSIGNED_SHORT: return GDT_UInt16; - case GL_SHORT: return GDT_Int16; - case GL_UNSIGNED_INT: return GDT_UInt32; - case GL_INT: return GDT_Int32; - case GL_FLOAT: return GDT_Float32; - case GL_DOUBLE: return GDT_Float64; +GDALDataType TileDataType::getGdalDataType(GLuint glType) { + switch (glType) { + case GL_UNSIGNED_BYTE: + return GDT_Byte; + case GL_UNSIGNED_SHORT: + return GDT_UInt16; + case GL_SHORT: + return GDT_Int16; + case GL_UNSIGNED_INT: + return GDT_UInt32; + case GL_INT: + return GDT_Int32; + case GL_FLOAT: + return GDT_Float32; + case GL_DOUBLE: + return GDT_Float64; default: LERROR("OpenGL data type unknown to GDAL: " << glType); return GDT_Unknown; - } } +} -} // namespace openspace +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/tile/tiledatatype.h b/modules/globebrowsing/tile/tiledatatype.h index 1df7a0d5bd..5c26df5a37 100644 --- a/modules/globebrowsing/tile/tiledatatype.h +++ b/modules/globebrowsing/tile/tiledatatype.h @@ -1,60 +1,54 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __TILE_DATA_TYPE_H__ -#define __TILE_DATA_TYPE_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___TILE_DATA_TYPE___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___TILE_DATA_TYPE___H__ -#include +#include -#include -#include - -#include "gdal_priv.h" +#include +#include namespace openspace { - - struct TileDataType { +namespace globebrowsing { - static GLuint getOpenGLDataType(GDALDataType gdalType); +struct TileDataType { + static GLuint getOpenGLDataType(GDALDataType gdalType); - static GDALDataType getGdalDataType(GLuint glType); + static GDALDataType getGdalDataType(GLuint glType); - static TextureFormat getTextureFormat(int rasterCount, GDALDataType gdalType); + static TextureFormat getTextureFormat(int rasterCount, GDALDataType gdalType); - static size_t getMaximumValue(GDALDataType gdalType); + static size_t getMaximumValue(GDALDataType gdalType); - static size_t numberOfBytes(GDALDataType gdalType); + static size_t numberOfBytes(GDALDataType gdalType); - static float interpretFloat(GDALDataType gdalType, const char* src); - - }; + static float interpretFloat(GDALDataType gdalType, const char* src); +}; +} // namespace globebrowsing } // namespace openspace - - - - -#endif // __TILE_DATA_TYPE_H__ \ No newline at end of file +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___TILE_DATA_TYPE___H__ diff --git a/modules/globebrowsing/tile/tiledepthtransform.h b/modules/globebrowsing/tile/tiledepthtransform.h index c283600164..2d71672b17 100644 --- a/modules/globebrowsing/tile/tiledepthtransform.h +++ b/modules/globebrowsing/tile/tiledepthtransform.h @@ -22,12 +22,18 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __TILEDEPTHTRANSFORM_H__ -#define __TILEDEPTHTRANSFORM_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___TILEDEPTHTRANSFORM___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___TILEDEPTHTRANSFORM___H__ + +namespace openspace { +namespace globebrowsing { struct TileDepthTransform { float depthScale; float depthOffset; }; -#endif // __TILEDEPTHTRANSFORM_H__ +} // namespace globebrowsing +} // namespace openspace + +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___TILEDEPTHTRANSFORM___H__ diff --git a/modules/globebrowsing/tile/tilediskcache.cpp b/modules/globebrowsing/tile/tilediskcache.cpp index f4504a542c..63e172f0fe 100644 --- a/modules/globebrowsing/tile/tilediskcache.cpp +++ b/modules/globebrowsing/tile/tilediskcache.cpp @@ -1,125 +1,115 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ #include -#include +#include -#include +#include -#include #include -#include - -namespace { - const std::string _loggerCat = "TileDiskCache"; -} +using namespace ghoul::filesystem; namespace openspace { - const std::string TileDiskCache::CACHE_ROOT = "tilecache"; +namespace globebrowsing { +const std::string TileDiskCache::CACHE_ROOT = "tilecache"; - TileDiskCache::TileDiskCache(const std::string& name) - : _name(name) - { - if (!FileSystem::isInitialized()) { - FileSystem::initialize(); - } - - std::string pathToCacheDir = FileSys.pathByAppendingComponent(CACHE_ROOT, name); - Directory cacheDir(pathToCacheDir, Directory::RawPath::No); - if (!FileSys.directoryExists(cacheDir)) { - FileSys.createDirectory(pathToCacheDir, FileSystem::Recursive::Yes); - } - _cacheDir = cacheDir; +TileDiskCache::TileDiskCache(const std::string& name) + : _name(name) +{ + std::string pathToCacheDir = FileSys.pathByAppendingComponent(CACHE_ROOT, name); + Directory cacheDir(pathToCacheDir, Directory::RawPath::No); + if (!FileSys.directoryExists(cacheDir)) { + FileSys.createDirectory(pathToCacheDir, FileSystem::Recursive::Yes); } + _cacheDir = cacheDir; +} - bool TileDiskCache::has(const ChunkIndex& chunkIndex) const { - File metaFile = getMetaDataFile(chunkIndex); - return FileSys.fileExists(metaFile); +bool TileDiskCache::has(const TileIndex& tileIndex) const { + File metaFile = getMetaDataFile(tileIndex); + return FileSys.fileExists(metaFile); +} + +std::shared_ptr TileDiskCache::get(const TileIndex& tileIndex) { + File metaDataFile = getMetaDataFile(tileIndex); + File dataFile = getDataFile(tileIndex); + if (FileSys.fileExists(metaDataFile) && FileSys.fileExists(dataFile)) { + // read meta + std::ifstream ifsMeta; + ifsMeta.open(metaDataFile.path(), std::ifstream::in); + RawTile res = RawTile::deserializeMetaData(ifsMeta); + ifsMeta.close(); + + // read data + std::ifstream ifsData; + ifsData.open(dataFile.path(), std::ifstream::binary); + char * buffer = new char[res.nBytesImageData]; + ifsData.read(buffer, res.nBytesImageData); + res.imageData = buffer; + + return std::make_shared(res); } + return nullptr; +} +bool TileDiskCache::put(const TileIndex& tileIndex, std::shared_ptr rawTile) { + File metaDataFile = getMetaDataFile(tileIndex); + if (!FileSys.fileExists(metaDataFile)) { + std::ofstream ofsMeta; + ofsMeta.open(metaDataFile.path()); + rawTile->serializeMetaData(ofsMeta); + ofsMeta.close(); - std::shared_ptr TileDiskCache::get(const ChunkIndex& chunkIndex) { - File metaDataFile = getMetaDataFile(chunkIndex); - File dataFile = getDataFile(chunkIndex); - if (FileSys.fileExists(metaDataFile) && FileSys.fileExists(dataFile)) { - // read meta - std::ifstream ifsMeta; - ifsMeta.open(metaDataFile.path(), std::ifstream::in); - TileIOResult res = TileIOResult::deserializeMetaData(ifsMeta); - ifsMeta.close(); - - // read data - std::ifstream ifsData; - ifsData.open(dataFile.path(), std::ifstream::binary); - char * buffer = new char[res.nBytesImageData]; - ifsData.read(buffer, res.nBytesImageData); - res.imageData = buffer; - - return std::make_shared(res); - } - return nullptr; + std::ofstream ofsData; + File dataFile = getDataFile(tileIndex); + ofsData.open(dataFile.path(), std::ofstream::binary); + char* data = (char*)rawTile->imageData; + ofsData.write(data, rawTile->nBytesImageData); + ofsData.close(); + return true; } + return false; +} - bool TileDiskCache::put(const ChunkIndex& chunkIndex, std::shared_ptr tileIOResult) { - File metaDataFile = getMetaDataFile(chunkIndex); - if (!FileSys.fileExists(metaDataFile)) { - std::ofstream ofsMeta; - ofsMeta.open(metaDataFile.path()); - tileIOResult->serializeMetaData(ofsMeta); - ofsMeta.close(); - - std::ofstream ofsData; - File dataFile = getDataFile(chunkIndex); - ofsData.open(dataFile.path(), std::ofstream::binary); - char * data = (char*)tileIOResult->imageData; - ofsData.write(data, tileIOResult->nBytesImageData); - ofsData.close(); - return true; - } - return false; - } - - std::string TileDiskCache::getFilePath(const ChunkIndex& chunkIndex) const { - std::stringstream ss; - ss << chunkIndex.level; - ss << "_" << chunkIndex.x; - ss << "_" << chunkIndex.y; - std::string filePath = FileSys.pathByAppendingComponent(_cacheDir.path(), ss.str()); - return filePath; - } - - File TileDiskCache::getMetaDataFile(const ChunkIndex& chunkIndex) const { - return File(getFilePath(chunkIndex) + ".meta"); - } - - File TileDiskCache::getDataFile(const ChunkIndex& chunkIndex) const { - return File(getFilePath(chunkIndex) + ".data"); - } +std::string TileDiskCache::getFilePath(const TileIndex& tileIndex) const { + std::stringstream ss; + ss << tileIndex.level; + ss << "_" << tileIndex.x; + ss << "_" << tileIndex.y; + std::string filePath = FileSys.pathByAppendingComponent(_cacheDir.path(), ss.str()); + return filePath; +} +File TileDiskCache::getMetaDataFile(const TileIndex& tileIndex) const { + return File(getFilePath(tileIndex) + ".meta"); +} +File TileDiskCache::getDataFile(const TileIndex& tileIndex) const { + return File(getFilePath(tileIndex) + ".data"); +} +} // namespace globebrowsing } // namespace openspace diff --git a/modules/globebrowsing/tile/tilediskcache.h b/modules/globebrowsing/tile/tilediskcache.h index 557aab00ef..71880d8036 100644 --- a/modules/globebrowsing/tile/tilediskcache.h +++ b/modules/globebrowsing/tile/tilediskcache.h @@ -1,66 +1,63 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __TILE_DISK_CACHE_H__ -#define __TILE_DISK_CACHE_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___TILE_DISK_CACHE___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___TILE_DISK_CACHE___H__ +#include +#include -#include -#include - -#include - +#include namespace openspace { +namespace globebrowsing { -struct TileIOResult; +struct TileIndex; +struct RawTile; - using namespace ghoul::filesystem; - - class TileDiskCache { - public: - TileDiskCache(const std::string& name); +class TileDiskCache { +public: + TileDiskCache(const std::string& name); - std::shared_ptr get(const ChunkIndex& chunkIndex); - bool has(const ChunkIndex& chunkIndex) const; - bool put(const ChunkIndex& chunkIndex, std::shared_ptr tileIOResult); - + std::shared_ptr get(const TileIndex& tileIndex); + bool has(const TileIndex& tileIndex) const; + bool put(const TileIndex& tileIndex, std::shared_ptr rawTile); - static const std::string CACHE_ROOT; + static const std::string CACHE_ROOT; - private: - const std::string _name; +private: + const std::string _name; - Directory _cacheDir; + ghoul::filesystem::Directory _cacheDir; - std::string getFilePath(const ChunkIndex& chunkIndex) const; - File getMetaDataFile(const ChunkIndex& chunkIndex) const; - File getDataFile(const ChunkIndex& chunkIndex) const; + std::string getFilePath(const TileIndex& tileIndex) const; + ghoul::filesystem::File getMetaDataFile(const TileIndex& tileIndex) const; + ghoul::filesystem::File getDataFile(const TileIndex& tileIndex) const; - }; +}; -} // namespace openspace +} // namespace globebrowsing +} // namespace openspace - -#endif // __TILE_DISK_CACHE_H__ \ No newline at end of file +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___TILE_DISK_CACHE___H__ diff --git a/modules/globebrowsing/tile/tileindex.cpp b/modules/globebrowsing/tile/tileindex.cpp new file mode 100644 index 0000000000..4ae8590415 --- /dev/null +++ b/modules/globebrowsing/tile/tileindex.cpp @@ -0,0 +1,160 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include + +namespace { + const char* KeyLevel = "Level"; + const char* KeyX = "X"; + const char* KeyY = "Y"; +} + +namespace openspace { +namespace globebrowsing { + +TileIndex::TileIndex(int x, int y, int level) + : x(x), y(y), level(level) +{} + +TileIndex::TileIndex(const TileIndex& other) + : x(other.x), y(other.y), level(other.level) +{} + +TileIndex::TileIndex(const Geodetic2& point, int level) + : level(level) +{ + int numIndicesAtLevel = 1 << level; + double u = 0.5 + point.lon / (2 * glm::pi()); + double v = 0.25 - point.lat / (2 * glm::pi()); + double xIndexSpace = u * numIndicesAtLevel; + double yIndexSpace = v * numIndicesAtLevel; + + x = floor(xIndexSpace); + y = floor(yIndexSpace); +} + +TileIndex::TileIndex(const ghoul::Dictionary& dict) { + level = static_cast(dict.value(KeyLevel)); + x = static_cast(dict.value(KeyX)); + y = static_cast(dict.value(KeyY)); +} + +TileIndex TileIndex::child(Quad q) const { + return TileIndex(2 * x + q % 2, 2 * y + q / 2, level + 1); +} + +TileIndex TileIndex::parent() const { + //ghoul_assert(level > 0, "tile at level 0 has no parent!"); + return TileIndex(x / 2, y / 2, level - 1); +} + +TileIndex& TileIndex::operator--() { + x /= 2; + y /= 2; + level--; + return *this; +} + +TileIndex TileIndex::operator--(int) { + TileIndex tmp(*this); + --(*this); + return tmp; +} + +TileIndex& TileIndex::operator-=(unsigned int levels) { + x <<= levels; + y <<= levels; + level -= levels; + return *this; +} + +glm::vec2 TileIndex::positionRelativeParent() const { + // In OpenGL, positive y direction is up + return glm::vec2(isEastChild() ? 0.5 : 0, isNorthChild() ? 0.5 : 0); +} + +TileIndex TileIndex::getRelatedTile(int deltaX, int deltaY) const { + int indicesAtThisLevel = 1 << level; + int newX = (indicesAtThisLevel + x + deltaX) % indicesAtThisLevel; + int newY = (indicesAtThisLevel + y + deltaY) % indicesAtThisLevel; + return TileIndex(newX, newY, level); +} + +int TileIndex::manhattan(const TileIndex& other) const { + ghoul_assert(level == other.level, "makes no sense if not on same level"); + return std::abs(x - other.x) + std::abs(y - other.y); +} + +/** +Creates a hash which can be used as key in hash maps. + ++-------+------------+-------+------------+ +| USAGE | BIT RANGE | #BITS | MAX VALUE | ++-------+------------+-------+------------+ +| level | 0 - 5 | 5 | 31 | +| x | 5 - 35 | 30 | 1073741824 | +| y | 35 - 64 | 29 | 536870912 | ++-------+------------+-------+------------+ + +*/ +TileHashKey TileIndex::hashKey() const { + TileHashKey key = 0LL; + key |= level; + key |= x << 5; + key |= ((TileHashKey)y) << 35; + return key; +} + +std::string TileIndex::toString() const { + std::stringstream ss; + for (int i = level; i > 0; i--) { + char digit = '0'; + int mask = 1 << (i - 1); + if ((x & mask) != 0) { + digit++; + } + if ((y & mask) != 0) { + digit++; + digit++; + } + ss << digit; + } + return ss.str(); +} + +bool TileIndex::operator==(const TileIndex& other) const { + return x == other.x && y == other.y && level == other.level; +} + +std::ostream& operator<<(std::ostream& os, const TileIndex& ci) { + os << "{ x = " << ci.x << ", y = " << ci.y << ", level = " << ci.level << " }"; + return os; +} + +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/chunk/chunkindex.h b/modules/globebrowsing/tile/tileindex.h similarity index 63% rename from modules/globebrowsing/chunk/chunkindex.h rename to modules/globebrowsing/tile/tileindex.h index 24b5ba4304..d8d3314c2f 100644 --- a/modules/globebrowsing/chunk/chunkindex.h +++ b/modules/globebrowsing/tile/tileindex.h @@ -22,19 +22,18 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __CHUNK_INDEX_H__ -#define __CHUNK_INDEX_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___TILE_INDEX___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___TILE_INDEX___H__ -#include - -#include -#include +#include #include - +namespace ghoul { + class Dictionary; +} namespace openspace { - +namespace globebrowsing { class Geodetic2; @@ -52,75 +51,76 @@ enum CardinalDirection { SOUTH, }; +using TileHashKey = uint64_t; - -using ChunkHashKey = uint64_t; - - -struct ChunkIndex { - - +struct TileIndex { int x, y, level; + TileIndex(int x = 0, int y = 0, int level = 0); + TileIndex(const TileIndex& other); - ChunkIndex() : x(0), y(0), level(0) { } - ChunkIndex(int x, int y, int level) : x(x), y(y), level(level) { } - ChunkIndex(const ChunkIndex& other) : x(other.x), y(other.y), level(other.level) { } - ChunkIndex(const Geodetic2& point, int level); + /** + * Creates the geodetic tile index for the Geodetic patch that covers the + * point p at the specified level + */ + TileIndex(const Geodetic2& point, int level); + + /** + * Initializes a TileIndex from a Dictionary + */ + TileIndex(const ghoul::Dictionary& dict); bool hasParent() const { return level > 0; } - ChunkIndex parent() const; + TileIndex parent() const; - ChunkIndex& operator--(); - ChunkIndex operator--(int); + TileIndex& operator--(); + TileIndex operator--(int); - ChunkIndex& operator-=(unsigned int levels); + TileIndex& operator-=(unsigned int levels); - bool isWestChild() const { + inline bool isWestChild() const { return x % 2 == 0; } - bool isEastChild() const { + inline bool isEastChild() const { return x % 2 == 1; } - bool isNorthChild() const { + inline bool isNorthChild() const { return y % 2 == 0; } - bool isSouthChild() const { + inline bool isSouthChild() const { return y % 2 == 1; } + TileIndex child(Quad q) const; - ChunkIndex child(Quad q) const; + glm::vec2 positionRelativeParent() const; std::string toString() const; /** - Gets the tile at a specified offset from this tile. - Accepts delta indices ranging from [-2^level, Infinity[ - */ - ChunkIndex getRelatedTile(int deltaX, int deltaY) const; + * Gets the tile at a specified offset from this tile. + * Accepts delta indices ranging from [-2^level, Infinity[ + */ + TileIndex getRelatedTile(int deltaX, int deltaY) const; - int manhattan(const ChunkIndex& other) const; + int manhattan(const TileIndex& other) const; - ChunkHashKey hashKey() const; + TileHashKey hashKey() const; - bool operator==(const ChunkIndex& other) const; + bool operator==(const TileIndex& other) const; }; +std::ostream& operator<<(std::ostream& os, const TileIndex& ti); -std::ostream& operator<<(std::ostream& os, const ChunkIndex& ti); - - +} // namespace globebrowsing } // namespace openspace - - -#endif // __CHUNK_INDEX_H__ +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___TILE_INDEX___H__ diff --git a/modules/globebrowsing/tile/tileioresult.cpp b/modules/globebrowsing/tile/tileioresult.cpp deleted file mode 100644 index d68e293263..0000000000 --- a/modules/globebrowsing/tile/tileioresult.cpp +++ /dev/null @@ -1,145 +0,0 @@ - /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ - -#include -#include - -#include -#include // abspath -#include - -#include - -#include - -#include - -#include -#include - - - - - -namespace { - const std::string _loggerCat = "TileIOResult"; -} - - - -namespace openspace { - void TilePreprocessData::serialize(std::ostream& os) { - os << maxValues.size() << std::endl; - for (float f : maxValues) { - os << f << " "; - } - os << std::endl; - for (float f : minValues) { - os << f << " "; - } - os << std::endl; - } - - - TilePreprocessData TilePreprocessData::deserialize(std::istream& is) { - TilePreprocessData res; - int n; is >> n; - res.maxValues.resize(n); - for (int i = 0; i < n; i++) { - is >> res.maxValues[i]; - } - res.minValues.resize(n); - for (int i = 0; i < n; i++) { - is >> res.minValues[i]; - } - - return std::move(res); - } - - TileIOResult::TileIOResult() - : imageData(nullptr) - , dimensions(0, 0, 0) - , preprocessData(nullptr) - , chunkIndex(0, 0, 0) - , error(CE_None) - , nBytesImageData(0) - { - - } - - - - TileIOResult TileIOResult::createDefaultRes() { - TileIOResult defaultRes; - int w = 8; - int h = 8; - defaultRes.dimensions = glm::uvec3(w, h, 1); - defaultRes.nBytesImageData = w * h * 1 * 3 * 4; // assume max 3 channels, max 4 bytes per pixel - defaultRes.imageData = new char[defaultRes.nBytesImageData]; - std::fill_n((char*)defaultRes.imageData, defaultRes.nBytesImageData, 0); - return std::move(defaultRes); - } - - - - void TileIOResult::serializeMetaData(std::ostream& os) { - os << dimensions.x << " " << dimensions.y << " " << dimensions.z << std::endl; - os << chunkIndex.x << " " << chunkIndex.y << " " << chunkIndex.level << std::endl; - os << error << std::endl; - - // preprocess data - os << (preprocessData != nullptr) << std::endl; - if (preprocessData != nullptr) { - preprocessData->serialize(os); - } - - os << nBytesImageData << std::endl; - } - - - TileIOResult TileIOResult::deserializeMetaData(std::istream& is) { - TileIOResult res; - is >> res.dimensions.x >> res.dimensions.y >> res.dimensions.z; - is >> res.chunkIndex.x >> res.chunkIndex.y >> res.chunkIndex.level; - int err; is >> err; res.error = (CPLErr) err; - - res.preprocessData = nullptr; - bool hasPreprocessData; - is >> hasPreprocessData; - if (hasPreprocessData) { - TilePreprocessData preprocessData = TilePreprocessData::deserialize(is); - res.preprocessData = std::make_shared(preprocessData); - } - - is >> res.nBytesImageData; - - char binaryDataSeparator; - is >> binaryDataSeparator; // not used - - char* buffer = new char[res.nBytesImageData](); - return std::move(res); - } - - -} // namespace openspace diff --git a/modules/globebrowsing/tile/tileioresult.h b/modules/globebrowsing/tile/tileioresult.h deleted file mode 100644 index c22f22c444..0000000000 --- a/modules/globebrowsing/tile/tileioresult.h +++ /dev/null @@ -1,88 +0,0 @@ -/***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ - -#ifndef __TILE_IO_RESULT_H__ -#define __TILE_IO_RESULT_H__ - -#include -#include - -#include - - -#include - -#include "gdal_priv.h" - - -#include -#include - - - -namespace openspace { - using namespace ghoul::opengl; - using namespace ghoul::filesystem; - - struct TilePreprocessData { - std::vector maxValues; - std::vector minValues; - std::vector hasMissingData; - - void serialize(std::ostream& s); - static TilePreprocessData deserialize(std::istream& s); - }; - - struct TextureFormat { - Texture::Format ghoulFormat; - GLuint glFormat; - }; - - struct TileIOResult { - TileIOResult(); - - char* imageData; - glm::uvec3 dimensions; - std::shared_ptr preprocessData; - ChunkIndex chunkIndex; - CPLErr error; - size_t nBytesImageData; - - void serializeMetaData(std::ostream& s); - static TileIOResult deserializeMetaData(std::istream& s); - - static TileIOResult createDefaultRes(); - - }; - - - - -} // namespace openspace - - - - - -#endif // __TILE_IO_RESULT_H__ \ No newline at end of file diff --git a/modules/globebrowsing/tile/tileprovider/cachingtileprovider.cpp b/modules/globebrowsing/tile/tileprovider/cachingtileprovider.cpp index 377d34c924..1b0efa1eff 100644 --- a/modules/globebrowsing/tile/tileprovider/cachingtileprovider.cpp +++ b/modules/globebrowsing/tile/tileprovider/cachingtileprovider.cpp @@ -1,225 +1,229 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#include #include -#include -#include -#include +#include +#include + #include - -#include +#include namespace { - const std::string _loggerCat = "CachingTileProvider"; + const char* _loggerCat = "CachingTileProvider"; - const std::string KeyDoPreProcessing = "DoPreProcessing"; - const std::string KeyMinimumPixelSize = "MinimumPixelSize"; - const std::string KeyFilePath = "FilePath"; - const std::string KeyCacheSize = "CacheSize"; - const std::string KeyFlushInterval = "FlushInterval"; + const char* KeyDoPreProcessing = "DoPreProcessing"; + const char* KeyMinimumPixelSize = "MinimumPixelSize"; + const char* KeyFilePath = "FilePath"; + const char* KeyCacheSize = "CacheSize"; + const char* KeyFlushInterval = "FlushInterval"; } namespace openspace { +namespace globebrowsing { - CachingTileProvider::CachingTileProvider(const ghoul::Dictionary& dictionary) +CachingTileProvider::CachingTileProvider(const ghoul::Dictionary& dictionary) : _framesSinceLastRequestFlush(0) - { - std::string name = "Name unspecified"; - dictionary.getValue("Name", name); - std::string _loggerCat = "CachingTileProvider : " + name; +{ + std::string name = "Name unspecified"; + dictionary.getValue("Name", name); + std::string _loggerCat = "CachingTileProvider : " + name; - // 1. Get required Keys - std::string filePath; - if (!dictionary.getValue(KeyFilePath, filePath)) { - throw std::runtime_error("Must define key '" + KeyFilePath + "'"); - } - - // 2. Initialize default values for any optional Keys - TileDataset::Configuration config; - config.doPreProcessing = false; - config.minimumTilePixelSize = 512; - - // getValue does not work for integers - double minimumPixelSize; - double cacheSize = 512; - double framesUntilRequestFlush = 60; - - // 3. Check for used spcified optional keys - if (dictionary.getValue(KeyDoPreProcessing, config.doPreProcessing)) { - LDEBUG("Default doPreProcessing overridden: " << config.doPreProcessing); - } - if (dictionary.getValue(KeyMinimumPixelSize, minimumPixelSize)) { - LDEBUG("Default minimumPixelSize overridden: " << minimumPixelSize); - config.minimumTilePixelSize = static_cast(minimumPixelSize); - } - if (dictionary.getValue(KeyCacheSize, cacheSize)) { - LDEBUG("Default cacheSize overridden: " << cacheSize); - } - if (dictionary.getValue(KeyFlushInterval, framesUntilRequestFlush)) { - LDEBUG("Default framesUntilRequestFlush overridden: " << - framesUntilRequestFlush); - } - - // Initialize instance variables - auto tileDataset = std::make_shared(filePath, config); - - // only one thread per provider supported atm - // (GDAL does not handle multiple threads for a single dataset very well - // currently) - auto threadPool = std::make_shared(1); - - _asyncTextureDataProvider = std::make_shared( - tileDataset, threadPool); - _tileCache = std::make_shared(cacheSize); - _framesUntilRequestFlush = framesUntilRequestFlush; + // 1. Get required Keys + std::string filePath; + if (!dictionary.getValue(KeyFilePath, filePath)) { + throw std::runtime_error(std::string("Must define key '") + KeyFilePath + "'"); } - CachingTileProvider::CachingTileProvider( - std::shared_ptr tileReader, - std::shared_ptr tileCache, - int framesUntilFlushRequestQueue) - : _asyncTextureDataProvider(tileReader) - , _tileCache(tileCache) - , _framesUntilRequestFlush(framesUntilFlushRequestQueue) - , _framesSinceLastRequestFlush(0) - { + // 2. Initialize default values for any optional Keys + TileDataset::Configuration config; + config.doPreProcessing = false; + config.minimumTilePixelSize = 512; + // getValue does not work for integers + double minimumPixelSize; + double cacheSize = 512; + double framesUntilRequestFlush = 60; + + // 3. Check for used spcified optional keys + if (dictionary.getValue(KeyDoPreProcessing, config.doPreProcessing)) { + LDEBUG("Default doPreProcessing overridden: " << config.doPreProcessing); + } + if (dictionary.getValue(KeyMinimumPixelSize, minimumPixelSize)) { + LDEBUG("Default minimumPixelSize overridden: " << minimumPixelSize); + config.minimumTilePixelSize = static_cast(minimumPixelSize); + } + if (dictionary.getValue(KeyCacheSize, cacheSize)) { + LDEBUG("Default cacheSize overridden: " << cacheSize); + } + if (dictionary.getValue(KeyFlushInterval, framesUntilRequestFlush)) { + LDEBUG("Default framesUntilRequestFlush overridden: " << + framesUntilRequestFlush); } - CachingTileProvider::~CachingTileProvider(){ + // Initialize instance variables + auto tileDataset = std::make_shared(filePath, config); + + // only one thread per provider supported atm + // (GDAL does not handle multiple threads for a single dataset very well + // currently) + auto threadPool = std::make_shared(1); + + _asyncTextureDataProvider = std::make_shared( + tileDataset, threadPool); + _tileCache = std::make_shared(static_cast(cacheSize)); + _framesUntilRequestFlush = framesUntilRequestFlush; +} + +CachingTileProvider::CachingTileProvider( + std::shared_ptr tileReader, + std::shared_ptr tileCache, + int framesUntilFlushRequestQueue) + : _asyncTextureDataProvider(tileReader) + , _tileCache(tileCache) + , _framesUntilRequestFlush(framesUntilFlushRequestQueue) + , _framesSinceLastRequestFlush(0) +{} + +CachingTileProvider::~CachingTileProvider(){ + clearRequestQueue(); +} + +void CachingTileProvider::update() { + initTexturesFromLoadedData(); + if (_framesSinceLastRequestFlush++ > _framesUntilRequestFlush) { clearRequestQueue(); } +} - void CachingTileProvider::update() { - initTexturesFromLoadedData(); - if (_framesSinceLastRequestFlush++ > _framesUntilRequestFlush) { - clearRequestQueue(); - } - } +void CachingTileProvider::reset() { + _tileCache->clear(); + _asyncTextureDataProvider->reset(); +} - void CachingTileProvider::reset() { - _tileCache->clear(); - _asyncTextureDataProvider->reset(); - } +int CachingTileProvider::maxLevel() { + return _asyncTextureDataProvider->getTextureDataProvider()->maxChunkLevel(); +} - int CachingTileProvider::maxLevel() { - return _asyncTextureDataProvider->getTextureDataProvider()->maxChunkLevel(); - } +Tile CachingTileProvider::getTile(const TileIndex& tileIndex) { + Tile tile = Tile::TileUnavailable; - Tile CachingTileProvider::getTile(const ChunkIndex& chunkIndex) { - Tile tile = Tile::TileUnavailable; - - if (chunkIndex.level > maxLevel()) { - tile.status = Tile::Status::OutOfRange; - return tile; - } - - ChunkHashKey key = chunkIndex.hashKey(); - - if (_tileCache->exist(key)) { - return _tileCache->get(key); - } - else { - _asyncTextureDataProvider->enqueueTileIO(chunkIndex); - } - + if (tileIndex.level > maxLevel()) { + tile.status = Tile::Status::OutOfRange; return tile; } - Tile CachingTileProvider::getDefaultTile() { - if (_defaultTile.texture == nullptr) { - _defaultTile = createTile(_asyncTextureDataProvider->getTextureDataProvider()->defaultTileData()); - } - return _defaultTile; + TileHashKey key = tileIndex.hashKey(); + + if (_tileCache->exist(key)) { + return _tileCache->get(key); } - - void CachingTileProvider::initTexturesFromLoadedData() { - auto readyTileIOResults = _asyncTextureDataProvider->getTileIOResults(); - for(auto tileIOResult : readyTileIOResults){ - ChunkHashKey key = tileIOResult->chunkIndex.hashKey(); - Tile tile = createTile(tileIOResult); - _tileCache->put(key, tile); - } + else { + _asyncTextureDataProvider->enqueueTileIO(tileIndex); } - - void CachingTileProvider::clearRequestQueue() { - _asyncTextureDataProvider->clearRequestQueue(); - _framesSinceLastRequestFlush = 0; - } - - Tile::Status CachingTileProvider::getTileStatus(const ChunkIndex& chunkIndex) { - auto tileDataset = _asyncTextureDataProvider->getTextureDataProvider(); - if (chunkIndex.level > tileDataset->maxChunkLevel()) { - return Tile::Status::OutOfRange; - } - - ChunkHashKey key = chunkIndex.hashKey(); - - if (_tileCache->exist(key)) { - return _tileCache->get(key).status; - } - - return Tile::Status::Unavailable; - } - - TileDepthTransform CachingTileProvider::depthTransform() { - return _asyncTextureDataProvider->getTextureDataProvider()->getDepthTransform(); - } - - Tile CachingTileProvider::createTile(std::shared_ptr tileIOResult) { - if (tileIOResult->error != CE_None) { - return{ nullptr, nullptr, Tile::Status::IOError }; - } - - ChunkHashKey key = tileIOResult->chunkIndex.hashKey(); - TileDataLayout dataLayout = - _asyncTextureDataProvider->getTextureDataProvider()->getDataLayout(); - // The texture should take ownership of the data - std::shared_ptr texture = std::make_shared( - tileIOResult->imageData, - tileIOResult->dimensions, - dataLayout.textureFormat.ghoulFormat, - dataLayout.textureFormat.glFormat, - dataLayout.glType, - Texture::FilterMode::Linear, - Texture::WrappingMode::ClampToEdge); - - texture->uploadTexture(); + return tile; +} - // AnisotropicMipMap must be set after texture is uploaded. Why?! - texture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); +float CachingTileProvider::noDataValueAsFloat() { + return _asyncTextureDataProvider->noDataValueAsFloat(); +} - Tile tile = { - texture, - tileIOResult->preprocessData, - Tile::Status::OK - }; +Tile CachingTileProvider::getDefaultTile() { + if (_defaultTile.texture == nullptr) { + _defaultTile = createTile( + _asyncTextureDataProvider->getTextureDataProvider()->defaultTileData() + ); + } + return _defaultTile; +} - return tile; +void CachingTileProvider::initTexturesFromLoadedData() { + auto rawTiles = _asyncTextureDataProvider->getRawTiles(); + for (auto rawTile : rawTiles){ + TileHashKey key = rawTile->tileIndex.hashKey(); + Tile tile = createTile(rawTile); + _tileCache->put(key, tile); + } +} + +void CachingTileProvider::clearRequestQueue() { + _asyncTextureDataProvider->clearRequestQueue(); + _framesSinceLastRequestFlush = 0; +} + +Tile::Status CachingTileProvider::getTileStatus(const TileIndex& tileIndex) { + auto tileDataset = _asyncTextureDataProvider->getTextureDataProvider(); + if (tileIndex.level > tileDataset->maxChunkLevel()) { + return Tile::Status::OutOfRange; } -} // namespace openspace + TileHashKey key = tileIndex.hashKey(); + + if (_tileCache->exist(key)) { + return _tileCache->get(key).status; + } + + return Tile::Status::Unavailable; +} + +TileDepthTransform CachingTileProvider::depthTransform() { + return _asyncTextureDataProvider->getTextureDataProvider()->getDepthTransform(); +} + +Tile CachingTileProvider::createTile(std::shared_ptr rawTile) { + if (rawTile->error != CE_None) { + return{ nullptr, nullptr, Tile::Status::IOError }; + } + + TileHashKey key = rawTile->tileIndex.hashKey(); + TileDataLayout dataLayout = + _asyncTextureDataProvider->getTextureDataProvider()->getDataLayout(); + + // The texture should take ownership of the data + std::shared_ptr texture = std::make_shared( + rawTile->imageData, + rawTile->dimensions, + dataLayout.textureFormat.ghoulFormat, + dataLayout.textureFormat.glFormat, + dataLayout.glType, + Texture::FilterMode::Linear, + Texture::WrappingMode::ClampToEdge); + + texture->uploadTexture(); + + // AnisotropicMipMap must be set after texture is uploaded. Why?! + texture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); + + Tile tile = { + texture, + rawTile->tileMetaData, + Tile::Status::OK + }; + + return tile; +} + +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/tile/tileprovider/cachingtileprovider.h b/modules/globebrowsing/tile/tileprovider/cachingtileprovider.h index 47fd735756..5531c6e9d2 100644 --- a/modules/globebrowsing/tile/tileprovider/cachingtileprovider.h +++ b/modules/globebrowsing/tile/tileprovider/cachingtileprovider.h @@ -1,114 +1,98 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __CACHING_TILE_PROVIDER_H__ -#define __CACHING_TILE_PROVIDER_H__ - -#include -#include // absPath -#include -#include +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___CACHING_TILE_PROVIDER___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___CACHING_TILE_PROVIDER___H__ #include -#include -#include - -////////////////////////////////////////////////////////////////////////////////////////// -// TILE PROVIDER // -////////////////////////////////////////////////////////////////////////////////////////// namespace openspace { +namespace globebrowsing { + +class AsyncTileDataProvider; + +/** +* Provides tiles loaded by AsyncTileDataProvider and +* caches them in memory using LRU caching +*/ +class CachingTileProvider : public TileProvider { +public: + CachingTileProvider(const ghoul::Dictionary& dictionary); + + CachingTileProvider( + std::shared_ptr tileReader, + std::shared_ptr tileCache, + int framesUntilFlushRequestQueue); + + virtual ~CachingTileProvider(); + + /** + * \returns a Tile with status OK iff it exists in in-memory + * cache. If not, it may enqueue some IO operations on a + * separate thread. + */ + virtual Tile getTile(const TileIndex& tileIndex); + + virtual Tile getDefaultTile(); + virtual Tile::Status getTileStatus(const TileIndex& tileIndex); + virtual TileDepthTransform depthTransform(); + virtual void update(); + virtual void reset(); + virtual int maxLevel(); + virtual float noDataValueAsFloat(); + +private: + /** + * Collects all asynchronously downloaded RawTile + * and uses createTile to create Tiles, + * which are put in the LRU cache - potentially pushing out outdated + * Tiles. + */ + void initTexturesFromLoadedData(); /** - * Provides tiles loaded by AsyncTileDataProvider and - * caches them in memory using LRU caching + * \returns A tile with Tile::Status::OK if no errors + * occured, a tile with Tile::Status::IOError otherwise */ - class CachingTileProvider : public TileProvider { - public: + Tile createTile(std::shared_ptr res); - CachingTileProvider(const ghoul::Dictionary& dictionary); + /** + * Deletes all enqueued, but not yet started async downloads of textures. + * Note that this does not cancel any currently ongoing async downloads. + */ + void clearRequestQueue(); - CachingTileProvider( - std::shared_ptr tileReader, - std::shared_ptr tileCache, - int framesUntilFlushRequestQueue); + std::shared_ptr _asyncTextureDataProvider; + std::shared_ptr _tileCache; - virtual ~CachingTileProvider(); - - /** - * \returns a Tile with status OK iff it exists in in-memory - * cache. If not, it may enqueue some IO operations on a - * separate thread. - */ - virtual Tile getTile(const ChunkIndex& chunkIndex); + int _framesSinceLastRequestFlush; + int _framesUntilRequestFlush; - virtual Tile getDefaultTile(); - virtual Tile::Status getTileStatus(const ChunkIndex& chunkIndex); - virtual TileDepthTransform depthTransform(); - virtual void update(); - virtual void reset(); - virtual int maxLevel(); + Tile _defaultTile; +}; - private: +} // namespace globebrowsing +} // namespace openspace - ////////////////////////////////////////////////////////////////////////////////// - // Helper functions // - ////////////////////////////////////////////////////////////////////////////////// - - /** - * Collects all asynchronously downloaded TileIOResult - * and uses createTile to create Tiles, - * which are put in the LRU cache - potentially pushing out outdated - * Tiles. - */ - void initTexturesFromLoadedData(); - - /** - * \returns A tile with Tile::Status::OK if no errors - * occured, a tile with Tile::Status::IOError otherwise - */ - Tile createTile(std::shared_ptr res); - - /** - * Deletes all enqueued, but not yet started async downloads of textures. - * Note that this does not cancel any currently ongoing async downloads. - */ - void clearRequestQueue(); - - ////////////////////////////////////////////////////////////////////////////////// - // Member variables // - ////////////////////////////////////////////////////////////////////////////////// - - std::shared_ptr _asyncTextureDataProvider; - std::shared_ptr _tileCache; - - int _framesSinceLastRequestFlush; - int _framesUntilRequestFlush; - - Tile _defaultTile; - }; - -} // namespace openspace - -#endif // __CACHING_TILE_PROVIDER_H__ \ No newline at end of file +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___CACHING_TILE_PROVIDER___H__ diff --git a/modules/globebrowsing/tile/tileprovider/singleimageprovider.cpp b/modules/globebrowsing/tile/tileprovider/singleimageprovider.cpp index e88464c5c0..240779820a 100644 --- a/modules/globebrowsing/tile/tileprovider/singleimageprovider.cpp +++ b/modules/globebrowsing/tile/tileprovider/singleimageprovider.cpp @@ -1,95 +1,90 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#include #include -#include #include -#include -#include - -#include +#include namespace { - const std::string _loggerCat = "SingleImageProvider"; - - const std::string KeyFilePath = "FilePath"; + const char* KeyFilePath = "FilePath"; } namespace openspace { +namespace globebrowsing { - SingleImageProvider::SingleImageProvider(const ghoul::Dictionary& dictionary) { - // Required input - if (!dictionary.getValue(KeyFilePath, _imagePath)) { - throw std::runtime_error("Must define key '" + KeyFilePath + "'"); - } - - reset(); +SingleImageProvider::SingleImageProvider(const ghoul::Dictionary& dictionary) { + // Required input + if (!dictionary.getValue(KeyFilePath, _imagePath)) { + throw std::runtime_error(std::string("Must define key '") + KeyFilePath + "'"); } - SingleImageProvider::SingleImageProvider(const std::string& imagePath) - : _imagePath(imagePath) - { - reset(); - } + reset(); +} - Tile SingleImageProvider::getTile(const ChunkIndex& chunkIndex) { - return _tile; - } +SingleImageProvider::SingleImageProvider(const std::string& imagePath) + : _imagePath(imagePath) +{ + reset(); +} - Tile SingleImageProvider::getDefaultTile() { - return _tile; - } +Tile SingleImageProvider::getTile(const TileIndex& tileIndex) { + return _tile; +} - Tile::Status SingleImageProvider::getTileStatus(const ChunkIndex& index) { - return _tile.status; - } +Tile SingleImageProvider::getDefaultTile() { + return _tile; +} - TileDepthTransform SingleImageProvider::depthTransform() { - TileDepthTransform transform; - transform.depthOffset = 0.0f; - transform.depthScale = 1.0f; - return transform; - } +Tile::Status SingleImageProvider::getTileStatus(const TileIndex& index) { + return _tile.status; +} - void SingleImageProvider::update() { - // nothing to be done - } +TileDepthTransform SingleImageProvider::depthTransform() { + TileDepthTransform transform; + transform.depthOffset = 0.0f; + transform.depthScale = 1.0f; + return transform; +} - void SingleImageProvider::reset() { - _tile = Tile(); - _tile.texture = std::shared_ptr(ghoul::io::TextureReader::ref().loadTexture(_imagePath).release()); - _tile.status = _tile.texture != nullptr ? Tile::Status::OK : Tile::Status::IOError; - _tile.preprocessData = nullptr; +void SingleImageProvider::update() { + // nothing to be done +} - _tile.texture->uploadTexture(); - _tile.texture->setFilter(ghoul::opengl::Texture::FilterMode::Linear); - } +void SingleImageProvider::reset() { + _tile = Tile(); + _tile.texture = std::shared_ptr(ghoul::io::TextureReader::ref().loadTexture(_imagePath).release()); + _tile.status = _tile.texture != nullptr ? Tile::Status::OK : Tile::Status::IOError; + _tile.metaData = nullptr; - int SingleImageProvider::maxLevel() { - return 1337; // unlimited - } + _tile.texture->uploadTexture(); + _tile.texture->setFilter(ghoul::opengl::Texture::FilterMode::Linear); +} -} // namespace openspace +int SingleImageProvider::maxLevel() { + return 1337; // unlimited +} + +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/tile/tileprovider/singleimageprovider.h b/modules/globebrowsing/tile/tileprovider/singleimageprovider.h index b83580712d..793337a0c4 100644 --- a/modules/globebrowsing/tile/tileprovider/singleimageprovider.h +++ b/modules/globebrowsing/tile/tileprovider/singleimageprovider.h @@ -1,69 +1,57 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __SINGLE_IMAGE_PROVIDER_H__ -#define __SINGLE_IMAGE_PROVIDER_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___SINGLE_IMAGE_PROVIDER___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___SINGLE_IMAGE_PROVIDER___H__ -#include #include -#include - -#include - -#include - -#include -#include // absPath -#include -#include -#include - -#include namespace openspace { - - using namespace ghoul::opengl; +namespace globebrowsing { - class SingleImageProvider : public TileProvider { - public: - - SingleImageProvider(const ghoul::Dictionary& dictionary); - SingleImageProvider(const std::string& imagePath); - virtual ~SingleImageProvider() { } +using namespace ghoul::opengl; - virtual Tile getTile(const ChunkIndex& chunkIndex); - virtual Tile getDefaultTile(); - virtual Tile::Status getTileStatus(const ChunkIndex& index); - virtual TileDepthTransform depthTransform(); - virtual void update(); - virtual void reset(); - virtual int maxLevel(); - private: - Tile _tile; - std::string _imagePath; - }; +class SingleImageProvider : public TileProvider { +public: + SingleImageProvider(const ghoul::Dictionary& dictionary); + SingleImageProvider(const std::string& imagePath); + virtual ~SingleImageProvider() = default; -} // namespace openspace + virtual Tile getTile(const TileIndex& tileIndex); + virtual Tile getDefaultTile(); + virtual Tile::Status getTileStatus(const TileIndex& index); + virtual TileDepthTransform depthTransform(); + virtual void update(); + virtual void reset(); + virtual int maxLevel(); -#endif // __SINGLE_IMAGE_PROVIDER_H__ \ No newline at end of file +private: + Tile _tile; + std::string _imagePath; +}; + +} // namespace globebrowsing +} // namespace openspace + +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___SINGLE_IMAGE_PROVIDER___H__ diff --git a/modules/globebrowsing/tile/tileprovider/temporaltileprovider.cpp b/modules/globebrowsing/tile/tileprovider/temporaltileprovider.cpp index 2cdbefd741..3e187dc95f 100644 --- a/modules/globebrowsing/tile/tileprovider/temporaltileprovider.cpp +++ b/modules/globebrowsing/tile/tileprovider/temporaltileprovider.cpp @@ -1,332 +1,351 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ - -#include + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ #include + #include - -#include - -#include - #include -#include - - -#include -#include -#include - #include "cpl_minixml.h" - - +#include namespace { const std::string _loggerCat = "TemporalTileProvider"; - const std::string KeyDoPreProcessing = "DoPreProcessing"; - const std::string KeyMinimumPixelSize = "MinimumPixelSize"; - const std::string KeyFilePath = "FilePath"; - const std::string KeyCacheSize = "CacheSize"; - const std::string KeyFlushInterval = "FlushInterval"; + const char* KeyDoPreProcessing = "DoPreProcessing"; + const char* KeyMinimumPixelSize = "MinimumPixelSize"; + const char* KeyFilePath = "FilePath"; + const char* KeyCacheSize = "CacheSize"; + const char* KeyFlushInterval = "FlushInterval"; } - namespace openspace { +namespace globebrowsing { - const std::string TemporalTileProvider::URL_TIME_PLACEHOLDER("${OpenSpaceTimeId}"); +const char* TemporalTileProvider::URL_TIME_PLACEHOLDER("${OpenSpaceTimeId}"); - const std::string TemporalTileProvider::TemporalXMLTags::TIME_START = "OpenSpaceTimeStart"; - const std::string TemporalTileProvider::TemporalXMLTags::TIME_END = "OpenSpaceTimeEnd"; - const std::string TemporalTileProvider::TemporalXMLTags::TIME_RESOLUTION = "OpenSpaceTimeResolution"; - const std::string TemporalTileProvider::TemporalXMLTags::TIME_FORMAT = "OpenSpaceTimeIdFormat"; +const char* TemporalTileProvider::TemporalXMLTags::TIME_START = "OpenSpaceTimeStart"; +const char* TemporalTileProvider::TemporalXMLTags::TIME_END = "OpenSpaceTimeEnd"; +const char* TemporalTileProvider::TemporalXMLTags::TIME_RESOLUTION = + "OpenSpaceTimeResolution"; +const char* TemporalTileProvider::TemporalXMLTags::TIME_FORMAT = "OpenSpaceTimeIdFormat"; +TemporalTileProvider::TemporalTileProvider(const ghoul::Dictionary& dictionary) + : _initDict(dictionary) +{ - TemporalTileProvider::TemporalTileProvider(const ghoul::Dictionary& dictionary) - : _initDict(dictionary) - { - - if (!dictionary.getValue(KeyFilePath, _datasetFile)) { - throw std::runtime_error("Must define key '" + KeyFilePath + "'"); - } - - - std::ifstream in(_datasetFile.c_str()); - ghoul_assert(errno == 0, strerror(errno) << std::endl << _datasetFile); - - // read file - std::string xml((std::istreambuf_iterator(in)), (std::istreambuf_iterator())); - _gdalXmlTemplate = consumeTemporalMetaData(xml); - _defaultTile = getTileProvider()->getDefaultTile(); + if (!dictionary.getValue(KeyFilePath, _datasetFile)) { + throw std::runtime_error(std::string("Must define key '") + KeyFilePath + "'"); } + std::ifstream in(_datasetFile.c_str()); + if (!in.is_open()) { + throw ghoul::FileNotFoundError(_datasetFile); + } + + // read file + std::string xml( + std::istreambuf_iterator(in), + (std::istreambuf_iterator()) + ); + _gdalXmlTemplate = consumeTemporalMetaData(xml); + _defaultTile = getTileProvider()->getDefaultTile(); +} +std::string TemporalTileProvider::consumeTemporalMetaData(const std::string& xml) { + CPLXMLNode* node = CPLParseXMLString(xml.c_str()); + std::string timeStart = getXMLValue( + node, + TemporalXMLTags::TIME_START, + "2000 Jan 1" + ); + std::string timeResolution = getXMLValue( + node, + TemporalXMLTags::TIME_RESOLUTION, + "2d" + ); + std::string timeEnd = getXMLValue( + node, + TemporalXMLTags::TIME_END, + "Now" + ); + std::string timeIdFormat = getXMLValue( + node, + TemporalXMLTags::TIME_FORMAT, + "YYYY-MM-DDThh:mm:ssZ" + ); - std::string TemporalTileProvider::consumeTemporalMetaData(const std::string& xml) { - CPLXMLNode* node = CPLParseXMLString(xml.c_str()); + Time start; start.setTime(timeStart); + Time end(Time::now()); + if (timeEnd != "Now") { + end.setTime(timeEnd); + } - std::string timeStart = getXMLValue(node, TemporalXMLTags::TIME_START, "2000 Jan 1"); - std::string timeResolution = getXMLValue(node, TemporalXMLTags::TIME_RESOLUTION, "2d"); - std::string timeEnd = getXMLValue(node, TemporalXMLTags::TIME_END, "Now"); - std::string timeIdFormat = getXMLValue(node, TemporalXMLTags::TIME_FORMAT, "YYYY-MM-DDThh:mm:ssZ"); + try { + _timeQuantizer = TimeQuantizer(start, end, timeResolution); + } + catch (const ghoul::RuntimeError& e) { + throw ghoul::RuntimeError( + "Could not create time quantizer for Temporal GDAL dataset '" + + _datasetFile + "'. " + e.message); + } + _timeFormat = TimeIdProviderFactory::getProvider(timeIdFormat); + if (!_timeFormat) { + throw ghoul::RuntimeError( + "Invalid Time Format " + timeIdFormat + " in " + _datasetFile + ); + } - Time start; start.setTime(timeStart); - Time end(Time::now()); - if (timeEnd != "Now") { - end.setTime(timeEnd); - } + std::string gdalDescription; + CPLXMLNode* gdalNode = CPLSearchXMLNode(node, "GDAL_WMS"); + if (gdalNode) { + gdalDescription = CPLSerializeXMLTree(gdalNode); + } + if (!gdalNode) { + CPLXMLNode* gdalNode = CPLSearchXMLNode(node, "FilePath"); + gdalDescription = std::string(gdalNode->psChild->pszValue); + } + + return gdalDescription; +} +std::string TemporalTileProvider::getXMLValue(CPLXMLNode* root, const std::string& key, + const std::string& defaultVal) +{ + CPLXMLNode * n = CPLSearchXMLNode(root, key.c_str()); + if (!n) { + throw ghoul::RuntimeError( + "Unable to parse file " + _datasetFile + ". " + key + " missing." + ); + } + + bool hasValue = + (n != nullptr && n->psChild != nullptr && n->psChild->pszValue != nullptr); + return hasValue ? std::string(n->psChild->pszValue) : defaultVal; +} + +TileDepthTransform TemporalTileProvider::depthTransform() { + ensureUpdated(); + return _currentTileProvider->depthTransform(); +} + +Tile::Status TemporalTileProvider::getTileStatus(const TileIndex& tileIndex) { + ensureUpdated(); + return _currentTileProvider->getTileStatus(tileIndex); +} + +Tile TemporalTileProvider::getTile(const TileIndex& tileIndex) { + ensureUpdated(); + return _currentTileProvider->getTile(tileIndex); +} + +Tile TemporalTileProvider::getDefaultTile() { + return _defaultTile; +} + +int TemporalTileProvider::maxLevel() { + ensureUpdated(); + return _currentTileProvider->maxLevel(); +} + +void TemporalTileProvider::ensureUpdated() { + if (_currentTileProvider == nullptr) { + LDEBUG("Warning: update was done lazily"); + update(); + } +} + +void TemporalTileProvider::update() { + auto newCurrent = getTileProvider(); + if (newCurrent) { + _currentTileProvider = newCurrent; + } + _currentTileProvider->update(); +} + +void TemporalTileProvider::reset() { + for (auto& it : _tileProviderMap) { + it.second->reset(); + } + //auto end = _tileProviderMap.end(); + //for (auto it = _tileProviderMap.begin(); it != end; it++) { + // it->second->reset(); + //} +} + +std::shared_ptr TemporalTileProvider::getTileProvider(Time t) { + Time tCopy(t); + if (_timeQuantizer.quantize(tCopy, true)) { + TimeKey timekey = _timeFormat->stringify(tCopy); try { - _timeQuantizer = TimeQuantizer(start, end, timeResolution); + return getTileProvider(timekey); } catch (const ghoul::RuntimeError& e) { - throw ghoul::RuntimeError( - "Could not create time quantizer for Temporal GDAL dataset '" + - _datasetFile + "'. " + e.message); - } - _timeFormat = TimeIdProviderFactory::getProvider(timeIdFormat); - if (!_timeFormat) { - throw ghoul::RuntimeError("Invalid Time Format " + timeIdFormat + " in " + _datasetFile); - } - - CPLXMLNode* gdalNode = CPLSearchXMLNode(node, "GDAL_WMS"); - return CPLSerializeXMLTree(gdalNode); - } - - - std::string TemporalTileProvider::getXMLValue(CPLXMLNode* root, const std::string& key, const std::string& defaultVal) { - CPLXMLNode * n = CPLSearchXMLNode(root, key.c_str()); - if (!n) { - throw ghoul::RuntimeError("Unable to parse file " + _datasetFile + ". " + key + " missing."); - } - - bool hasValue = (n != nullptr && n->psChild != nullptr && n->psChild->pszValue != nullptr); - return hasValue ? std::string(n->psChild->pszValue) : defaultVal; - } - - TileDepthTransform TemporalTileProvider::depthTransform() { - ensureUpdated(); - return _currentTileProvider->depthTransform(); - } - - Tile::Status TemporalTileProvider::getTileStatus(const ChunkIndex& chunkIndex) { - ensureUpdated(); - return _currentTileProvider->getTileStatus(chunkIndex); - } - - Tile TemporalTileProvider::getTile(const ChunkIndex& chunkIndex) { - ensureUpdated(); - return _currentTileProvider->getTile(chunkIndex); - } - - Tile TemporalTileProvider::getDefaultTile() { - return _defaultTile; - } - - - int TemporalTileProvider::maxLevel() { - ensureUpdated(); - return _currentTileProvider->maxLevel(); - } - - void TemporalTileProvider::ensureUpdated() { - if (_currentTileProvider == nullptr) { - LDEBUG("Warning: update was done lazily"); - update(); + LERROR(e.message); + return nullptr; } } + return nullptr; +} - void TemporalTileProvider::update() { - _currentTileProvider = getTileProvider(); - _currentTileProvider->update(); +std::shared_ptr TemporalTileProvider::getTileProvider(TimeKey timekey) { + auto it = _tileProviderMap.find(timekey); + if (it != _tileProviderMap.end()) { + return it->second; } + else { + auto tileProvider = initTileProvider(timekey); - void TemporalTileProvider::reset() { - auto end = _tileProviderMap.end(); - for (auto it = _tileProviderMap.begin(); it != end; it++) { - it->second->reset(); - } + _tileProviderMap[timekey] = tileProvider; + return tileProvider; } +} - std::shared_ptr TemporalTileProvider::getTileProvider(Time t) { - Time tCopy(t); - if (_timeQuantizer.quantize(tCopy, true)) { - TimeKey timekey = _timeFormat->stringify(tCopy); - try { - return getTileProvider(timekey); - } - catch (const ghoul::RuntimeError& e) { - LERROR(e.message); - return nullptr; - } - } - return nullptr; - } - - - std::shared_ptr TemporalTileProvider::getTileProvider(TimeKey timekey) { - auto it = _tileProviderMap.find(timekey); - if (it != _tileProviderMap.end()) { - return it->second; - } - else { - auto tileProvider = initTileProvider(timekey); - - _tileProviderMap[timekey] = tileProvider; - return tileProvider; - } - } - - - std::shared_ptr TemporalTileProvider::initTileProvider(TimeKey timekey) { - std::string gdalDatasetXml = getGdalDatasetXML(timekey); - _initDict.setValue(KeyFilePath, gdalDatasetXml); - return std::make_shared(_initDict); - } +std::shared_ptr TemporalTileProvider::initTileProvider(TimeKey timekey) { + std::string gdalDatasetXml = getGdalDatasetXML(timekey); + _initDict.setValue(KeyFilePath, gdalDatasetXml); + auto tileProvider = std::make_shared(_initDict); + return tileProvider; +} - std::string TemporalTileProvider::getGdalDatasetXML(Time t) { - TimeKey timekey = _timeFormat->stringify(t); - return getGdalDatasetXML(timekey); - } +std::string TemporalTileProvider::getGdalDatasetXML(Time t) { + TimeKey timekey = _timeFormat->stringify(t); + return getGdalDatasetXML(timekey); +} - std::string TemporalTileProvider::getGdalDatasetXML(TimeKey timeKey) { - std::string xmlTemplate(_gdalXmlTemplate); - size_t pos = xmlTemplate.find(URL_TIME_PLACEHOLDER); - size_t numChars = URL_TIME_PLACEHOLDER.length(); - ghoul_assert(pos != std::string::npos, "Invalid dataset file"); - std::string timeSpecifiedXml = xmlTemplate.replace(pos, numChars, timeKey); - return timeSpecifiedXml; - } +std::string TemporalTileProvider::getGdalDatasetXML(TimeKey timeKey) { + std::string xmlTemplate(_gdalXmlTemplate); + size_t pos = xmlTemplate.find(URL_TIME_PLACEHOLDER); + //size_t numChars = std::string(URL_TIME_PLACEHOLDER).length(); + size_t numChars = strlen(URL_TIME_PLACEHOLDER); + ghoul_assert(pos != std::string::npos, "Invalid dataset file"); + std::string timeSpecifiedXml = xmlTemplate.replace(pos, numChars, timeKey); + return timeSpecifiedXml; +} +std::string YYYY_MM_DD::stringify(const Time& t) const { + return t.ISO8601().substr(0, 10); +} - - - - ////////////////////////////////////////////////////////////////////////////////////// - // Time Id Providers // - ////////////////////////////////////////////////////////////////////////////////////// - std::string YYYY_MM_DD::stringify(const Time& t) const { - return t.ISO8601().substr(0, 10); - } - - std::string YYYY_MM_DDThh_mm_ssZ::stringify(const Time& t) const { - return t.ISO8601().substr(0, 19) + "Z"; - } - +std::string YYYY_MM_DDThhColonmmColonssZ::stringify(const Time& t) const { + return t.ISO8601().substr(0, 19) + "Z"; +} +std::string YYYY_MM_DDThh_mm_ssZ::stringify(const Time& t) const { + std::string timeString = t.ISO8601().substr(0, 19) + "Z"; + replace( timeString.begin(), timeString.end(), ':', '_' ); + return timeString; +} - ////////////////////////////////////////////////////////////////////////////////////// - // Time Id Providers Facotry // - ////////////////////////////////////////////////////////////////////////////////////// +bool TimeIdProviderFactory::initialized = false; - bool TimeIdProviderFactory::initialized = false; +std::unordered_map> + TimeIdProviderFactory::_timeIdProviderMap = + std::unordered_map>(); - std::unordered_map> TimeIdProviderFactory::_timeIdProviderMap = std::unordered_map>(); +void TimeIdProviderFactory::init() { + _timeIdProviderMap.insert(std::pair>( + { "YYYY-MM-DD" , std::make_unique() } + )); + _timeIdProviderMap.insert(std::pair>( + { "YYYY-MM-DDThh:mm:ssZ", std::make_unique() } + )); + initialized = true; + _timeIdProviderMap.insert(std::pair>( + { "YYYY-MM-DDThh_mm_ssZ", std::make_unique() } + )); + initialized = true; +} - void TimeIdProviderFactory::init() { - _timeIdProviderMap.insert( - std::pair >( "YYYY-MM-DD", std::make_unique() )); - _timeIdProviderMap.insert(std::pair > ( "YYYY-MM-DDThh:mm:ssZ", std::make_unique() )); - initialized = true; +TimeFormat* TimeIdProviderFactory::getProvider(const std::string& format) { + if (!initialized) { + init(); } + ghoul_assert( + _timeIdProviderMap.find(format) != _timeIdProviderMap.end(), + "Unsupported Time format: " << format + ); + return _timeIdProviderMap[format].get(); +} - TimeFormat* TimeIdProviderFactory::getProvider(const std::string& format) { - if (!initialized) { - init(); - } - ghoul_assert(_timeIdProviderMap.find(format) != _timeIdProviderMap.end(), - "Unsupported Time format: " << format); - return _timeIdProviderMap[format].get(); - } +TimeQuantizer::TimeQuantizer(const Time& start, const Time& end, double resolution) + : _timerange(start.j2000Seconds(), end.j2000Seconds()) + , _resolution(resolution) +{} +TimeQuantizer::TimeQuantizer(const Time& start, const Time& end, + const std::string& resolution) + : TimeQuantizer(start, end, parseTimeResolutionStr(resolution)) +{} - - - ////////////////////////////////////////////////////////////////////////////////////// - // Time Quantizer // - ////////////////////////////////////////////////////////////////////////////////////// - TimeQuantizer::TimeQuantizer(const Time& start, const Time& end, double resolution) - : _timerange(start.j2000Seconds(), end.j2000Seconds()) - , _resolution(resolution) - { - - } - - TimeQuantizer::TimeQuantizer(const Time& start, const Time& end, const std::string& resolution) - : TimeQuantizer(start, end, parseTimeResolutionStr(resolution)) - { - - } - - double TimeQuantizer::parseTimeResolutionStr(const std::string& resoltutionStr) { - const char unit = resoltutionStr.back(); - std::string numberString = resoltutionStr.substr(0, resoltutionStr.length() - 1); +double TimeQuantizer::parseTimeResolutionStr(const std::string& resoltutionStr) { + const char unit = resoltutionStr.back(); + std::string numberString = resoltutionStr.substr(0, resoltutionStr.length() - 1); - char* p; - double value = strtol(numberString.c_str(), &p, 10); - if (*p) { // not a number - throw ghoul::RuntimeError("Cannot convert " + numberString + " to number"); - } - else { - // convert value to seconds, based on unit. - // The switch statment has intentional fall throughs - switch (unit) { - case 'y': value *= 365; - case 'd': value *= 24.0; - case 'h': value *= 60.0; - case 'm': value *= 60.0; - case 's': value *= 1.0; - break; - default: - throw ghoul::RuntimeError("Invalid unit format '" + std::string(1, unit) + - "'. Expected 'y', 'd', 'h', 'm' or 's'."); - } - return value; - } + char* p; + double value = strtol(numberString.c_str(), &p, 10); + if (*p) { // not a number + throw ghoul::RuntimeError("Cannot convert " + numberString + " to number"); } - - bool TimeQuantizer::quantize(Time& t, bool clamp) const { - double unquantized = t.j2000Seconds(); - if (_timerange.includes(unquantized)) { - double quantized = std::floor((unquantized - _timerange.start) / _resolution) * _resolution + _timerange.start; - t.setTime(quantized); - return true; - } - else if (clamp) { - double clampedTime = unquantized; - clampedTime = std::max(clampedTime, _timerange.start); - clampedTime = std::min(clampedTime, _timerange.end); - t.setTime(clampedTime); - return true; - } - else { - return false; + else { + // convert value to seconds, based on unit. + // The switch statment has intentional fall throughs + switch (unit) { + case 'y': value *= 365; + case 'd': value *= 24.0; + case 'h': value *= 60.0; + case 'm': value *= 60.0; + case 's': value *= 1.0; + break; + default: + throw ghoul::RuntimeError("Invalid unit format '" + std::string(1, unit) + + "'. Expected 'y', 'd', 'h', 'm' or 's'."); } + return value; } +} -} // namespace openspace +bool TimeQuantizer::quantize(Time& t, bool clamp) const { + double unquantized = t.j2000Seconds(); + if (_timerange.includes(unquantized)) { + double quantized = std::floor((unquantized - _timerange.start) / _resolution) * _resolution + _timerange.start; + t.setTime(quantized); + return true; + } + else if (clamp) { + double clampedTime = unquantized; + clampedTime = std::max(clampedTime, _timerange.start); + clampedTime = std::min(clampedTime, _timerange.end); + t.setTime(clampedTime); + return true; + } + else { + return false; + } +} + +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/tile/tileprovider/temporaltileprovider.h b/modules/globebrowsing/tile/tileprovider/temporaltileprovider.h index eed8e64ed0..fa7b08103d 100644 --- a/modules/globebrowsing/tile/tileprovider/temporaltileprovider.h +++ b/modules/globebrowsing/tile/tileprovider/temporaltileprovider.h @@ -1,327 +1,298 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __TEMPORAL_TILE_PROVIDER_H__ -#define __TEMPORAL_TILE_PROVIDER_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___TEMPORAL_TILE_PROVIDER___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___TEMPORAL_TILE_PROVIDER___H__ - -#include -#include - -#include #include #include #include +#include +#include #include -#include - - - - -////////////////////////////////////////////////////////////////////////////////////////// -// TILE PROVIDER // -////////////////////////////////////////////////////////////////////////////////////////// +struct CPLXMLNode; namespace openspace { +namespace globebrowsing { - ////////////////////////////////////////////////////////////////////////////////////// - // Time Id Providers // - ////////////////////////////////////////////////////////////////////////////////////// +/** + * Interface for stringifying OpenSpace Time instances. + * + * Once OpenSpace has a proper Time format class, this should be handled by that instead + * of here. + */ +struct TimeFormat { + /** + * Stringifies a OpenSpace time instance + * \param t The time to be stringifyed + * \returns A string description of the provided time + */ + virtual std::string stringify(const Time& t) const = 0; +}; + +/** + * Stringifies OpenSpace to the format "YYYY-MM-DD". + * Example: 2016-09-08 + */ +struct YYYY_MM_DD : public TimeFormat { + virtual std::string stringify(const Time& t) const; +}; + +/** + * Stringifies OpenSpace to the format "YYYY-MM-DDThh:mm:ssZ" + * Example: 2016-09-08T23:05:05Z + */ +struct YYYY_MM_DDThhColonmmColonssZ : public TimeFormat { + virtual std::string stringify(const Time& t) const; +}; + +/** + * Stringifies OpenSpace to the format "YYYY-MM-DDThh:mm:ssZ" + * Example: 2016-09-08T23:05:05Z + */ +struct YYYY_MM_DDThh_mm_ssZ : public TimeFormat { + virtual std::string stringify(const Time& t) const; +}; + +/** + * Static factory class for providing different TimeFormats. + * A time format stringifier is retrieved by a name of the format. + * See implementation of init() to see what time + * id formats are supported. + */ +struct TimeIdProviderFactory { + /** + * Maps a name of a format to an implementation of a TimeFormat. + * Calling this method will also initialize the TimeIdProviderFactory + * if it hasn't been. + * + * See implementation of init() for supported time formats. + * + * \param format - name of TimeFormat, eg "YYYY-MM-DDThh:mm:ssZ". + * \returns a concrete TimeFormat used to stringify instances of Time + */ + static TimeFormat* getProvider(const std::string& format); /** - * Interface for stringifying OpenSpace Time instances. - * - * Once OpenSpace has a proper Time format class, this should be - * handled by that instead of here. - */ - struct TimeFormat { + * Registers all supported TimeFormats. + */ + static void init(); + + static std::unordered_map> _timeIdProviderMap; + static bool initialized; +}; + +/** + * Used to quantize time to descrete values. + */ +struct TimeQuantizer { + TimeQuantizer() {} + TimeQuantizer(const Time& start, const Time& end, double resolution); + TimeQuantizer(const Time& start, const Time& end, const std::string& resolutionStr); + + /** + * Takes a time resulition string and parses it into a double + * value representing the time resolution as seconds. + * + * Example: parseTimeResolutionStr("1d"); + * + * \param resoltutionStr with the format {number}{unit} + * where supported units are: + * (s)econds, (m)inutes, (h)ours, (d)ays, (y)ears + * + * \returns the time resolution in seconds + */ + static double parseTimeResolutionStr(const std::string& resoltutionStr); + + /** + * Quantizes a OpenSpace Time into descrete values. + * If the provided Time t is outside the time range, it will + * be clamped to the the time range. + * + * \param t Time instance, which will be quantized + * \param clamp Whether or not time should be clamped if not t is in the time range + * \returns wether or not time was quantized + */ + bool quantize(Time& t, bool clamp) const; + +private: + TimeRange _timerange; + double _resolution; +}; + +/** + * Provide Tiles from web map services that have temporal resolution. + * + * TemporalTileProviders are instantiated using a ghoul::Dictionary, + * and must define a filepath to a Openspace Temporal dataset description file. + * This is an xml-file that defines the same meta data as the GDAL wms description + * (http://www.gdal.org/frmt_wms.html), but augmented with some + * extra tags describing the temporal properties of the dataset. See + * TemporalTileProvider::TemporalXMLTags + * + */ +class TemporalTileProvider : public TileProvider { +public: + /** + * Dictionary constructor. Must provide KeyFilePath as defined in .cpp file. + */ + TemporalTileProvider(const ghoul::Dictionary& dictionary); + + // These methods implements the TileProvider interface + + virtual Tile getTile(const TileIndex& tileIndex); + virtual Tile getDefaultTile(); + virtual Tile::Status getTileStatus(const TileIndex& tileIndex); + virtual TileDepthTransform depthTransform(); + virtual void update(); + virtual void reset(); + virtual int maxLevel(); + + + typedef std::string TimeKey; + + std::shared_ptr getTileProvider(Time t = Time::ref()); + std::shared_ptr getTileProvider(TimeKey timekey); + +private: + /** + * A placeholder string that must be provided in the WMS template url. This + * placeholder will be replaced by quantized date-time strings during run time + * in order to access the datasets for different instances of time. + */ + static const char* URL_TIME_PLACEHOLDER; + + /** + * These are tags that TemporalTileProviders must be able to read from the XML + * file provided in the ghoul::Dictionary used to create this provider. These + * tags describe the temporal properties of the dataset. + */ + struct TemporalXMLTags { /** - * Stringifies a OpenSpace time instance - * \param t The time to be stringifyed - * \returns A string description of the provided time - */ - virtual std::string stringify(const Time& t) const = 0; + * Tag should contain a ISO8601 time specifying the datasets start time + */ + static const char* TIME_START; + + /** + * Tag should contain a ISO8601 time specifying the datasets end time + * Example 1: "2016 SEP 08". + * Example 2: "now" - sets the dataset's end time to the current time. + */ + static const char* TIME_END; + + /** + * Tag should contain the time resolution of the dataset. + * The resolution is defined by a number along with a unit specifying how + * often the dataset is updated temporally. Supported units are: + * (s)econds, (m)inutes, (h)ours, (d)ays, (y)ears. + * + * Example 1: "2d" - dataset updated every other day. + * Example 2: "1h" - dataset is updated every hour. + */ + static const char* TIME_RESOLUTION; + + /** + * Tag should contain a string specifying the date-time format expected by the + * WMS. + */ + static const char* TIME_FORMAT; }; - /** - * Stringifies OpenSpace to the format "YYYY-MM-DD". - * Example: 2016-09-08 - */ - struct YYYY_MM_DD : public TimeFormat { - virtual std::string stringify(const Time& t) const; - }; - - /** - * Stringifies OpenSpace to the format "YYYY-MM-DDThh:mm:ssZ" - * Example: 2016-09-08T23:05:05Z - */ - struct YYYY_MM_DDThh_mm_ssZ : public TimeFormat { - virtual std::string stringify(const Time& t) const; - }; - - - - /** - * Static factory class for providing different TimeFormats. - * A time format stringifier is retrieved by a name of the format. - * See implementation of init() to see what time - * id formats are supported. - */ - struct TimeIdProviderFactory { - /** - * Maps a name of a format to an implementation of a TimeFormat. - * Calling this method will also initialize the TimeIdProviderFactory - * if it hasn't been. - * - * See implementation of init() for supported time formats. - * - * \param format - name of TimeFormat, eg "YYYY-MM-DDThh:mm:ssZ". - * \returns a concrete TimeFormat used to stringify instances of Time - */ - static TimeFormat* getProvider(const std::string& format); - - /** - * Registers all supported TimeFormats. - */ - static void init(); - - static std::unordered_map> _timeIdProviderMap; - static bool initialized; - }; - - - - ////////////////////////////////////////////////////////////////////////////////////// - // Time Quantizer // - ////////////////////////////////////////////////////////////////////////////////////// - - /** - * Used to quantize time to descrete values. - */ - struct TimeQuantizer { - TimeQuantizer() {} - TimeQuantizer(const Time& start, const Time& end, double resolution); - TimeQuantizer(const Time& start, const Time& end, const std::string& resolutionStr); - - /** - * Takes a time resulition string and parses it into a double - * value representing the time resolution as seconds. - * - * Example: parseTimeResolutionStr("1d"); - * - * \param resoltutionStr with the format {number}{unit} - * where supported units are: - * (s)econds, (m)inutes, (h)ours, (d)ays, (y)ears - * - * \returns the time resolution in seconds - */ - static double parseTimeResolutionStr(const std::string& resoltutionStr); - - /** - * Quantizes a OpenSpace Time into descrete values. - * If the provided Time t is outside the time range, it will - * be clamped to the the time range. - * - * \param t Time instance, which will be quantized - * \param clamp Whether or not time should be clamped if not t is in the time range - * \returns wether or not time was quantized - */ - bool quantize(Time& t, bool clamp) const; - - private: - TimeRange _timerange; - double _resolution; - }; - - - ////////////////////////////////////////////////////////////////////////////////////// - // Temporal tile Provider // - ////////////////////////////////////////////////////////////////////////////////////// - - /** - * Provide Tiles from web map services that have temporal resolution. - * - * TemporalTileProviders are instantiated using a ghoul::Dictionary, - * and must define a filepath to a Openspace Temporal dataset description file. - * This is an xml-file that defines the same meta data as the GDAL wms description - * (http://www.gdal.org/frmt_wms.html), but augmented with some - * extra tags describing the temporal properties of the dataset. See - * TemporalTileProvider::TemporalXMLTags - * - */ - class TemporalTileProvider : public TileProvider { - public: - /** - * Dictionary constructor. Must provide KeyFilePath as defined in .cpp file. - */ - TemporalTileProvider(const ghoul::Dictionary& dictionary); - - // These methods implements the TileProvider interface - - virtual Tile getTile(const ChunkIndex& chunkIndex); - virtual Tile getDefaultTile(); - virtual Tile::Status getTileStatus(const ChunkIndex& chunkIndex); - virtual TileDepthTransform depthTransform(); - virtual void update(); - virtual void reset(); - virtual int maxLevel(); - - - typedef std::string TimeKey; - - std::shared_ptr getTileProvider(Time t = Time::ref()); - std::shared_ptr getTileProvider(TimeKey timekey); - - private: - - /** - * A placeholder string that must be provided in the WMS template url. This - * placeholder will be replaced by quantized date-time strings during run time - * in order to access the datasets for different instances of time. - */ - static const std::string URL_TIME_PLACEHOLDER; - - /** - * These are tags that TemporalTileProviders must be able to read from the XML - * file provided in the ghoul::Dictionary used to create this provider. These - * tags describe the temporal properties of the dataset. - */ - static const struct TemporalXMLTags { - /** - * Tag should contain a ISO8601 time specifying the datasets start time - */ - static const std::string TIME_START; - - /** - * Tag should contain a ISO8601 time specifying the datasets end time - * Example 1: "2016 SEP 08". - * Example 2: "now" - sets the dataset's end time to the current time. - */ - static const std::string TIME_END; - - /** - * Tag should contain the time resolution of the dataset. - * The resolution is defined by a number along with a unit specifying how - * often the dataset is updated temporally. Supported units are: - * (s)econds, (m)inutes, (h)ours, (d)ays, (y)ears. - * - * Example 1: "2d" - dataset updated every other day. - * Example 2: "1h" - dataset is updated every hour. - */ - static const std::string TIME_RESOLUTION; - - /** - * Tag should contain a string specifying the date-time format expected by the - * WMS. - */ - static const std::string TIME_FORMAT; - }; - - /** - * Create a GDAL dataset description based on the time t - * \param t Time to generate a GDAL dataset description for - * \returns a GDAL dataset description - */ - std::string getGdalDatasetXML(Time t); + /** + * Create a GDAL dataset description based on the time t + * \param t Time to generate a GDAL dataset description for + * \returns a GDAL dataset description + */ + std::string getGdalDatasetXML(Time t); - /** - * Create a GDAL dataset description associated with the provided TimeKey - * \param key The TimeKey specifying time - * \returns a GDAL dataset description - */ - std::string getGdalDatasetXML(TimeKey key); + /** + * Create a GDAL dataset description associated with the provided TimeKey + * \param key The TimeKey specifying time + * \returns a GDAL dataset description + */ + std::string getGdalDatasetXML(TimeKey key); - /** - * Instantiates a new TileProvder for the temporal dataset at the time - * specified. - * - * This method replaced the URL_TIME_PLACEHOLDER in the template URL - * with the provided timekey, the opens a new GDAL dataset with that URL. - * - * \param timekey time specifying dataset's temporality - * \returns newly instantiated TileProvider - */ - std::shared_ptr initTileProvider(TimeKey timekey); + /** + * Instantiates a new TileProvder for the temporal dataset at the time + * specified. + * + * This method replaced the URL_TIME_PLACEHOLDER in the template URL + * with the provided timekey, the opens a new GDAL dataset with that URL. + * + * \param timekey time specifying dataset's temporality + * \returns newly instantiated TileProvider + */ + std::shared_ptr initTileProvider(TimeKey timekey); - /** - * Takes as input a Openspace Temporal dataset description, extracts the temporal - * metadata provided by reading the TemporalXMLTags, removes the - * read tags from the description, and returns a GDAL template GDAL dataset - * description. The template GDAL dataset description has the a - * URL_TIME_PLACEHOLDER still in it, which needs to be replaced before - * GDAL can open it as a GDALDataset. - * - * \param xml Openspace Temporal dataset description - * \returns a GDAL template data description. - */ - std::string consumeTemporalMetaData(const std::string &xml); + /** + * Takes as input a Openspace Temporal dataset description, extracts the temporal + * metadata provided by reading the TemporalXMLTags, removes the + * read tags from the description, and returns a GDAL template GDAL dataset + * description. The template GDAL dataset description has the a + * URL_TIME_PLACEHOLDER still in it, which needs to be replaced before + * GDAL can open it as a GDALDataset. + * + * \param xml Openspace Temporal dataset description + * \returns a GDAL template data description. + */ + std::string consumeTemporalMetaData(const std::string &xml); - /** - * Helper method to read a XML value from a XML tree. - * \param node XML tree to search in - * \param key XML tag to find the value for - * \param defaultVal value to return if key was not found - * \returns the value of the Key, or defaultVal if key was undefined. - */ - std::string getXMLValue(CPLXMLNode* node, const std::string& key, const std::string& defaultVal); + /** + * Helper method to read a XML value from a XML tree. + * \param node XML tree to search in + * \param key XML tag to find the value for + * \param defaultVal value to return if key was not found + * \returns the value of the Key, or defaultVal if key was undefined. + */ + std::string getXMLValue(CPLXMLNode* node, const std::string& key, const std::string& defaultVal); - /** - * Ensures that the TemporalTileProvider is up to date. - */ - void ensureUpdated(); + /** + * Ensures that the TemporalTileProvider is up to date. + */ + void ensureUpdated(); - ////////////////////////////////////////////////////////////////////////////////// - // Members variables // - ////////////////////////////////////////////////////////////////////////////////// + std::string _datasetFile; + std::string _gdalXmlTemplate; - std::string _datasetFile; - std::string _gdalXmlTemplate; + std::unordered_map> _tileProviderMap; - std::unordered_map > _tileProviderMap; + // Used for creation of time specific instances of CachingTileProvider + ghoul::Dictionary _initDict; - // Used for creation of time specific instances of CachingTileProvider - ghoul::Dictionary _initDict; - - - Tile _defaultTile; - - std::shared_ptr _currentTileProvider; + Tile _defaultTile; + std::shared_ptr _currentTileProvider; - TimeFormat * _timeFormat; - TimeQuantizer _timeQuantizer; - }; + TimeFormat* _timeFormat; + TimeQuantizer _timeQuantizer; +}; +} // namespace globebrowsing +} // namespace openspace - -} // namespace openspace - - - - -#endif // __TEMPORAL_TILE_PROVIDER_H__ \ No newline at end of file +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___TEMPORAL_TILE_PROVIDER___H__ diff --git a/modules/globebrowsing/tile/tileprovider/texttileprovider.cpp b/modules/globebrowsing/tile/tileprovider/texttileprovider.cpp index 39b070b628..278a7d4234 100644 --- a/modules/globebrowsing/tile/tileprovider/texttileprovider.cpp +++ b/modules/globebrowsing/tile/tileprovider/texttileprovider.cpp @@ -1,274 +1,261 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ #include -#include - -#include -#include - -#include -#include - #include -#include - - - - -namespace { - const std::string _loggerCat = "TextTileProvider"; -} +#include +#include +#include +#include +#include +using namespace ghoul::fontrendering; namespace openspace { +namespace globebrowsing { - TextTileProvider::TextTileProvider(const glm::uvec2& textureSize, size_t fontSize) - : _tileCache(500) - , _textureSize(textureSize) - , _fontSize(fontSize) - { - - _font = OsEng.fontManager().font("Mono", _fontSize); +TextTileProvider::TextTileProvider(const glm::uvec2& textureSize, size_t fontSize) + : _tileCache(500) + , _textureSize(textureSize) + , _fontSize(fontSize) +{ + _font = OsEng.fontManager().font("Mono", _fontSize); - _fontRenderer = std::unique_ptr(FontRenderer::createDefault()); - _fontRenderer->setFramebufferSize(textureSize); + _fontRenderer = std::unique_ptr(FontRenderer::createDefault()); + _fontRenderer->setFramebufferSize(textureSize); + glGenFramebuffers(1, &_fbo); +} - glGenFramebuffers(1, &_fbo); - } +TextTileProvider::~TextTileProvider() { + glDeleteFramebuffers(1, &_fbo); +} - TextTileProvider::~TextTileProvider() { - glDeleteFramebuffers(1, &_fbo); - } - - Tile TextTileProvider::getTile(const ChunkIndex& chunkIndex) { - ChunkHashKey key = chunkIndex.hashKey(); +Tile TextTileProvider::getTile(const TileIndex& tileIndex) { + TileHashKey key = tileIndex.hashKey(); - if (!_tileCache.exist(key)) { - _tileCache.put(key, createChunkIndexTile(chunkIndex)); - } - - return _tileCache.get(key); + if (!_tileCache.exist(key)) { + _tileCache.put(key, createChunkIndexTile(tileIndex)); } - Tile TextTileProvider::getDefaultTile() { - return Tile::TileUnavailable; - } + return _tileCache.get(key); +} +Tile TextTileProvider::getDefaultTile() { + return Tile::TileUnavailable; +} - Tile::Status TextTileProvider::getTileStatus(const ChunkIndex& index) { - return Tile::Status::OK; - } +Tile::Status TextTileProvider::getTileStatus(const TileIndex& index) { + return Tile::Status::OK; +} - TileDepthTransform TextTileProvider::depthTransform() { - TileDepthTransform transform; - transform.depthOffset = 0.0f; - transform.depthScale = 1.0f; - return transform; - } +TileDepthTransform TextTileProvider::depthTransform() { + TileDepthTransform transform; + transform.depthOffset = 0.0f; + transform.depthScale = 1.0f; + return transform; +} - void TextTileProvider::update() { - // nothing to be done - } +void TextTileProvider::update() {} - void TextTileProvider::reset() { - _tileCache.clear(); - } +void TextTileProvider::reset() { + _tileCache.clear(); +} - Tile TextTileProvider::createChunkIndexTile(const ChunkIndex& chunkIndex) { - Tile tile = backgroundTile(chunkIndex); +Tile TextTileProvider::createChunkIndexTile(const TileIndex& tileIndex) { + Tile tile = backgroundTile(tileIndex); - // Keep track of defaultFBO and viewport to be able to reset state when done - GLint defaultFBO; - GLint viewport[4]; - glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); - glGetIntegerv(GL_VIEWPORT, viewport); + // Keep track of defaultFBO and viewport to be able to reset state when done + GLint defaultFBO; + GLint viewport[4]; + glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); + glGetIntegerv(GL_VIEWPORT, viewport); - // Render to texture - glBindFramebuffer(GL_FRAMEBUFFER, _fbo); - glFramebufferTexture2D( - GL_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - GL_TEXTURE_2D, - *(tile.texture), - 0 - ); + // Render to texture + glBindFramebuffer(GL_FRAMEBUFFER, _fbo); + glFramebufferTexture2D( + GL_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_TEXTURE_2D, + *(tile.texture), + 0 + ); - GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); - //LDEBUG(status); + GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); - glViewport( - 0, 0, - static_cast(tile.texture->width()), - static_cast(tile.texture->height()) - ); + glViewport( + 0, 0, + static_cast(tile.texture->width()), + static_cast(tile.texture->height()) + ); - ghoul_assert(_fontRenderer != nullptr, "_fontRenderer must not be null"); - renderText(*_fontRenderer, chunkIndex); + ghoul_assert(_fontRenderer != nullptr, "_fontRenderer must not be null"); + renderText(*_fontRenderer, tileIndex); - // Reset state: bind default FBO and set viewport to what it was - glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO); - glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); + // Reset state: bind default FBO and set viewport to what it was + glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO); + glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); + return tile; +} + +int TextTileProvider::maxLevel() { + return 1337; // unlimited +} + +TileHashKey TextTileProvider::toHash(const TileIndex& tileIndex) const { + return tileIndex.hashKey(); +} + +Tile TextTileProvider::backgroundTile(const TileIndex& tileIndex) const { + glm::uvec4 color = { 0, 0, 0, 0 }; + return Tile::createPlainTile(_textureSize, color); +} + +void TileIndexTileProvider::renderText(const FontRenderer& fontRenderer, const TileIndex& tileIndex) const { + fontRenderer.render( + *_font, + glm::vec2( + _textureSize.x / 4 - (_textureSize.x / 32) * log10(1 << tileIndex.level), + _textureSize.y / 2 + _fontSize), + glm::vec4(1.0, 0.0, 0.0, 1.0), + "level: %i \nx: %i \ny: %i", + tileIndex.level, tileIndex.x, tileIndex.y + ); +} + +namespace { + const char* KeyRadii = "Radii"; + const char* KeyBackgroundImagePath = "BackgroundImagePath"; +} + +SizeReferenceTileProvider::SizeReferenceTileProvider(const ghoul::Dictionary& dictionary) +{ + _fontSize = 50; + FontManager& fm = OsEng.fontManager(); + _font = fm.font("Mono", _fontSize); + + glm::dvec3 radii(1,1,1); + if (!dictionary.getValue(KeyRadii, radii)) { + throw std::runtime_error("Must define key '" + std::string(KeyRadii) + "'"); + } + _ellipsoid = Ellipsoid(radii); + + _backgroundTile.status = Tile::Status::Unavailable; + std::string backgroundImagePath; + if (dictionary.getValue(KeyBackgroundImagePath, backgroundImagePath)) { + using namespace ghoul::io; + std::string imgAbsPath = absPath(backgroundImagePath); + _backgroundTile.texture = TextureReader::ref().loadTexture(imgAbsPath); + _backgroundTile.texture->uploadTexture(); + _backgroundTile.texture->setFilter(ghoul::opengl::Texture::FilterMode::Linear); + _backgroundTile.status = Tile::Status::OK; + } + +} + +void SizeReferenceTileProvider::renderText(const FontRenderer& fontRenderer, + const TileIndex& tileIndex) const +{ + GeodeticPatch patch(tileIndex); + bool aboveEquator = patch.isNorthern(); + + double tileLongitudalLength = roundedLongitudalLength(tileIndex); + + std::string unit = "m"; + if (tileLongitudalLength > 9999) { + tileLongitudalLength *= 0.001; + unit = "km"; + } + + glm::vec2 textPosition; + textPosition.x = 0; + textPosition.y = aboveEquator ? _fontSize / 2 : _textureSize.y - 3 * _fontSize / 2; + glm::vec4 color(1.0, 1.0, 1.0, 1.0); + + fontRenderer.render( + *_font, + textPosition, + color, + " %.0f %s", + tileLongitudalLength, unit.c_str() + ); +} + +int SizeReferenceTileProvider::roundedLongitudalLength(const TileIndex& tileIndex) const { + GeodeticPatch patch(tileIndex); + bool aboveEquator = patch.isNorthern(); + double lat = aboveEquator ? patch.minLat() : patch.maxLat(); + double lon1 = patch.minLon(); + double lon2 = patch.maxLon(); + int l = static_cast(_ellipsoid.longitudalDistance(lat, lon1, lon2)); + + bool useKm = l > 9999; + if (useKm) { + l /= 1000; + } + l = std::round(l); + if (useKm) { + l *= 1000; + } + + return l; +} + +TileHashKey SizeReferenceTileProvider::toHash(const TileIndex& tileIndex) const { + int l = roundedLongitudalLength(tileIndex); + TileHashKey key = static_cast(l); + return key; +} + +Tile SizeReferenceTileProvider::backgroundTile(const TileIndex& tileIndex) const { + if (_backgroundTile.status == Tile::Status::OK) { + Tile tile; + auto t = _backgroundTile.texture; + void* pixelData = new char[t->expectedPixelDataSize()]; + memcpy(pixelData, t->pixelData(), t->expectedPixelDataSize()); + tile.texture = std::make_shared( + pixelData, + t->dimensions(), + t->format(), + t->internalFormat(), + t->dataType(), + t->filter(), + t->wrapping() + ); + tile.texture->uploadTexture(); + tile.texture->setDataOwnership(Texture::TakeOwnership::Yes); + tile.status = Tile::Status::OK; return tile; } - - int TextTileProvider::maxLevel() { - return 1337; // unlimited + else { + // use default background + return TextTileProvider::backgroundTile(tileIndex); } +} - ChunkHashKey TextTileProvider::toHash(const ChunkIndex& chunkIndex) const { - return chunkIndex.hashKey(); - } - - - Tile TextTileProvider::backgroundTile(const ChunkIndex& chunkIndex) const { - glm::uvec4 color = { 0, 0, 0, 0 }; - return Tile::createPlainTile(_textureSize, color); - } - - - ////////////////////////////////////////////////////////////////////////////////////// - // Chunk Index Tile Provider // - ////////////////////////////////////////////////////////////////////////////////////// - - void ChunkIndexTileProvider::renderText(const FontRenderer& fontRenderer, const ChunkIndex& chunkIndex) const { - fontRenderer.render( - *_font, - glm::vec2( - _textureSize.x / 4 - (_textureSize.x / 32) * log10(1 << chunkIndex.level), - _textureSize.y / 2 + _fontSize), - glm::vec4(1.0, 0.0, 0.0, 1.0), - "level: %i \nx: %i \ny: %i", - chunkIndex.level, chunkIndex.x, chunkIndex.y - ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - // Tile Size Reference Tile Provider // - ////////////////////////////////////////////////////////////////////////////////////// - - namespace { - const std::string KeyRadii = "Radii"; - const std::string KeyBackgroundImagePath = "BackgroundImagePath"; - } - - SizeReferenceTileProvider::SizeReferenceTileProvider(const ghoul::Dictionary& dictionary) { - _fontSize = 50; - ghoul::fontrendering::FontManager& fm = OsEng.fontManager(); - _font = fm.font("Mono", _fontSize); - - glm::dvec3 radii(1,1,1); - if (!dictionary.getValue(KeyRadii, radii)) { - throw std::runtime_error("Must define key '" + KeyRadii + "'"); - } - _ellipsoid = Ellipsoid(radii); - - _backgroundTile.status = Tile::Status::Unavailable; - std::string backgroundImagePath; - if (dictionary.getValue(KeyBackgroundImagePath, backgroundImagePath)) { - using namespace ghoul::io; - std::string imgAbsPath = absPath(backgroundImagePath); - _backgroundTile.texture = TextureReader::ref().loadTexture(imgAbsPath); - _backgroundTile.texture->uploadTexture(); - _backgroundTile.texture->setFilter(ghoul::opengl::Texture::FilterMode::Linear); - _backgroundTile.status = Tile::Status::OK; - } - - } - - void SizeReferenceTileProvider::renderText(const FontRenderer& fontRenderer, const ChunkIndex& chunkIndex) const { - GeodeticPatch patch(chunkIndex); - bool aboveEquator = patch.isNorthern(); - - double tileLongitudalLength = roundedLongitudalLength(chunkIndex); - - std::string unit = "m"; - if (tileLongitudalLength > 9999) { - tileLongitudalLength *= 0.001; - unit = "km"; - } - - glm::vec2 textPosition; - textPosition.x = 0; - textPosition.y = aboveEquator ? _fontSize / 2 : _textureSize.y - 3 * _fontSize / 2; - glm::vec4 color(1.0, 1.0, 1.0, 1.0); - - fontRenderer.render( - *_font, - textPosition, - color, - " %.0f %s", - tileLongitudalLength, unit.c_str() - ); - } - - int SizeReferenceTileProvider::roundedLongitudalLength(const ChunkIndex& chunkIndex) const { - GeodeticPatch patch(chunkIndex); - bool aboveEquator = patch.isNorthern(); - double lat = aboveEquator ? patch.minLat() : patch.maxLat(); - double lon1 = patch.minLon(); - double lon2 = patch.maxLon(); - int l = static_cast(_ellipsoid.longitudalDistance(lat, lon1, lon2)); - - bool useKm = l > 9999; - if (useKm) l /= 1000; - l = std::round(l); - if (useKm) l *= 1000; - - return l; - } - - ChunkHashKey SizeReferenceTileProvider::toHash(const ChunkIndex& chunkIndex) const { - int l = roundedLongitudalLength(chunkIndex); - ChunkHashKey key = static_cast(l); - return key; - } - - Tile SizeReferenceTileProvider::backgroundTile(const ChunkIndex& chunkIndex) const { - if (_backgroundTile.status == Tile::Status::OK) { - Tile tile; - auto t = _backgroundTile.texture; - void* pixelData = new char[t->expectedPixelDataSize()]; - memcpy(pixelData, t->pixelData(), t->expectedPixelDataSize()); - tile.texture = std::make_shared( - pixelData, t->dimensions(), t->format(), t->internalFormat(), t->dataType(), t->filter(), t->wrapping()); - tile.texture->uploadTexture(); - tile.texture->setDataOwnership(Texture::TakeOwnership::Yes); - tile.status = Tile::Status::OK; - return tile; - } - else { - // use default background - return TextTileProvider::backgroundTile(chunkIndex); - } - } - - - - -} // namespace openspace +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/tile/tileprovider/texttileprovider.h b/modules/globebrowsing/tile/tileprovider/texttileprovider.h index a31c8510e3..a158fb7416 100644 --- a/modules/globebrowsing/tile/tileprovider/texttileprovider.h +++ b/modules/globebrowsing/tile/tileprovider/texttileprovider.h @@ -1,152 +1,137 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __TEXT_TILE_PROVIDER_H__ -#define __TEXT_TILE_PROVIDER_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___TEXT_TILE_PROVIDER___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___TEXT_TILE_PROVIDER___H__ -#include - -#include -#include // absPath -#include - -#include - -#include -#include - -#include #include -#include + #include +namespace ghoul { namespace fontrendering { -////////////////////////////////////////////////////////////////////////////////////////// -// TILE PROVIDER // -////////////////////////////////////////////////////////////////////////////////////////// +class Font; +class FontRenderer; +}} namespace openspace { - using namespace ghoul::fontrendering; +namespace globebrowsing { + +/** + * Enables a simple way of providing tiles with any type of rendered text. + * Internally it handles setting up a FBO for rendering the text, and defines a new + * interface, consisting of only a single method for subclasses to implement: + * renderText(const FontRenderer&, const TileIndex&) const; + */ +class TextTileProvider : public TileProvider { +public: + /** + * Default constructor with default values for texture and font size + */ + TextTileProvider(const glm::uvec2& textureSize = {512, 512}, size_t fontSize = 48); + virtual ~TextTileProvider(); + + // The TileProvider interface below is implemented in this class + virtual Tile getTile(const TileIndex& tileIndex); + virtual Tile getDefaultTile(); + virtual Tile::Status getTileStatus(const TileIndex& index); + virtual TileDepthTransform depthTransform(); + virtual void update(); + virtual void reset(); + virtual int maxLevel(); /** - * Enables a simple way of providing tiles with any type of rendered text. - * Internally it handles setting up a FBO for rendering the text, and defines a new - * interface, consisting of only a single method for subclasses to implement: - * renderText(const FontRenderer&, const ChunkIndex&) const; + * Returns the tile which will be used to draw text onto. + * Default implementation returns a tile with a plain transparent texture. */ - class TextTileProvider : public TileProvider { - public: + virtual Tile backgroundTile(const TileIndex& tileIndex) const; - /** - * Default constructor with default values for texture and font size - */ - TextTileProvider(const glm::uvec2& textureSize = {512, 512}, size_t fontSize = 48); - virtual ~TextTileProvider(); - - // The TileProvider interface below is implemented in this class - - virtual Tile getTile(const ChunkIndex& chunkIndex); - virtual Tile getDefaultTile(); - virtual Tile::Status getTileStatus(const ChunkIndex& index); - virtual TileDepthTransform depthTransform(); - virtual void update(); - virtual void reset(); - virtual int maxLevel(); - - /** - * Returns the tile which will be used to draw text onto. - * Default implementation returns a tile with a plain transparent texture. - */ - virtual Tile backgroundTile(const ChunkIndex& chunkIndex) const; - - - /** - * Allow overriding of hash function. - * Default is ChunkIndex::hashKey() - * - * \param chunkIndex chunkIndex to hash - * \returns hashkey used for in LRU cache for this tile - */ - virtual ChunkHashKey toHash(const ChunkIndex& chunkIndex) const; + /** + * Allow overriding of hash function. + * Default is TileIndex::hashKey() + * + * \param tileIndex tileIndex to hash + * \returns hashkey used for in LRU cache for this tile + */ + virtual TileHashKey toHash(const TileIndex& tileIndex) const; - /** - * Uses the fontRenderer to render some text onto the tile texture provided in - * backgroundTile(const ChunkIndex& chunkIndex). - * - * \param fontRenderer used for rendering text onto texture - * \param chunkIndex associated with the tile to be rendered onto - */ - virtual void renderText(const FontRenderer& fontRenderer, const ChunkIndex& chunkIndex) const = 0; - - protected: - std::shared_ptr _font; - glm::uvec2 _textureSize; - size_t _fontSize; - - private: - Tile createChunkIndexTile(const ChunkIndex& chunkIndex); - std::unique_ptr _fontRenderer; - - TileCache _tileCache; - GLuint _fbo; - }; - - /** - * Provides Tiles with the chunk index rendered as text onto its tiles. + * Uses the fontRenderer to render some text onto the tile texture provided in + * backgroundTile(const TileIndex& tileIndex). + * + * \param fontRenderer used for rendering text onto texture + * \param tileIndex associated with the tile to be rendered onto */ - class ChunkIndexTileProvider : public TextTileProvider { - public: - virtual void renderText(const FontRenderer& fontRenderer, const ChunkIndex& chunkIndex) const; - }; + virtual void renderText(const ghoul::fontrendering::FontRenderer& fontRenderer, + const TileIndex& tileIndex) const = 0; - /** - * Constructed with an ellipsoid and uses that to render the longitudal length of each - * of each tile. - */ - class SizeReferenceTileProvider : public TextTileProvider { - public: - SizeReferenceTileProvider(const ghoul::Dictionary& dictionary); +protected: + std::shared_ptr _font; + glm::uvec2 _textureSize; + size_t _fontSize; - virtual void renderText(const FontRenderer& fontRenderer, const ChunkIndex& chunkIndex) const; - virtual Tile backgroundTile(const ChunkIndex& chunkIndex) const; +private: + Tile createChunkIndexTile(const TileIndex& tileIndex); + std::unique_ptr _fontRenderer; - virtual ChunkHashKey toHash(const ChunkIndex& chunkIndex) const; + TileCache _tileCache; + GLuint _fbo; +}; +/** + * Provides Tiles with the chunk index rendered as text onto its tiles. + */ +class TileIndexTileProvider : public TextTileProvider { +public: + virtual void renderText(const ghoul::fontrendering::FontRenderer& fontRenderer, + const TileIndex& tileIndex) const; +}; - private: +/** + * Constructed with an ellipsoid and uses that to render the longitudal length of each + * of each tile. + */ +class SizeReferenceTileProvider : public TextTileProvider { +public: + SizeReferenceTileProvider(const ghoul::Dictionary& dictionary); - int roundedLongitudalLength(const ChunkIndex& chunkIndex) const; + virtual void renderText(const ghoul::fontrendering::FontRenderer& fontRenderer, + const TileIndex& tileIndex) const; + virtual Tile backgroundTile(const TileIndex& tileIndex) const; - Ellipsoid _ellipsoid; - Tile _backgroundTile; - }; + virtual TileHashKey toHash(const TileIndex& tileIndex) const; -} // namespace openspace +private: + int roundedLongitudalLength(const TileIndex& tileIndex) const; + Ellipsoid _ellipsoid; + Tile _backgroundTile; +}; +} // namespace globebrowsing +} // namespace openspace -#endif // __TEXT_TILE_PROVIDER_H__ \ No newline at end of file +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___TEXT_TILE_PROVIDER___H__ diff --git a/modules/globebrowsing/tile/tileprovider/tileprovider.cpp b/modules/globebrowsing/tile/tileprovider/tileprovider.cpp index f47121ec71..b3f25fbc66 100644 --- a/modules/globebrowsing/tile/tileprovider/tileprovider.cpp +++ b/modules/globebrowsing/tile/tileprovider/tileprovider.cpp @@ -1,53 +1,49 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ #include +#include + #include +#include #include - namespace { const std::string _loggerCat = "TileProvider"; - const std::string KeyType = "Type"; + const char* KeyType = "Type"; } - namespace openspace { +namespace globebrowsing { TileProvider* TileProvider::createFromDictionary(const ghoul::Dictionary& dictionary) { - if (!dictionary.hasValue(KeyType)) { - LERROR("TileProvider did not have key '" << KeyType << "'"); - return nullptr; - } - - std::string type; + std::string type = "LRUCaching"; dictionary.getValue(KeyType, type); - ghoul::TemplateFactory* factory - = FactoryManager::ref().factory(); + auto factory = FactoryManager::ref().factory(); TileProvider* result = factory->create(type, dictionary); if (result == nullptr) { @@ -58,6 +54,73 @@ TileProvider* TileProvider::createFromDictionary(const ghoul::Dictionary& dictio return result; } -TileProvider::TileProvider(const ghoul::Dictionary& dictionary) { }; +TileProvider::TileProvider(const ghoul::Dictionary& dictionary) {}; -} // namespace openspace +float TileProvider::noDataValueAsFloat() { + return std::numeric_limits::min(); +} + +ChunkTile TileProvider::getChunkTile(TileIndex tileIndex, int parents, int maxParents) { + TileUvTransform uvTransform; + uvTransform.uvOffset = glm::vec2(0, 0); + uvTransform.uvScale = glm::vec2(1, 1); + + // Step 1. Traverse 0 or more parents up the chunkTree as requested by the caller + for (int i = 0; i < parents && tileIndex.level > 1; i++) { + TileSelector::ascendToParent(tileIndex, uvTransform); + } + maxParents -= parents; + + // Step 2. Traverse 0 or more parents up the chunkTree to make sure we're inside + // the range of defined data. + int maximumLevel = maxLevel(); + while (tileIndex.level > maximumLevel){ + TileSelector::ascendToParent(tileIndex, uvTransform); + maxParents--; + } + if(maxParents < 0){ + return { Tile::TileUnavailable, uvTransform }; + } + + // Step 3. Traverse 0 or more parents up the chunkTree until we find a chunk that + // has a loaded tile ready to use. + while (tileIndex.level > 1) { + Tile tile = getTile(tileIndex); + if (tile.status != Tile::Status::OK) { + if (--maxParents < 0){ + return{ Tile::TileUnavailable, uvTransform }; + } + TileSelector::ascendToParent(tileIndex, uvTransform); + } + else { + return { tile, uvTransform }; + } + } + + return { Tile::TileUnavailable, uvTransform }; +} + +ChunkTilePile TileProvider::getChunkTilePile(TileIndex tileIndex, int pileSize){ + ghoul_assert(pileSize >= 0, "pileSize must be positive"); + ChunkTilePile chunkTilePile; + chunkTilePile.chunkTiles.resize(pileSize); + for (size_t i = 0; i < pileSize; ++i) { + chunkTilePile.chunkTiles[i] = getChunkTile(tileIndex, i); + if (chunkTilePile.chunkTiles[i].tile.status == Tile::Status::Unavailable) { + if (i>0) { + chunkTilePile.chunkTiles[i].tile = chunkTilePile.chunkTiles[i-1].tile; + chunkTilePile.chunkTiles[i].uvTransform.uvOffset = chunkTilePile.chunkTiles[i-1].uvTransform.uvOffset; + chunkTilePile.chunkTiles[i].uvTransform.uvScale = chunkTilePile.chunkTiles[i-1].uvTransform.uvScale; + } + else { + chunkTilePile.chunkTiles[i].tile = getDefaultTile(); + chunkTilePile.chunkTiles[i].uvTransform.uvOffset = { 0, 0 }; + chunkTilePile.chunkTiles[i].uvTransform.uvScale = { 1, 1 }; + } + } + } + return std::move(chunkTilePile); +} + +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/tile/tileprovider/tileprovider.h b/modules/globebrowsing/tile/tileprovider/tileprovider.h index 3e39c7c30d..7a43c24482 100644 --- a/modules/globebrowsing/tile/tileprovider/tileprovider.h +++ b/modules/globebrowsing/tile/tileprovider/tileprovider.h @@ -1,153 +1,149 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __TILE_PROVIDER_H__ -#define __TILE_PROVIDER_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___TILE_PROVIDER___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___TILE_PROVIDER___H__ -#include // absPath -#include -#include - -#include +#include #include #include -////////////////////////////////////////////////////////////////////////////////////////// -// TILE PROVIDER // -////////////////////////////////////////////////////////////////////////////////////////// +#include namespace openspace { +namespace globebrowsing { - using namespace ghoul::opengl; - +/** + * Interface for providing Tiles given a + * TileIndex. + */ +class TileProvider { +public: /** - * Interface for providing Tiles given a - * ChunkIndex. - */ - class TileProvider { - public: + * Factory method for instantiating different implementations of + * TileProviders. The provided dictionary must + * define a key specifying what implementation of TileProvider + * to be instantiated. + */ + static TileProvider* createFromDictionary(const ghoul::Dictionary& dictionary); - /** - * Factory method for instantiating different implementations of - * TileProviders. The provided dictionary must - * define a key specifying what implementation of TileProvider - * to be instantiated. - */ - static TileProvider* createFromDictionary(const ghoul::Dictionary& dictionary); + /** + * Empty default constructor + */ + TileProvider() = default; - /** - * Empty default constructor - */ - TileProvider() {}; + /** + * Implementations of the TileProvider interface must implement + * a constructor taking a dictionary as input. The provided + * dictionary must define a key specifying what implementation + * of TileProvider to be instantiated. + */ + TileProvider(const ghoul::Dictionary& dictionary); - /** - * Implementations of the TileProvider interface must implement - * a constructor taking a dictionary as input. The provided - * dictionary must define a key specifying what implementation - * of TileProvider to be instantiated. - */ - TileProvider(const ghoul::Dictionary& dictionary); + /** + * Virtual destructor that subclasses should override to do + * clean up. + */ + virtual ~TileProvider() { } - /** - * Virtual destructor that subclasses should override to do - * clean up. - */ - virtual ~TileProvider() { } + /** + * Method for querying tiles, given a specified TileIndex. + * + * This method is expected to be invoked multiple times per frame, + * and should therefore return quickly, e.g. not perform heavy I/O + * operations. However, invoking this method may spawn separate threads + * to perform such operations. Therefore, programmers shoud + * note that there is no guarantee that the Tile + * status and texture will be consistent over different invocations + * of this method. + * + * \param tileIndex specifying a region of a map for which + * we want tile data. + * + * \returns The tile corresponding to the TileIndex by the time + * the method was invoked. + */ + virtual Tile getTile(const TileIndex& tileIndex) = 0; - /** - * Method for querying tiles, given a specified ChunkIndex. - * - * This method is expected to be invoked multiple times per frame, - * and should therefore return quickly, e.g. not perform heavy I/O - * operations. However, invoking this method may spawn separate threads - * to perform such operations. Therefore, programmers shoud - * note that there is no guarantee that the Tile - * status and texture will be consistent over different invocations - * of this method. - * - * \param chunkIndex specifying a region of a map for which - * we want tile data. - * - * \returns The tile corresponding to the ChunkIndex by the time - * the method was invoked. - */ - virtual Tile getTile(const ChunkIndex& chunkIndex) = 0; - /** - * TileProviders must be able to provide a defualt - * Tile which may be used by clients in cases when - * requested tiles were unavailable. - * - * \returns A default tile - */ - virtual Tile getDefaultTile() = 0; + virtual ChunkTile getChunkTile(TileIndex tileIndex, int parents = 0, + int maxParents = 1337); - /** - * Returns the status of a Tile. The Tile::Status - * corresponds the Tile that would be returned - * if the function getTile would be invoked with the same - * ChunkIndex argument at this point in time. - */ - virtual Tile::Status getTileStatus(const ChunkIndex& index) = 0; + virtual ChunkTilePile getChunkTilePile(TileIndex tileIndex, int pileSize); - /** - * Get the associated depth transform for this TileProvider. - * This is necessary for TileProviders serving height map - * data, in order to correcly map pixel values to meters. - */ - virtual TileDepthTransform depthTransform() = 0; + /** + * TileProviders must be able to provide a defualt + * Tile which may be used by clients in cases when + * requested tiles were unavailable. + * + * \returns A default tile + */ + virtual Tile getDefaultTile() = 0; - /** - * This method should be called once per frame. Here, TileProviders - * are given the opportunity to update their internal state. - */ - virtual void update() = 0; + /** + * Returns the status of a Tile. The Tile::Status + * corresponds the Tile that would be returned + * if the function getTile would be invoked with the same + * TileIndex argument at this point in time. + */ + virtual Tile::Status getTileStatus(const TileIndex& index) = 0; - /** - * Provides a uniform way of all TileProviders to reload or - * restore all of its internal state. This is mainly useful - * for debugging purposes. - */ - virtual void reset() = 0; + /** + * Get the associated depth transform for this TileProvider. + * This is necessary for TileProviders serving height map + * data, in order to correcly map pixel values to meters. + */ + virtual TileDepthTransform depthTransform() = 0; - /** - * \returns The maximum level as defined by ChunkIndex - * that this TileProvider is able provide. - */ - virtual int maxLevel() = 0; - }; + /** + * This method should be called once per frame. Here, TileProviders + * are given the opportunity to update their internal state. + */ + virtual void update() = 0; - typedef LRUCache TileCache; + /** + * Provides a uniform way of all TileProviders to reload or + * restore all of its internal state. This is mainly useful + * for debugging purposes. + */ + virtual void reset() = 0; - struct TileProviderInitData { - int minimumPixelSize; - int threads; - int cacheSize; - int framesUntilRequestQueueFlush; - bool preprocessTiles = false; - }; + /** + * \returns The maximum level as defined by TileIndex + * that this TileProvider is able provide. + */ + virtual int maxLevel() = 0; + + /** + * \returns the no data value for the dataset. Default is the minimum float avalue. + */ + virtual float noDataValueAsFloat(); +}; -} // namespace openspace +using TileCache = LRUCache; -#endif // __TILE_PROVIDER_H__ \ No newline at end of file +} // namespace globebrowsing +} // namespace openspace + +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___TILE_PROVIDER___H__ diff --git a/modules/globebrowsing/tile/tileprovider/tileproviderbyindex.cpp b/modules/globebrowsing/tile/tileprovider/tileproviderbyindex.cpp new file mode 100644 index 0000000000..44e4eda06c --- /dev/null +++ b/modules/globebrowsing/tile/tileprovider/tileproviderbyindex.cpp @@ -0,0 +1,117 @@ +/***************************************************************************************** +* * +* OpenSpace * +* * +* Copyright (c) 2014-2016 * +* * +* Permission is hereby granted, free of charge, to any person obtaining a copy of this * +* software and associated documentation files (the "Software"), to deal in the Software * +* without restriction, including without limitation the rights to use, copy, modify, * +* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * +* permit persons to whom the Software is furnished to do so, subject to the following * +* conditions: * +* * +* The above copyright notice and this permission notice shall be included in all copies * +* or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * +* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * +* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * +* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * +* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * +* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * +****************************************************************************************/ + +#include + +#include + +namespace { + const std::string _loggerCat = "TileProviderByIndex"; + + const char* KeyDefaultProvider = "DefaultProvider"; + const char* KeyProviders = "IndexTileProviders"; + const char* KeyTileIndex = "TileIndex"; + const char* KeyTileProvider = "TileProvider"; +} + +namespace openspace { +namespace globebrowsing { + +TileProviderByIndex::TileProviderByIndex(const ghoul::Dictionary& dictionary) { + ghoul::Dictionary defaultProviderDict = dictionary.value( + KeyDefaultProvider + ); + TileProvider* defaultProvider = TileProvider::createFromDictionary( + defaultProviderDict + ); + _defaultTileProvider = std::shared_ptr(defaultProvider); + + ghoul::Dictionary indexProvidersDict = dictionary.value( + KeyProviders + ); + for (size_t i = 0; i < indexProvidersDict.size(); i++) { + std::string dictKey = std::to_string(i + 1); + ghoul::Dictionary indexProviderDict = indexProvidersDict.value( + dictKey + ); + ghoul::Dictionary tileIndexDict = indexProviderDict.value( + KeyTileIndex + ); + ghoul::Dictionary providerDict = indexProviderDict.value( + KeyTileProvider + ); + + TileIndex tileIndex(tileIndexDict); + TileProvider* tileProvider = TileProvider::createFromDictionary(providerDict); + std::shared_ptr stp = std::shared_ptr(tileProvider); + TileHashKey key = tileIndex.hashKey(); + _tileProviderMap.insert(std::make_pair(key, stp)); + } +} + +Tile TileProviderByIndex::getTile(const TileIndex& tileIndex) { + auto it = _tileProviderMap.find(tileIndex.hashKey()); + bool hasProvider = it != _tileProviderMap.end(); + return hasProvider ? it->second->getTile(tileIndex) : Tile::TileUnavailable; +} + +Tile TileProviderByIndex::getDefaultTile() { + return _defaultTileProvider->getDefaultTile(); +} + +Tile::Status TileProviderByIndex::getTileStatus(const TileIndex& tileIndex) { + auto it = _tileProviderMap.find(tileIndex.hashKey()); + bool hasProvider = it != _tileProviderMap.end(); + return hasProvider ? it->second->getTileStatus(tileIndex) : Tile::Status::Unavailable; +} + +TileDepthTransform TileProviderByIndex::depthTransform() { + return _defaultTileProvider->depthTransform(); +} + +void TileProviderByIndex::update() { + for (auto& it : _tileProviderMap){ + it.second->update(); + } + _defaultTileProvider->update(); +} + +void TileProviderByIndex::reset() { + for (auto& it : _tileProviderMap) { + it.second->reset(); + } + _defaultTileProvider->reset(); +} + +int TileProviderByIndex::maxLevel() { + return _defaultTileProvider->maxLevel(); +} + +TileProvider* TileProviderByIndex::indexProvider(const TileIndex& tileIndex) const { + auto it = _tileProviderMap.find(tileIndex.hashKey()); + return (it != _tileProviderMap.end()) ? it->second.get() : nullptr; +} + +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/tile/tileprovider/tileproviderbyindex.h b/modules/globebrowsing/tile/tileprovider/tileproviderbyindex.h new file mode 100644 index 0000000000..09e4922e71 --- /dev/null +++ b/modules/globebrowsing/tile/tileprovider/tileproviderbyindex.h @@ -0,0 +1,57 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___TILE_PROVIDER_BY_INDEX___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___TILE_PROVIDER_BY_INDEX___H__ + +#include + +namespace openspace { +namespace globebrowsing { + +class TileProviderByIndex : public TileProvider { +public: + TileProviderByIndex(const ghoul::Dictionary& dictionary); + TileProviderByIndex(const std::string& imagePath); + virtual ~TileProviderByIndex() { } + + virtual Tile getTile(const TileIndex& tileIndex); + virtual Tile getDefaultTile(); + virtual Tile::Status getTileStatus(const TileIndex& index); + virtual TileDepthTransform depthTransform(); + virtual void update(); + virtual void reset(); + virtual int maxLevel(); + +private: + TileProvider* indexProvider(const TileIndex& tileIndex) const; + + std::unordered_map> _tileProviderMap; + std::shared_ptr _defaultTileProvider; +}; + +} // namespace globebrowsing +} // namespace openspace + +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___TILE_PROVIDER_BY_INDEX___H__ diff --git a/modules/globebrowsing/tile/tileprovider/tileproviderbylevel.cpp b/modules/globebrowsing/tile/tileprovider/tileproviderbylevel.cpp new file mode 100644 index 0000000000..7a0edaf313 --- /dev/null +++ b/modules/globebrowsing/tile/tileprovider/tileproviderbylevel.cpp @@ -0,0 +1,132 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +namespace { + const std::string _loggerCat = "TileProviderByLevel"; + + const char* KeyProviders = "LevelTileProviders"; + const char* KeyMaxLevel = "MaxLevel"; + const char* KeyTileProvider = "TileProvider"; +} + +namespace openspace { +namespace globebrowsing { + +TileProviderByLevel::TileProviderByLevel(const ghoul::Dictionary& dictionary) { + ghoul::Dictionary levelProvidersDict = dictionary.value( + KeyProviders + ); + + for (size_t i = 0; i < levelProvidersDict.size(); i++) { + std::string dictKey = std::to_string(i + 1); + ghoul::Dictionary levelProviderDict = levelProvidersDict.value( + dictKey + ); + double floatMaxLevel; + int maxLevel = 0; + if (!levelProviderDict.getValue(KeyMaxLevel, floatMaxLevel)) { + throw std::runtime_error( + "Must define key '" + std::string(KeyMaxLevel) + "'" + ); + } + maxLevel = std::round(floatMaxLevel); + + ghoul::Dictionary providerDict; + if (!levelProviderDict.getValue(KeyTileProvider, providerDict)) + { + throw std::runtime_error( + "Must define key '" + std::string(KeyTileProvider) + "'" + ); + } + + TileProvider* tileProvider = TileProvider::createFromDictionary(providerDict); + _levelTileProviders.push_back(std::shared_ptr(tileProvider)); + + // Ensure we can represent the max level + if(_providerIndices.size() < maxLevel){ + _providerIndices.resize(maxLevel+1, -1); + } + + // map this level to the tile provider index + _providerIndices[maxLevel] = _levelTileProviders.size() - 1; + } + + // Fill in the gaps (value -1) in provider indices, from back to end + for(int i = _providerIndices.size() - 2; i >= 0; --i){ + if(_providerIndices[i] == -1){ + _providerIndices[i] = _providerIndices[i+1]; + } + } +} + +Tile TileProviderByLevel::getTile(const TileIndex& tileIndex) { + return levelProvider(tileIndex.level)->getTile(tileIndex); +} + +Tile TileProviderByLevel::getDefaultTile() { + return levelProvider(0)->getDefaultTile(); +} + +Tile::Status TileProviderByLevel::getTileStatus(const TileIndex& index) { + return levelProvider(index.level)->getTileStatus(index); +} + +TileDepthTransform TileProviderByLevel::depthTransform() { + TileDepthTransform transform; + transform.depthOffset = 0.0f; + transform.depthScale = 1.0f; + return transform; +} + +void TileProviderByLevel::update() { + for(auto provider : _levelTileProviders){ + provider->update(); + } +} + +void TileProviderByLevel::reset() { + for(auto provider : _levelTileProviders){ + provider->reset(); + } +} + +int TileProviderByLevel::maxLevel() { + return _providerIndices.size()-1; +} + +int TileProviderByLevel::providerIndex(int level) const { + int clampedLevel = std::max(0, std::min(level, (int)_providerIndices.size()-1)); + return _providerIndices[clampedLevel]; +} + +TileProvider* TileProviderByLevel::levelProvider(int level) const { + return _levelTileProviders[providerIndex(level)].get(); +} + +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/tile/tileprovider/tileproviderbylevel.h b/modules/globebrowsing/tile/tileprovider/tileproviderbylevel.h new file mode 100644 index 0000000000..3477c92e86 --- /dev/null +++ b/modules/globebrowsing/tile/tileprovider/tileproviderbylevel.h @@ -0,0 +1,57 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___TILE_PROVIDER_BY_LEVEL___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___TILE_PROVIDER_BY_LEVEL___H__ + +#include + +namespace openspace { +namespace globebrowsing { + +class TileProviderByLevel : public TileProvider { +public: + TileProviderByLevel(const ghoul::Dictionary& dictionary); + TileProviderByLevel(const std::string& imagePath); + virtual ~TileProviderByLevel() { } + + virtual Tile getTile(const TileIndex& tileIndex); + virtual Tile getDefaultTile(); + virtual Tile::Status getTileStatus(const TileIndex& index); + virtual TileDepthTransform depthTransform(); + virtual void update(); + virtual void reset(); + virtual int maxLevel(); +private: + inline int providerIndex(int level) const; + inline TileProvider* levelProvider(int level) const; + + std::vector _providerIndices; + std::vector> _levelTileProviders; +}; + +} // namespace globebrowsing +} // namespace openspace + +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___TILE_PROVIDER_BY_LEVEL___H__ diff --git a/modules/globebrowsing/tile/tileprovidermanager.cpp b/modules/globebrowsing/tile/tileprovidermanager.cpp deleted file mode 100644 index c395398074..0000000000 --- a/modules/globebrowsing/tile/tileprovidermanager.cpp +++ /dev/null @@ -1,189 +0,0 @@ -/***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ - -#include - -#include - -#include - -#include "cpl_minixml.h" - - -namespace { - const std::string _loggerCat = "TileProviderManager"; -} - - -namespace openspace { - - - ////////////////////////////////////////////////////////////////////////////////////// - // Tile Provider Group // - ////////////////////////////////////////////////////////////////////////////////////// - - void TileProviderGroup::update() { - for (auto tileProviderWithName : tileProviders) { - if (tileProviderWithName.isActive) { - tileProviderWithName.tileProvider->update(); - } - } - } - - - const std::vector> TileProviderGroup::getActiveTileProviders() const { - std::vector> activeTileProviders; - for (auto tileProviderWithName : tileProviders) { - if (tileProviderWithName.isActive) { - activeTileProviders.push_back(tileProviderWithName.tileProvider); - } - } - return activeTileProviders; - } - - ////////////////////////////////////////////////////////////////////////////////////// - // Tile Provider Manager // - ////////////////////////////////////////////////////////////////////////////////////// - - - TileProviderManager::TileProviderManager( - const ghoul::Dictionary& textureCategoriesDictionary, - const ghoul::Dictionary& textureInitDictionary){ - // Create all the categories of tile providers - for (size_t i = 0; i < textureCategoriesDictionary.size(); i++) { - ghoul::Dictionary texturesDict = textureCategoriesDictionary.value( - LayeredTextures::TEXTURE_CATEGORY_NAMES[i]); - - ghoul_assert(texturesDict.size() <= - LayeredTextures::MAX_NUM_TEXTURES_PER_CATEGORY, - "Too many textures! Number of textures per category must be less than or equal to " - << LayeredTextures::MAX_NUM_TEXTURES_PER_CATEGORY); - - TileProviderInitData initData; - - if (i == LayeredTextures::ColorTextures || - i == LayeredTextures::NightTextures || - i == LayeredTextures::WaterMasks || - i == LayeredTextures::GrayScaleOverlays) { - initData.minimumPixelSize = textureInitDictionary.value("ColorTextureMinimumSize"); - } - else if (i == LayeredTextures::Overlays) { - initData.minimumPixelSize = textureInitDictionary.value("OverlayMinimumSize"); - } - else if (i == LayeredTextures::HeightMaps) { - initData.minimumPixelSize = textureInitDictionary.value("HeightMapMinimumSize"); - } - else { - initData.minimumPixelSize = 512; - } - - initData.threads = 1; - initData.cacheSize = 5000; - initData.framesUntilRequestQueueFlush = 60; - // Only preprocess height maps. - initData.preprocessTiles = i == LayeredTextures::HeightMaps; - - initTexures( - _layerCategories[i].tileProviders, - texturesDict, - initData); - - // init level blending to be true - _layerCategories[i].levelBlendingEnabled = true; - } - } - - TileProviderManager::~TileProviderManager() - { - } - - void TileProviderManager::initTexures(std::vector& dest, - const ghoul::Dictionary& texturesDict, const TileProviderInitData& initData) - { - // Create TileProviders for all textures within this category - for (size_t i = 0; i < texturesDict.size(); i++) { - std::string name, path; - - std::string dictKey = std::to_string(i + 1); - ghoul::Dictionary texDict = texturesDict.value(dictKey); - texDict.getValue("Name", name); - texDict.getValue("FilePath", path); - - std::string type = "LRUCaching"; // if type is unspecified - texDict.getValue("Type", type); - - TileProvider* tileProvider; - auto tileProviderFactory = FactoryManager::ref().factory(); - try { - tileProvider = tileProviderFactory->create(type, texDict); - } - catch (const ghoul::RuntimeError& e) { - LERROR(e.what()); - continue; - } - - // Something else went wrong and no exception was thrown - if (tileProvider == nullptr) { - LERROR("Unable to create TileProvider '" << name << "' of type '" - << type << "'"); - continue; - } - - bool enabled = false; // defaults to false if unspecified - texDict.getValue("Enabled", enabled); - - dest.push_back({ name, std::shared_ptr(tileProvider), enabled }); - } - } - - TileProviderGroup& TileProviderManager::getTileProviderGroup(size_t groupId) { - return _layerCategories[groupId]; - } - - TileProviderGroup& TileProviderManager::getTileProviderGroup(LayeredTextures::TextureCategory category) { - return _layerCategories[category]; - } - - void TileProviderManager::update() { - for (auto tileProviderGroup : _layerCategories) { - tileProviderGroup.update(); - } - } - - void TileProviderManager::reset(bool includingInactive) { - for (auto layerCategory : _layerCategories) { - for (auto tileProviderWithName : layerCategory.tileProviders) { - if (tileProviderWithName.isActive) { - tileProviderWithName.tileProvider->reset(); - } - else if (includingInactive) { - tileProviderWithName.tileProvider->reset(); - } - } - } - } - - - -} // namespace openspace diff --git a/modules/globebrowsing/tile/tileprovidermanager.h b/modules/globebrowsing/tile/tileprovidermanager.h deleted file mode 100644 index f2ee5abcca..0000000000 --- a/modules/globebrowsing/tile/tileprovidermanager.h +++ /dev/null @@ -1,89 +0,0 @@ -/***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ - -#ifndef __TILE_PROVIDER_MANAGER_H__ -#define __TILE_PROVIDER_MANAGER_H__ - - -#include -#include - -#include - -#include -#include -#include - - -namespace openspace { - - - struct NamedTileProvider { - std::string name; - std::shared_ptr tileProvider; - bool isActive; - }; - - - - struct TileProviderGroup { - - void update(); - const std::vector> getActiveTileProviders() const; - - - std::vector tileProviders; - bool levelBlendingEnabled; - - }; - - - - class TileProviderManager { - public: - - TileProviderManager( - const ghoul::Dictionary& textureCategoriesDictionary, - const ghoul::Dictionary& textureInitDictionary); - ~TileProviderManager(); - - - TileProviderGroup& getTileProviderGroup(size_t groupId); - TileProviderGroup& getTileProviderGroup(LayeredTextures::TextureCategory); - - void update(); - void reset(bool includingInactive = false); - - - private: - static void initTexures( - std::vector& destination, - const ghoul::Dictionary& dict, - const TileProviderInitData& initData); - - std::array _layerCategories; - }; - -} // namespace openspace -#endif // __TILE_PROVIDER_MANAGER_H__ \ No newline at end of file diff --git a/modules/globebrowsing/tile/tileselector.cpp b/modules/globebrowsing/tile/tileselector.cpp index fbc9ab7bc3..870c706645 100644 --- a/modules/globebrowsing/tile/tileselector.cpp +++ b/modules/globebrowsing/tile/tileselector.cpp @@ -1,130 +1,84 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ #include +#include #include -#include +namespace openspace { +namespace globebrowsing { -#include -#include +ChunkTile TileSelector::getHighestResolutionTile(const LayerGroup& layerGroup, + TileIndex tileIndex) +{ + ChunkTile mostHighResolution; + mostHighResolution.tile = Tile::TileUnavailable; + mostHighResolution.uvTransform.uvScale.x = 0; -#include "gdal_priv.h" + for (const auto& layer : layerGroup.activeLayers()) { + ChunkTile chunkTile = layer->tileProvider()->getChunkTile(tileIndex); + bool tileIsOk = chunkTile.tile.status == Tile::Status::OK; + bool tileHasMetaData = chunkTile.tile.metaData != nullptr; + bool tileIsHigherResolution = + chunkTile.uvTransform.uvScale.x > mostHighResolution.uvTransform.uvScale.x; + if (tileIsOk && tileHasMetaData && tileIsHigherResolution) { + mostHighResolution = chunkTile; + } + } - - -namespace { - const std::string _loggerCat = "TileSelector"; + return mostHighResolution; } - -namespace openspace { - - const TileSelector::CompareResolution TileSelector::HIGHEST_RES = TileSelector::CompareResolution(); - - TileAndTransform TileSelector::getHighestResolutionTile(TileProvider* tileProvider, ChunkIndex chunkIndex, int parents) { - TileUvTransform uvTransform; - uvTransform.uvOffset = glm::vec2(0, 0); - uvTransform.uvScale = glm::vec2(1, 1); - - // Step 1. Traverse 0 or more parents up the chunkTree as requested by the caller - for (int i = 0; i < parents && chunkIndex.level > 1; i++) { - ascendToParent(chunkIndex, uvTransform); - } - - // Step 2. Traverse 0 or more parents up the chunkTree to make sure we're inside - // the range of defined data. - int maximumLevel = tileProvider->maxLevel(); - while(chunkIndex.level > maximumLevel){ - ascendToParent(chunkIndex, uvTransform); - } - - // Step 3. Traverse 0 or more parents up the chunkTree until we find a chunk that - // has a loaded tile ready to use. - while (chunkIndex.level > 1) { - Tile tile = tileProvider->getTile(chunkIndex); - if (tile.status != Tile::Status::OK) { - ascendToParent(chunkIndex, uvTransform); - } - else return { tile, uvTransform }; - } - - return{ Tile::TileUnavailable, uvTransform }; +std::vector TileSelector::getTilesSortedByHighestResolution( + const LayerGroup& layerGroup, + const TileIndex& tileIndex) +{ + std::vector tiles; + for (const auto& layer : layerGroup.activeLayers()) { + tiles.push_back(layer->tileProvider()->getChunkTile(tileIndex)); } - TileAndTransform TileSelector::getHighestResolutionTile(const TileProviderGroup& tileProviderGroup, ChunkIndex chunkIndex) { - TileAndTransform mostHighResolution; - mostHighResolution.tile = Tile::TileUnavailable; - mostHighResolution.uvTransform.uvScale.x = 0; - - auto activeProviders = tileProviderGroup.getActiveTileProviders(); - for (size_t i = 0; i < activeProviders.size(); i++) { - TileAndTransform tileAndTransform = getHighestResolutionTile(activeProviders[i].get(), chunkIndex); - bool tileIsOk = tileAndTransform.tile.status == Tile::Status::OK; - bool tileHasPreprocessData = tileAndTransform.tile.preprocessData != nullptr; - bool tileIsHigherResolution = tileAndTransform.uvTransform.uvScale.x > mostHighResolution.uvTransform.uvScale.x; - if (tileIsOk && tileHasPreprocessData && tileIsHigherResolution) { - mostHighResolution = tileAndTransform; - } + std::sort( + tiles.begin(), + tiles.end(), + [](const ChunkTile& lhs, const ChunkTile& rhs) { + return lhs.uvTransform.uvScale.x > rhs.uvTransform.uvScale.x; } + ); - return mostHighResolution; - } + return tiles; +} - bool TileSelector::CompareResolution::operator()(const TileAndTransform& a, const TileAndTransform& b) { - // large uv scale means smaller resolution - return a.uvTransform.uvScale.x > b.uvTransform.uvScale.x; - } +void TileSelector::ascendToParent(TileIndex& tileIndex, TileUvTransform& uv) { + uv.uvOffset *= 0.5; + uv.uvScale *= 0.5; - std::vector TileSelector::getTilesSortedByHighestResolution(const TileProviderGroup& tileProviderGroup, const ChunkIndex& chunkIndex) { - auto activeProviders = tileProviderGroup.getActiveTileProviders(); - std::vector tiles; - for (auto provider : activeProviders){ - tiles.push_back(getHighestResolutionTile(provider.get(), chunkIndex)); - } + uv.uvOffset += tileIndex.positionRelativeParent(); + --tileIndex; +} - std::sort(tiles.begin(), tiles.end(), TileSelector::HIGHEST_RES); - - return tiles; - } - - void TileSelector::ascendToParent(ChunkIndex& chunkIndex, TileUvTransform& uv) { - uv.uvOffset *= 0.5; - uv.uvScale *= 0.5; - - if (chunkIndex.isEastChild()) { - uv.uvOffset.x += 0.5; - } - - // In OpenGL, positive y direction is up - if (chunkIndex.isNorthChild()) { - uv.uvOffset.y += 0.5; - } - - --chunkIndex; - } - -} // namespace openspace +} // namespace globebrowsing +} // namespace openspace diff --git a/modules/globebrowsing/tile/tileselector.h b/modules/globebrowsing/tile/tileselector.h index c331d3fe55..3a5b960b36 100644 --- a/modules/globebrowsing/tile/tileselector.h +++ b/modules/globebrowsing/tile/tileselector.h @@ -1,73 +1,52 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __TILE_SELECTOR_H__ -#define __TILE_SELECTOR_H__ +#ifndef __OPENSPACE_MODULE_GLOBEBROWSING___TILE_SELECTOR___H__ +#define __OPENSPACE_MODULE_GLOBEBROWSING___TILE_SELECTOR___H__ - -#include -#include +#include +#include #include - - namespace openspace { - - struct TileUvTransform { - glm::vec2 uvOffset; - glm::vec2 uvScale; - }; - - struct TileAndTransform { - Tile tile; - TileUvTransform uvTransform; - }; - - - class TileSelector { - public: - static TileAndTransform getHighestResolutionTile(TileProvider* tileProvider, ChunkIndex chunkIndex, int parents = 0); - static TileAndTransform getHighestResolutionTile(const TileProviderGroup& tileProviderGroup, ChunkIndex chunkIndex); - static std::vector getTilesSortedByHighestResolution(const TileProviderGroup&, const ChunkIndex& chunkIndex); - - - struct CompareResolution { - bool operator() (const TileAndTransform& a, const TileAndTransform& b); - }; - - static const CompareResolution HIGHEST_RES; - - private: - static void ascendToParent(ChunkIndex& chunkIndex, TileUvTransform& uv); - - }; - +namespace globebrowsing { +struct LayerGroup; +class TileProvider; +class TileSelector { +public: + static ChunkTile getHighestResolutionTile(const LayerGroup& layerGroup, + TileIndex tileIndex); + static std::vector getTilesSortedByHighestResolution( + const LayerGroup& layerGroup, const TileIndex& tileIndex); -} // namespace openspace + static void ascendToParent(TileIndex& tileIndex, TileUvTransform& uv); +}; +} // namespace globebrowsing +} // namespace openspace -#endif // __TILE_SELECTOR_H__ \ No newline at end of file +#endif // __OPENSPACE_MODULE_GLOBEBROWSING___TILE_SELECTOR___H__ diff --git a/modules/iswa/include.cmake b/modules/iswa/include.cmake index 4569df0ac7..8492fd468d 100644 --- a/modules/iswa/include.cmake +++ b/modules/iswa/include.cmake @@ -1,3 +1,5 @@ set (OPENSPACE_DEPENDENCIES - base kameleon + base + kameleon + space ) \ No newline at end of file diff --git a/modules/iswa/iswamodule.cpp b/modules/iswa/iswamodule.cpp index 4a13c225a7..98d0094eef 100644 --- a/modules/iswa/iswamodule.cpp +++ b/modules/iswa/iswamodule.cpp @@ -1,26 +1,26 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ #include @@ -38,22 +38,23 @@ namespace openspace { - IswaModule::IswaModule() - : OpenSpaceModule("ISWA") - {} +IswaModule::IswaModule() + : OpenSpaceModule("ISWA") +{} - void IswaModule::internalInitialize(){ - auto fRenderable = FactoryManager::ref().factory(); - ghoul_assert(fRenderable, "No renderable factory existed"); +void IswaModule::internalInitialize(){ + auto fRenderable = FactoryManager::ref().factory(); + ghoul_assert(fRenderable, "No renderable factory existed"); - fRenderable->registerClass("TexturePlane"); - fRenderable->registerClass("DataPlane"); - fRenderable->registerClass("KameleonPlane"); - fRenderable->registerClass("DataSphere"); + fRenderable->registerClass("TexturePlane"); + fRenderable->registerClass("DataPlane"); + fRenderable->registerClass("KameleonPlane"); + fRenderable->registerClass("DataSphere"); - auto fScreenSpaceRenderable = FactoryManager::ref().factory(); - ghoul_assert(fScreenSpaceRenderable, "No fScreenSpaceRenderable factory existed"); + auto fScreenSpaceRenderable = FactoryManager::ref().factory(); + ghoul_assert(fScreenSpaceRenderable, "No fScreenSpaceRenderable factory existed"); - fScreenSpaceRenderable->registerClass("ScreenSpaceCygnet"); - } -} \ No newline at end of file + fScreenSpaceRenderable->registerClass("ScreenSpaceCygnet"); +} + +} // namespace openspace diff --git a/modules/iswa/iswamodule.h b/modules/iswa/iswamodule.h index 91a213de15..5d1bbb19a9 100644 --- a/modules/iswa/iswamodule.h +++ b/modules/iswa/iswamodule.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,12 +22,12 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ - #ifndef __ISWAMODULE_H__ - #define __ISWAMODULE_H__ + #ifndef __OPENSPACE_MODULE_ISWA___ISWAMODULE___H__ + #define __OPENSPACE_MODULE_ISWA___ISWAMODULE___H__ #include - namespace openspace{ + namespace openspace { class IswaModule : public OpenSpaceModule { public: @@ -39,4 +39,4 @@ protected: } // namespace openspace -#endif // __ISWAMODULE_H__ \ No newline at end of file +#endif // __OPENSPACE_MODULE_ISWA___ISWAMODULE___H__ diff --git a/modules/iswa/rendering/datacygnet.h b/modules/iswa/rendering/datacygnet.h index 48265635dc..2fd73b17e1 100644 --- a/modules/iswa/rendering/datacygnet.h +++ b/modules/iswa/rendering/datacygnet.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __DATACYGNET_H__ -#define __DATACYGNET_H__ +#ifndef __OPENSPACE_MODULE_ISWA___DATACYGNET___H__ +#define __OPENSPACE_MODULE_ISWA___DATACYGNET___H__ #include #include @@ -32,7 +32,7 @@ namespace { const int MAX_TEXTURES = 6; } -namespace openspace{ +namespace openspace { /** * This class abstracts away the the loading of data and creation of @@ -108,8 +108,9 @@ protected: private: bool readyToRender() const override; - bool downloadTextureResource(double timestamp = Time::ref().currentTime()) override; + bool downloadTextureResource(double timestamp = Time::ref().j2000Seconds()) override; }; + } //namespace openspace -#endif //__DATACYGNET_H__ \ No newline at end of file +#endif //__OPENSPACE_MODULE_ISWA___DATACYGNET___H__ diff --git a/modules/iswa/rendering/dataplane.cpp b/modules/iswa/rendering/dataplane.cpp index 2ac68f7b7e..c53bdc6381 100644 --- a/modules/iswa/rendering/dataplane.cpp +++ b/modules/iswa/rendering/dataplane.cpp @@ -21,6 +21,7 @@ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ + #include #include @@ -55,10 +56,12 @@ bool DataPlane::initialize(){ // and unregister backgroundvalues property. if(_autoFilter.value()){ _backgroundValues.setValue(_dataProcessor->filterValues()); - _backgroundValues.setVisible(false); + _backgroundValues.setVisibility(properties::Property::Visibility::None); + //_backgroundValues.setVisible(false); // else if autofilter is turned off, register backgroundValues } else { - _backgroundValues.setVisible(true); + _backgroundValues.setVisibility(properties::Property::Visibility::All); + //_backgroundValues.setVisible(true); } }); } diff --git a/modules/iswa/rendering/dataplane.h b/modules/iswa/rendering/dataplane.h index 2efa100e6f..fcd609c6dd 100644 --- a/modules/iswa/rendering/dataplane.h +++ b/modules/iswa/rendering/dataplane.h @@ -1,33 +1,34 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __DATAPLANE_H__ -#define __DATAPLANE_H__ +#ifndef __OPENSPACE_MODULE_ISWA___DATAPLANE___H__ +#define __OPENSPACE_MODULE_ISWA___DATAPLANE___H__ #include -namespace openspace{ +namespace openspace { + /** * DataPlane is a concrete IswaCygnet with data files as its input source. * The class handles creation, destruction and rendering of a plane geometry. @@ -58,4 +59,4 @@ private: } // namespace openspace -#endif //__DATAPLANE_H__ \ No newline at end of file +#endif //__OPENSPACE_MODULE_ISWA___DATAPLANE___H__ diff --git a/modules/iswa/rendering/datasphere.cpp b/modules/iswa/rendering/datasphere.cpp index 9e3da7d657..fde4d90932 100644 --- a/modules/iswa/rendering/datasphere.cpp +++ b/modules/iswa/rendering/datasphere.cpp @@ -1,26 +1,26 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ #include #include @@ -38,8 +38,8 @@ namespace { namespace openspace { DataSphere::DataSphere(const ghoul::Dictionary& dictionary) - :DataCygnet(dictionary) - ,_sphere(nullptr) + : DataCygnet(dictionary) + , _sphere(nullptr) { float radius; dictionary.getValue("Radius", radius); @@ -69,10 +69,12 @@ bool DataSphere::initialize(){ // and unregister backgroundvalues property. if(_autoFilter.value()){ _backgroundValues.setValue(_dataProcessor->filterValues()); - _backgroundValues.setVisible(false); + _backgroundValues.setVisibility(properties::Property::Visibility::None); + //_backgroundValues.setVisible(false); // else if autofilter is turned off, register backgroundValues } else { - _backgroundValues.setVisible(true); + _backgroundValues.setVisibility(properties::Property::Visibility::All); + //_backgroundValues.setVisible(true); } }); } diff --git a/modules/iswa/rendering/datasphere.h b/modules/iswa/rendering/datasphere.h index 47206615a1..c50ea616d8 100644 --- a/modules/iswa/rendering/datasphere.h +++ b/modules/iswa/rendering/datasphere.h @@ -1,33 +1,33 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2015 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __DATASPHERE_H__ -#define __DATASPHERE_H__ +#ifndef __OPENSPACE_MODULE_ISWA___DATASPHERE___H__ +#define __OPENSPACE_MODULE_ISWA___DATASPHERE___H__ #include -namespace openspace{ +namespace openspace { class PowerScaledSphere; /** @@ -41,8 +41,8 @@ public: ~DataSphere(); bool initialize() override; -protected: +protected: /** * Creates a sphere geometry */ @@ -56,7 +56,6 @@ protected: float _radius; }; +} // namespace openspace -} //namespace openspace - -#endif //__DATASPHERE_H__ +#endif //__OPENSPACE_MODULE_ISWA___DATASPHERE___H__ diff --git a/modules/iswa/rendering/iswabasegroup.cpp b/modules/iswa/rendering/iswabasegroup.cpp index 2e3e56cc83..6050cd7e87 100644 --- a/modules/iswa/rendering/iswabasegroup.cpp +++ b/modules/iswa/rendering/iswabasegroup.cpp @@ -1,27 +1,28 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2015 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ -#include + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include #include #include diff --git a/modules/iswa/rendering/iswabasegroup.h b/modules/iswa/rendering/iswabasegroup.h index 5df21788db..0a97234dff 100644 --- a/modules/iswa/rendering/iswabasegroup.h +++ b/modules/iswa/rendering/iswabasegroup.h @@ -1,34 +1,35 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2015 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __ISWAGROUP_H__ -#define __ISWAGROUP_H__ +#ifndef __OPENSPACE_MODULE_ISWA___ISWABASEGROUP___H__ +#define __OPENSPACE_MODULE_ISWA___ISWABASEGROUP___H__ #include #include #include #include +#include #include #include // #include @@ -37,7 +38,7 @@ #include -namespace openspace{ +namespace openspace { class IswaCygnet; class IswaBaseGroup : public properties::PropertyOwner{ @@ -68,4 +69,5 @@ protected: }; } //namespace openspace -#endif \ No newline at end of file + +#endif // __OPENSPACE_MODULE_ISWA___ISWABASEGROUP___H__ diff --git a/modules/iswa/rendering/iswacygnet.cpp b/modules/iswa/rendering/iswacygnet.cpp index ee964d75e7..3f2e844672 100644 --- a/modules/iswa/rendering/iswacygnet.cpp +++ b/modules/iswa/rendering/iswacygnet.cpp @@ -1,26 +1,27 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2015 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + #include #include #include @@ -32,7 +33,7 @@ namespace { const std::string _loggerCat = "IswaCygnet"; } -namespace openspace{ +namespace openspace { IswaCygnet::IswaCygnet(const ghoul::Dictionary& dictionary) : Renderable(dictionary) @@ -107,7 +108,10 @@ bool IswaCygnet::initialize(){ }else{ _delete.onChange([this](){ deinitialize(); - OsEng.scriptEngine().queueScript("openspace.removeSceneGraphNode('" + name() + "')"); + OsEng.scriptEngine().queueScript( + "openspace.removeSceneGraphNode('" + name() + "')", + scripting::ScriptEngine::RemoteScripting::Yes + ); }); } @@ -178,7 +182,7 @@ void IswaCygnet::update(const UpdateData& data){ // the texture resource is downloaded ahead of time, so we need to // now if we are going backwards or forwards double clockwiseSign = (Time::ref().deltaTime()>0) ? 1.0 : -1.0; - _openSpaceTime = Time::ref().currentTime(); + _openSpaceTime = Time::ref().j2000Seconds(); _realTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()); _stateMatrix = TransformationManager::ref().frameTransformationMatrix(_data->frame, "GALACTIC", _openSpaceTime); @@ -222,7 +226,7 @@ void IswaCygnet::unregisterProperties(){ } void IswaCygnet::initializeTime(){ - _openSpaceTime = Time::ref().currentTime(); + _openSpaceTime = Time::ref().j2000Seconds(); _lastUpdateOpenSpaceTime = 0.0; _realTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()); @@ -260,8 +264,11 @@ void IswaCygnet::initializeGroup(){ groupEvent->subscribe(name(), "clearGroup", [&](ghoul::Dictionary dict){ LDEBUG(name() + " Event clearGroup"); - OsEng.scriptEngine().queueScript("openspace.removeSceneGraphNode('" + name() + "')"); + OsEng.scriptEngine().queueScript( + "openspace.removeSceneGraphNode('" + name() + "')", + scripting::ScriptEngine::RemoteScripting::Yes + ); }); } -}//namespace openspac \ No newline at end of file +} //namespace openspace diff --git a/modules/iswa/rendering/iswacygnet.h b/modules/iswa/rendering/iswacygnet.h index 5f140af97f..11172e28bd 100644 --- a/modules/iswa/rendering/iswacygnet.h +++ b/modules/iswa/rendering/iswacygnet.h @@ -1,29 +1,29 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2015 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __ISWACYGNET_H__ -#define __ISWACYGNET_H__ +#ifndef __OPENSPACE_MODULE_ISWA___ISWACYGNET___H__ +#define __OPENSPACE_MODULE_ISWA___ISWACYGNET___H__ #include #include @@ -40,7 +40,7 @@ #include #include -namespace openspace{ +namespace openspace { class IswaBaseGroup; struct Metadata { @@ -156,5 +156,6 @@ private: }; -}//namespace openspace -#endif \ No newline at end of file +} //namespace openspace + +#endif // __OPENSPACE_MODULE_ISWA___ISWACYGNET___H__ diff --git a/modules/iswa/rendering/iswadatagroup.cpp b/modules/iswa/rendering/iswadatagroup.cpp index 6fbff8e972..eaa26b2362 100644 --- a/modules/iswa/rendering/iswadatagroup.cpp +++ b/modules/iswa/rendering/iswadatagroup.cpp @@ -1,26 +1,27 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2015 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + #include #include @@ -41,15 +42,14 @@ namespace { namespace openspace{ IswaDataGroup::IswaDataGroup(std::string name, std::string type) - :IswaBaseGroup(name, type) - ,_useLog("useLog","Use Logarithm", false) - - ,_useHistogram("useHistogram", "Auto Contrast", false) - ,_autoFilter("autoFilter", "Auto Filter", true) - ,_normValues("normValues", "Normalize Values", glm::vec2(1.0,1.0), glm::vec2(0), glm::vec2(5.0)) - ,_backgroundValues("backgroundValues", "Background Values", glm::vec2(0.0), glm::vec2(0), glm::vec2(1.0)) - ,_transferFunctionsFile("transferfunctions", "Transfer Functions", "${SCENE}/iswa/tfs/default.tf") - ,_dataOptions("dataOptions", "Data Options") + : IswaBaseGroup(name, type) + , _useLog("useLog","Use Logarithm", false) + , _useHistogram("useHistogram", "Auto Contrast", false) + , _autoFilter("autoFilter", "Auto Filter", true) + , _normValues("normValues", "Normalize Values", glm::vec2(1.0,1.0), glm::vec2(0), glm::vec2(5.0)) + , _backgroundValues("backgroundValues", "Background Values", glm::vec2(0.0), glm::vec2(0), glm::vec2(1.0)) + , _transferFunctionsFile("transferfunctions", "Transfer Functions", "${SCENE}/iswa/tfs/default.tf") + , _dataOptions("dataOptions", "Data Options") { addProperty(_useLog); addProperty(_useHistogram); @@ -94,10 +94,12 @@ void IswaDataGroup::registerProperties(){ // and unregister backgroundvalues property. if(_autoFilter.value()){ _backgroundValues.setValue(_dataProcessor->filterValues()); - _backgroundValues.setVisible(false); + _backgroundValues.setVisibility(properties::Property::Visibility::None); + //_backgroundValues.setVisible(false); // else if autofilter is turned off, register backgroundValues } else { - _backgroundValues.setVisible(true); + _backgroundValues.setVisibility(properties::Property::Visibility::All); + //_backgroundValues.setVisible(true); } _groupEvent->publish("autoFilterChanged", ghoul::Dictionary({{"autoFilter", _autoFilter.value()}})); }); diff --git a/modules/iswa/rendering/iswadatagroup.h b/modules/iswa/rendering/iswadatagroup.h index d08b16506a..07f37e05ec 100644 --- a/modules/iswa/rendering/iswadatagroup.h +++ b/modules/iswa/rendering/iswadatagroup.h @@ -1,32 +1,37 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2015 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ -#ifndef __ISWADATAGROUP_H__ -#define __ISWADATAGROUP_H__ -#include + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -namespace openspace{ -class IswaDataGroup : public IswaBaseGroup{ +#ifndef __OPENSPACE_MODULE_ISWA___ISWADATAGROUP___H__ +#define __OPENSPACE_MODULE_ISWA___ISWADATAGROUP___H__ + +#include + +#include + +namespace openspace { + +class IswaDataGroup : public IswaBaseGroup { public: IswaDataGroup(std::string name, std::string type); ~IswaDataGroup(); @@ -53,4 +58,5 @@ protected: }; } //namespace openspace -#endif // __ISWADATAGROUP_H__ \ No newline at end of file + +#endif // __OPENSPACE_MODULE_ISWA___ISWADATAGROUP___H__ diff --git a/modules/iswa/rendering/iswagroup.cpp b/modules/iswa/rendering/iswagroup.cpp deleted file mode 100644 index 44fe7c20a9..0000000000 --- a/modules/iswa/rendering/iswagroup.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2015 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ -#include - -#include -#include - -#include -#include -#include - -#include -#include -#include - - -namespace { - const std::string _loggerCat = "IswaBaseGroup"; - using json = nlohmann::json; -} - -namespace openspace { -IswaBaseGroup::IswaBaseGroup(std::string name, std::string type) - :_enabled("enabled", "Enabled", true) - ,_alpha("alpha", "Alpha", 0.9f, 0.0f, 1.0f) - ,_delete("delete", "Delete") - ,_registered(false) - ,_type(type) - ,_dataProcessor(nullptr) -{ - setName(name); - - addProperty(_enabled); - addProperty(_alpha); - addProperty(_delete); - - _groupEvent = std::make_shared >(); - registerProperties(); - - _autoFilter.setValue(true); -} - -IswaBaseGroup::~IswaBaseGroup(){} - -bool IswaBaseGroup::isType(std::string type){ - return (_type == type); -} - -void IswaBaseGroup::updateGroup(){ - _groupEvent->publish("updateGroup", ghoul::Dictionary()); -} - -void IswaBaseGroup::clearGroup(){ - _groupEvent->publish("clearGroup", ghoul::Dictionary()); - LDEBUG("Group " + name() + " published clearGroup"); - unregisterProperties(); -} - -std::shared_ptr IswaBaseGroup::dataProcessor(){ - return _dataProcessor; -} - -std::shared_ptr > IswaBaseGroup::groupEvent(){ - return _groupEvent; -}; - - -void IswaBaseGroup::registerProperties(){ - OsEng.gui()._iswa.registerProperty(&_enabled); - OsEng.gui()._iswa.registerProperty(&_alpha); - - _enabled.onChange([this]{ - LDEBUG("Group " + name() + " published enabledChanged"); - _groupEvent->publish("enabledChanged", ghoul::Dictionary({{"enabled", _enabled.value()}})); - }); - - _alpha.onChange([this]{ - LDEBUG("Group " + name() + " published alphaChanged"); - _groupEvent->publish("alphaChanged", ghoul::Dictionary({{"alpha", _alpha.value()}})); - }); - - OsEng.gui()._iswa.registerProperty(&_delete); - _delete.onChange([this]{ - clearGroup(); - }); - - _registered = true; -} - -void IswaBaseGroup::unregisterProperties(){ - OsEng.gui()._iswa.unregisterProperties(name()); - _registered = false; -} - -} //namespace openspace \ No newline at end of file diff --git a/modules/iswa/rendering/iswagroup.h b/modules/iswa/rendering/iswagroup.h deleted file mode 100644 index 5df21788db..0000000000 --- a/modules/iswa/rendering/iswagroup.h +++ /dev/null @@ -1,71 +0,0 @@ -/***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2015 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ - -#ifndef __ISWAGROUP_H__ -#define __ISWAGROUP_H__ - -#include -#include -#include -#include -#include -#include -// #include -#include -#include -#include - - -namespace openspace{ -class IswaCygnet; - -class IswaBaseGroup : public properties::PropertyOwner{ -public: - IswaBaseGroup(std::string name, std::string type); - ~IswaBaseGroup(); - bool isType(std::string type); - - void updateGroup(); - virtual void clearGroup(); - - std::shared_ptr dataProcessor(); - std::shared_ptr > groupEvent(); - -protected: - void registerProperties(); - void unregisterProperties(); - - properties::BoolProperty _enabled; - properties::FloatProperty _alpha; - properties::TriggerProperty _delete; - - std::shared_ptr > _groupEvent; - std::shared_ptr _dataProcessor; - - bool _registered; - std::string _type; -}; - -} //namespace openspace -#endif \ No newline at end of file diff --git a/modules/iswa/rendering/iswakameleongroup.cpp b/modules/iswa/rendering/iswakameleongroup.cpp index 4273f8330e..9f57bbb6ab 100644 --- a/modules/iswa/rendering/iswakameleongroup.cpp +++ b/modules/iswa/rendering/iswakameleongroup.cpp @@ -1,26 +1,27 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2015 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + #include #include @@ -130,7 +131,10 @@ void IswaKameleonGroup::updateFieldlineSeeds(){ // if this option was turned off if( std::find(selectedOptions.begin(), selectedOptions.end(), seedPath.first)==selectedOptions.end() && std::get<2>(seedPath.second)){ LDEBUG("Removed fieldlines: " + std::get<0>(seedPath.second)); - OsEng.scriptEngine().queueScript("openspace.removeSceneGraphNode('" + std::get<0>(seedPath.second) + "')"); + OsEng.scriptEngine().queueScript( + "openspace.removeSceneGraphNode('" + std::get<0>(seedPath.second) + "')", + scripting::ScriptEngine::RemoteScripting::Yes + ); std::get<2>(seedPath.second) = false; // if this option was turned on } else if( std::find(selectedOptions.begin(), selectedOptions.end(), seedPath.first)!=selectedOptions.end() && !std::get<2>(seedPath.second)) { @@ -146,7 +150,10 @@ void IswaKameleonGroup::clearFieldlines(){ for (auto& seedPath: _fieldlineState) { if(std::get<2>(seedPath.second)){ LDEBUG("Removed fieldlines: " + std::get<0>(seedPath.second)); - OsEng.scriptEngine().queueScript("openspace.removeSceneGraphNode('" + std::get<0>(seedPath.second) + "')"); + OsEng.scriptEngine().queueScript( + "openspace.removeSceneGraphNode('" + std::get<0>(seedPath.second) + "')", + scripting::ScriptEngine::RemoteScripting::Yes + ); std::get<2>(seedPath.second) = false; } } @@ -160,4 +167,4 @@ void IswaKameleonGroup::changeCdf(std::string path){ _groupEvent->publish("cdfChanged", ghoul::Dictionary({{"path", path}})); } -}//namespace openspace \ No newline at end of file +} //namespace openspace diff --git a/modules/iswa/rendering/iswakameleongroup.h b/modules/iswa/rendering/iswakameleongroup.h index ce5a7cd9c2..26e7c921b1 100644 --- a/modules/iswa/rendering/iswakameleongroup.h +++ b/modules/iswa/rendering/iswakameleongroup.h @@ -1,31 +1,33 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2015 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ -#ifndef __ISWAKAMELEONGROUP_H__ -#define __ISWAKAMELEONGROUP_H__ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_ISWA___ISWAKAMELEONGROUP___H__ +#define __OPENSPACE_MODULE_ISWA___ISWAKAMELEONGROUP___H__ + #include -namespace openspace{ +namespace openspace { class IswaKameleonGroup : public IswaDataGroup{ public: IswaKameleonGroup(std::string name, std::string type); @@ -52,5 +54,6 @@ protected: std::map > _fieldlineState; }; -}//namespace openspace -#endif \ No newline at end of file +} //namespace openspace + +#endif // __OPENSPACE_MODULE_ISWA___ISWAKAMELEONGROUP___H__ diff --git a/modules/iswa/rendering/kameleonplane.cpp b/modules/iswa/rendering/kameleonplane.cpp index 9a5dab1125..55fce2c729 100644 --- a/modules/iswa/rendering/kameleonplane.cpp +++ b/modules/iswa/rendering/kameleonplane.cpp @@ -107,10 +107,12 @@ bool KameleonPlane::initialize(){ // and unregister backgroundvalues property. if(_autoFilter.value()){ _backgroundValues.setValue(_dataProcessor->filterValues()); - _backgroundValues.setVisible(false); + _backgroundValues.setVisibility(properties::Property::Visibility::None); + //_backgroundValues.setVisible(false); // else if autofilter is turned off, register backgroundValues } else { - _backgroundValues.setVisible(true); + _backgroundValues.setVisibility(properties::Property::Visibility::All); + //_backgroundValues.setVisible(true); } }); } @@ -232,7 +234,10 @@ void KameleonPlane::updateFieldlineSeeds(){ if(OsEng.renderEngine().scene()->sceneGraphNode(std::get<0>(seedPath.second)) == nullptr) return; LDEBUG("Removed fieldlines: " + std::get<0>(seedPath.second)); - OsEng.scriptEngine().queueScript("openspace.removeSceneGraphNode('" + std::get<0>(seedPath.second) + "')"); + OsEng.scriptEngine().queueScript( + "openspace.removeSceneGraphNode('" + std::get<0>(seedPath.second) + "')", + scripting::ScriptEngine::RemoteScripting::Yes + ); std::get<2>(seedPath.second) = false; // if this option was turned on } else if( std::find(selectedOptions.begin(), selectedOptions.end(), seedPath.first)!=selectedOptions.end() && !std::get<2>(seedPath.second)) { diff --git a/modules/iswa/rendering/kameleonplane.h b/modules/iswa/rendering/kameleonplane.h index 9b1ab3a933..702a7f5aa7 100644 --- a/modules/iswa/rendering/kameleonplane.h +++ b/modules/iswa/rendering/kameleonplane.h @@ -1,34 +1,34 @@ -/**************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __KAMELEONPLANE_H__ -#define __KAMELEONPLANE_H__ +#ifndef __OPENSPACE_MODULE_ISWA___KAMELEONPLANE___H__ +#define __OPENSPACE_MODULE_ISWA___KAMELEONPLANE___H__ #include #include -namespace openspace{ +namespace openspace { /** * KameleonPlane is a concrete IswaCygnet with volume data files from @@ -106,4 +106,4 @@ private: } // namespace openspace -#endif //__KAMELEONPLANE_H__ \ No newline at end of file +#endif //__OPENSPACE_MODULE_ISWA___KAMELEONPLANE___H__ diff --git a/modules/iswa/rendering/screenspacecygnet.cpp b/modules/iswa/rendering/screenspacecygnet.cpp index 7b493ea866..32c2c340a0 100644 --- a/modules/iswa/rendering/screenspacecygnet.cpp +++ b/modules/iswa/rendering/screenspacecygnet.cpp @@ -50,7 +50,7 @@ ScreenSpaceCygnet::ScreenSpaceCygnet(const ghoul::Dictionary& dictionary) _downloadImage = true; _url = IswaManager::ref().iswaUrl(_cygnetId); - _openSpaceTime = Time::ref().currentTime(); + _openSpaceTime = Time::ref().j2000Seconds(); _lastUpdateOpenSpaceTime = _openSpaceTime; _realTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()); @@ -59,7 +59,8 @@ ScreenSpaceCygnet::ScreenSpaceCygnet(const ghoul::Dictionary& dictionary) _delete.onChange([this](){ OsEng.scriptEngine().queueScript( - "openspace.iswa.removeScreenSpaceCygnet("+std::to_string(_cygnetId)+");" + "openspace.iswa.removeScreenSpaceCygnet("+std::to_string(_cygnetId)+");", + scripting::ScriptEngine::RemoteScripting::Yes ); }); // IswaManager::ref().deleteIswaCygnet(name());}); @@ -69,7 +70,7 @@ ScreenSpaceCygnet::ScreenSpaceCygnet(const ghoul::Dictionary& dictionary) ScreenSpaceCygnet::~ScreenSpaceCygnet(){} void ScreenSpaceCygnet::update(){ - _openSpaceTime = Time::ref().currentTime(); + _openSpaceTime = Time::ref().j2000Seconds(); _realTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()); bool timeToUpdate = (fabs(_openSpaceTime-_lastUpdateOpenSpaceTime) >= _updateTime && diff --git a/modules/iswa/rendering/screenspacecygnet.h b/modules/iswa/rendering/screenspacecygnet.h index bdf021da34..a34e51dd50 100644 --- a/modules/iswa/rendering/screenspacecygnet.h +++ b/modules/iswa/rendering/screenspacecygnet.h @@ -1,29 +1,29 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2015 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __SCREENSPACECYGNET_H__ -#define __SCREENSPACECYGNET_H__ +#ifndef __OPENSPACE_MODULE_ISWA___SCREENSPACECYGNET___H__ +#define __OPENSPACE_MODULE_ISWA___SCREENSPACECYGNET___H__ #include #include @@ -54,6 +54,6 @@ private: int _minRealTimeUpdateInterval; }; - } // namespace openspace +} // namespace openspace -#endif //__SCREENSPACECYGNET_H__ \ No newline at end of file +#endif //__OPENSPACE_MODULE_ISWA___SCREENSPACECYGNET___H__ diff --git a/modules/iswa/rendering/texturecygnet.h b/modules/iswa/rendering/texturecygnet.h index 1beef542c2..c432ae3abb 100644 --- a/modules/iswa/rendering/texturecygnet.h +++ b/modules/iswa/rendering/texturecygnet.h @@ -22,12 +22,12 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __TEXTURECYGNET_H__ -#define __TEXTURECYGNET_H__ +#ifndef __OPENSPACE_MODULE_ISWA___TEXTURECYGNET___H__ +#define __OPENSPACE_MODULE_ISWA___TEXTURECYGNET___H__ #include -namespace openspace{ +namespace openspace { /** * This class exist to abstract away the loading of images @@ -43,7 +43,7 @@ public: protected: bool updateTexture() override; - bool downloadTextureResource(double timestamp = Time::ref().currentTime()) override; + bool downloadTextureResource(double timestamp = Time::ref().j2000Seconds()) override; bool readyToRender() const override; bool updateTextureResource() override; @@ -58,4 +58,4 @@ private: }; } //namespace openspace -#endif //__TEXTURECYGNET_H__ \ No newline at end of file +#endif //__OPENSPACE_MODULE_ISWA___TEXTURECYGNET___H__ diff --git a/modules/iswa/rendering/textureplane.cpp b/modules/iswa/rendering/textureplane.cpp index 2f032f1062..5704a1bae5 100644 --- a/modules/iswa/rendering/textureplane.cpp +++ b/modules/iswa/rendering/textureplane.cpp @@ -34,9 +34,9 @@ namespace { namespace openspace { TexturePlane::TexturePlane(const ghoul::Dictionary& dictionary) - :TextureCygnet(dictionary) - ,_quad(0) - ,_vertexPositionBuffer(0) + : TextureCygnet(dictionary) + , _quad(0) + , _vertexPositionBuffer(0) { _programName = "PlaneProgram"; _vsPath = "${MODULE_ISWA}/shaders/textureplane_vs.glsl"; @@ -104,4 +104,4 @@ void TexturePlane::renderGeometry() const { glDrawArrays(GL_TRIANGLES, 0, 6); } -}// namespace openspace \ No newline at end of file +} // namespace openspace diff --git a/modules/iswa/rendering/textureplane.h b/modules/iswa/rendering/textureplane.h index 4803ec0176..3f812e1847 100644 --- a/modules/iswa/rendering/textureplane.h +++ b/modules/iswa/rendering/textureplane.h @@ -1,33 +1,33 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __TEXTUREPLANE_H__ -#define __TEXTUREPLANE_H__ +#ifndef __OPENSPACE_MODULE_ISWA___TEXTUREPLANE___H__ +#define __OPENSPACE_MODULE_ISWA___TEXTUREPLANE___H__ #include -namespace openspace{ +namespace openspace { /** * TexturePlane is a "concrete" IswaCygnet with texture as its input source. @@ -51,4 +51,4 @@ private: } // namespace openspace -#endif \ No newline at end of file +#endif // __OPENSPACE_MODULE_ISWA___TEXTUREPLANE___H__ diff --git a/modules/iswa/util/dataprocessor.cpp b/modules/iswa/util/dataprocessor.cpp index 3639899a94..b61fa59315 100644 --- a/modules/iswa/util/dataprocessor.cpp +++ b/modules/iswa/util/dataprocessor.cpp @@ -1,26 +1,27 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2015 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + #include #include @@ -31,6 +32,7 @@ namespace { } namespace openspace { + DataProcessor::DataProcessor() :_useLog(false) ,_useHistogram(false) diff --git a/modules/iswa/util/dataprocessor.h b/modules/iswa/util/dataprocessor.h index 767c75d80b..8a84fcd8f3 100644 --- a/modules/iswa/util/dataprocessor.h +++ b/modules/iswa/util/dataprocessor.h @@ -1,29 +1,29 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2015 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __DATAPROCESSOR_H__ -#define __DATAPROCESSOR_H__ +#ifndef __OPENSPACE_MODULE_ISWA___DATAPROCESSOR___H__ +#define __OPENSPACE_MODULE_ISWA___DATAPROCESSOR___H__ #include #include @@ -31,7 +31,8 @@ #include #include -namespace openspace{ +namespace openspace { + class DataProcessor{ friend class IswaBaseGroup; public: @@ -77,4 +78,4 @@ protected: } // namespace openspace -#endif //__DATAPROCESSOR_H__ +#endif //__OPENSPACE_MODULE_ISWA___DATAPROCESSOR___H__ diff --git a/modules/iswa/util/dataprocessorjson.cpp b/modules/iswa/util/dataprocessorjson.cpp index 151f8e6a13..b966fefe09 100644 --- a/modules/iswa/util/dataprocessorjson.cpp +++ b/modules/iswa/util/dataprocessorjson.cpp @@ -1,27 +1,29 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2015 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + #include + #include #include #include @@ -31,13 +33,13 @@ namespace { using json = nlohmann::json; } -namespace openspace{ +namespace openspace { DataProcessorJson::DataProcessorJson() - :DataProcessor() + : DataProcessor() {} -DataProcessorJson::~DataProcessorJson(){} +DataProcessorJson::~DataProcessorJson() {} std::vector DataProcessorJson::readMetadata(std::string data, glm::size3_t& dimensions){ std::vector options = std::vector(); @@ -139,4 +141,4 @@ std::vector DataProcessorJson::processData(std::string data, properties: return std::vector(); } -}//namespace openspace +} //namespace openspace diff --git a/modules/iswa/util/dataprocessorjson.h b/modules/iswa/util/dataprocessorjson.h index 2516bea159..98f29aae4c 100644 --- a/modules/iswa/util/dataprocessorjson.h +++ b/modules/iswa/util/dataprocessorjson.h @@ -1,30 +1,31 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2015 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ -#include + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __DATAPROCESSORJSON_H__ -#define __DATAPROCESSORJSON_H__ +#ifndef __OPENSPACE_MODULE_ISWA___DATAPROCESSORJSON___H__ +#define __OPENSPACE_MODULE_ISWA___DATAPROCESSORJSON___H__ + +#include namespace openspace { @@ -38,5 +39,6 @@ public: virtual std::vector processData(std::string data, properties::SelectionProperty& dataOptions, glm::size3_t& dimensions) override; }; -}// namespace -#endif __DATAPROCESSORJSON_H__ \ No newline at end of file +}// namespace openspace + +#endif __OPENSPACE_MODULE_ISWA___DATAPROCESSORJSON___H__ diff --git a/modules/iswa/util/dataprocessorkameleon.cpp b/modules/iswa/util/dataprocessorkameleon.cpp index 5abba4833b..b1078cab58 100644 --- a/modules/iswa/util/dataprocessorkameleon.cpp +++ b/modules/iswa/util/dataprocessorkameleon.cpp @@ -1,26 +1,27 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2015 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + #include //#include #include @@ -29,19 +30,18 @@ namespace { const std::string _loggerCat = "DataProcessorKameleon"; } -namespace openspace{ +namespace openspace { DataProcessorKameleon::DataProcessorKameleon() - :DataProcessor() - ,_kwPath("") - ,_kw(nullptr) - ,_initialized(false) - ,_slice(0.5) + : DataProcessor() + , _kwPath("") + , _kw(nullptr) + , _initialized(false) + , _slice(0.5) {} DataProcessorKameleon::~DataProcessorKameleon(){} - std::vector DataProcessorKameleon::readMetadata(std::string path, glm::size3_t& dimensions){ if(!path.empty()){ @@ -147,4 +147,4 @@ void DataProcessorKameleon::initializeKameleonWrapper(std::string path){ } } -}//namespace openspace \ No newline at end of file +} //namespace openspace diff --git a/modules/iswa/util/dataprocessorkameleon.h b/modules/iswa/util/dataprocessorkameleon.h index 482242f7e2..aa29aa0dc9 100644 --- a/modules/iswa/util/dataprocessorkameleon.h +++ b/modules/iswa/util/dataprocessorkameleon.h @@ -1,32 +1,33 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2015 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_ISWA___DATAPROCESSORKAMELEON___H__ +#define __OPENSPACE_MODULE_ISWA___DATAPROCESSORKAMELEON___H__ + #include #include -#ifndef __DATAPROCESSORKAMELEON_H__ -#define __DATAPROCESSORKAMELEON_H__ - namespace openspace { class DataProcessorKameleon : public DataProcessor { @@ -51,5 +52,6 @@ private: // std::vector _data; }; -}// namespace -#endif __DATAPROCESSORKAMELEON_H__ \ No newline at end of file +} // namespace openspace + +#endif __OPENSPACE_MODULE_ISWA___DATAPROCESSORKAMELEON___H__ diff --git a/modules/iswa/util/dataprocessortext.cpp b/modules/iswa/util/dataprocessortext.cpp index ecdb1ac4d0..8e8e724844 100644 --- a/modules/iswa/util/dataprocessortext.cpp +++ b/modules/iswa/util/dataprocessortext.cpp @@ -1,26 +1,27 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + #include //#include //#include @@ -38,7 +39,7 @@ namespace { namespace openspace{ DataProcessorText::DataProcessorText() - :DataProcessor() + : DataProcessor() {} DataProcessorText::~DataProcessorText(){} @@ -224,4 +225,4 @@ std::vector DataProcessorText::processData(std::string data, properties: return std::vector(); } -}//namespace openspace \ No newline at end of file +} //namespace openspace diff --git a/modules/iswa/util/dataprocessortext.h b/modules/iswa/util/dataprocessortext.h index b3fb53323c..d4648d5018 100644 --- a/modules/iswa/util/dataprocessortext.h +++ b/modules/iswa/util/dataprocessortext.h @@ -1,30 +1,31 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2015 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ -#include + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __DATAPROCESSORTEXT_H__ -#define __DATAPROCESSORTEXT_H__ +#ifndef __OPENSPACE_MODULE_ISWA___DATAPROCESSORTEXT___H__ +#define __OPENSPACE_MODULE_ISWA___DATAPROCESSORTEXT___H__ + +#include namespace openspace { @@ -43,5 +44,6 @@ private: // void calculateFilterValues(std::vector selectedOptions); }; -}// namespace -#endif __DATAPROCESSORTEXT_H__ +} // namespace openspace + +#endif __OPENSPACE_MODULE_ISWA___DATAPROCESSORTEXT___H__ diff --git a/modules/iswa/util/iswamanager.cpp b/modules/iswa/util/iswamanager.cpp index bad0b41bf7..7e243fea85 100644 --- a/modules/iswa/util/iswamanager.cpp +++ b/modules/iswa/util/iswamanager.cpp @@ -1,26 +1,27 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2015 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + #include #include @@ -439,7 +440,10 @@ std::string IswaManager::jsonSphereToLuaTable(std::shared_ptr da void IswaManager::createScreenSpace(int id){ std::string script = "openspace.iswa.addScreenSpaceCygnet(" "{CygnetId =" + std::to_string(id) + "});"; - OsEng.scriptEngine().queueScript(script); + OsEng.scriptEngine().queueScript( + script, + scripting::ScriptEngine::RemoteScripting::Yes + ); } void IswaManager::createPlane(std::shared_ptr data){ @@ -475,7 +479,10 @@ void IswaManager::createPlane(std::shared_ptr data){ std::string luaTable = jsonPlaneToLuaTable(data); if(luaTable != ""){ std::string script = "openspace.addSceneGraphNode(" + luaTable + ");"; - OsEng.scriptEngine().queueScript(script); + OsEng.scriptEngine().queueScript( + script, + scripting::ScriptEngine::RemoteScripting::Yes + ); } } @@ -504,7 +511,10 @@ void IswaManager::createSphere(std::shared_ptr data){ std::string luaTable = jsonSphereToLuaTable(data); if(luaTable != ""){ std::string script = "openspace.addSceneGraphNode(" + luaTable + ");"; - OsEng.scriptEngine().queueScript(script); + OsEng.scriptEngine().queueScript( + script, + scripting::ScriptEngine::RemoteScripting::Yes + ); } } @@ -536,7 +546,10 @@ void IswaManager::createKameleonPlane(CdfInfo info, std::string cut){ std::string luaTable = parseKWToLuaTable(info, cut); if(!luaTable.empty()){ std::string script = "openspace.addSceneGraphNode(" + luaTable + ");"; - OsEng.scriptEngine().queueScript(script); + OsEng.scriptEngine().queueScript( + script, + scripting::ScriptEngine::RemoteScripting::Yes + ); } }else{ LWARNING( absPath(info.path) + " is not a cdf file or can't be found."); @@ -570,7 +583,10 @@ void IswaManager::createFieldline(std::string name, std::string cdfPath, std::st "}"; if(!luaTable.empty()){ std::string script = "openspace.addSceneGraphNode(" + luaTable + ");"; - OsEng.scriptEngine().queueScript(script); + OsEng.scriptEngine().queueScript( + script, + scripting::ScriptEngine::RemoteScripting::Yes + ); } }else{ LWARNING( cdfPath + " is not a cdf file or can't be found."); @@ -661,21 +677,18 @@ scripting::LuaLibrary IswaManager::luaLibrary() { &luascriptfunctions::iswa_addCygnet, "int, string, string", "Adds a IswaCygnet", - true }, { "addScreenSpaceCygnet", &luascriptfunctions::iswa_addScreenSpaceCygnet, "int, string, string", "Adds a Screen Space Cygnets", - true }, { "addKameleonPlanes", &luascriptfunctions::iswa_addKameleonPlanes, "string, int", "Adds KameleonPlanes from cdf file.", - true }, // { // "addKameleonPlane", @@ -689,38 +702,33 @@ scripting::LuaLibrary IswaManager::luaLibrary() { &luascriptfunctions::iswa_addCdfFiles, "string", "Adds a cdf files to choose from.", - true }, { "removeCygnet", &luascriptfunctions::iswa_removeCygnet, "string", "Remove a Cygnets", - true }, { "removeScreenSpaceCygnet", &luascriptfunctions::iswa_removeScrenSpaceCygnet, "int", "Remove a Screen Space Cygnets", - true }, { "removeGroup", &luascriptfunctions::iswa_removeGroup, "int", "Remove a group of Cygnets", - true }, { "setBaseUrl", &luascriptfunctions::iswa_setBaseUrl, "string", "sets the base url", - true } } }; } -}// namsepace openspace \ No newline at end of file +} // namsepace openspace diff --git a/modules/iswa/util/iswamanager.h b/modules/iswa/util/iswamanager.h index b96e69dc19..24d926c05f 100644 --- a/modules/iswa/util/iswamanager.h +++ b/modules/iswa/util/iswamanager.h @@ -1,28 +1,29 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2015 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ -#ifndef __ISWAMANAGER_H__ -#define __ISWAMANAGER_H__ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_ISWA___ISWAMANAGER___H__ +#define __OPENSPACE_MODULE_ISWA___ISWAMANAGER___H__ #include #include @@ -137,4 +138,5 @@ private: }; } //namespace openspace -#endif //__ISWAMANAGER_H__ \ No newline at end of file + +#endif //__OPENSPACE_MODULE_ISWA___ISWAMANAGER___H__ diff --git a/modules/iswa/util/iswamanager_lua.inl b/modules/iswa/util/iswamanager_lua.inl index 703a053ba0..1a704b8aee 100644 --- a/modules/iswa/util/iswamanager_lua.inl +++ b/modules/iswa/util/iswamanager_lua.inl @@ -114,7 +114,10 @@ int iswa_addScreenSpaceCygnet(lua_State* L){ int iswa_removeCygnet(lua_State* L){ std::string name = luaL_checkstring(L, -1); - OsEng.scriptEngine().queueScript("openspace.removeSceneGraphNode('" + name + "')"); + OsEng.scriptEngine().queueScript( + "openspace.removeSceneGraphNode('" + name + "')", + scripting::ScriptEngine::RemoteScripting::Yes + ); // IswaManager::ref().deleteIswaCygnet(s); return 0; } @@ -134,7 +137,10 @@ int iswa_removeScrenSpaceCygnet(lua_State* L){ info->selected = false; std::string script = "openspace.unregisterScreenSpaceRenderable('" + cygnetInformation[id]->name + "');"; - OsEng.scriptEngine().queueScript(script); + OsEng.scriptEngine().queueScript( + script, + scripting::ScriptEngine::RemoteScripting::Yes + ); return 0; } diff --git a/modules/kameleon/include.cmake b/modules/kameleon/include.cmake new file mode 100644 index 0000000000..1231f1db18 --- /dev/null +++ b/modules/kameleon/include.cmake @@ -0,0 +1,3 @@ +set (OPENSPACE_DEPENDENCIES + space +) \ No newline at end of file diff --git a/modules/kameleon/include/kameleonwrapper.h b/modules/kameleon/include/kameleonwrapper.h index fafa688bfb..08f717c8e1 100644 --- a/modules/kameleon/include/kameleonwrapper.h +++ b/modules/kameleon/include/kameleonwrapper.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef KAMELEONWRAPPER_H_ -#define KAMELEONWRAPPER_H_ +#ifndef __OPENSPACE_MODULE_ISWA___KAMELEONWRAPPER___H__ +#define __OPENSPACE_MODULE_ISWA___KAMELEONWRAPPER___H__ #include @@ -179,4 +179,4 @@ private: } // namespace openspace -#endif // KAMELEONWRAPPER_H_ +#endif // __OPENSPACE_MODULE_ISWA___KAMELEONWRAPPER___H__ diff --git a/modules/kameleon/kameleonmodule.cpp b/modules/kameleon/kameleonmodule.cpp index 244d86e513..735d08248d 100644 --- a/modules/kameleon/kameleonmodule.cpp +++ b/modules/kameleon/kameleonmodule.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * diff --git a/modules/kameleon/kameleonmodule.h b/modules/kameleon/kameleonmodule.h index 979aba5dd9..458157ef79 100644 --- a/modules/kameleon/kameleonmodule.h +++ b/modules/kameleon/kameleonmodule.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __KAMELEONMODULE_H__ -#define __KAMELEONMODULE_H__ +#ifndef __OPENSPACE_MODULE_ISWA___KAMELEONMODULE___H__ +#define __OPENSPACE_MODULE_ISWA___KAMELEONMODULE___H__ #include @@ -36,4 +36,4 @@ public: } // namespace openspace -#endif // __KAMELEONMODULE_H__ +#endif // __OPENSPACE_MODULE_ISWA___KAMELEONMODULE___H__ diff --git a/modules/multiresvolume/include.cmake b/modules/multiresvolume/include.cmake index e69de29bb2..1231f1db18 100644 --- a/modules/multiresvolume/include.cmake +++ b/modules/multiresvolume/include.cmake @@ -0,0 +1,3 @@ +set (OPENSPACE_DEPENDENCIES + space +) \ No newline at end of file diff --git a/modules/multiresvolume/multiresvolumemodule.cpp b/modules/multiresvolume/multiresvolumemodule.cpp index 7d9baab170..13f988638c 100644 --- a/modules/multiresvolume/multiresvolumemodule.cpp +++ b/modules/multiresvolume/multiresvolumemodule.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * diff --git a/modules/multiresvolume/multiresvolumemodule.h b/modules/multiresvolume/multiresvolumemodule.h index 48d14100ec..5f12395790 100644 --- a/modules/multiresvolume/multiresvolumemodule.h +++ b/modules/multiresvolume/multiresvolumemodule.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __MULTIRESVOLUMEMODULE_H__ -#define __MULTIRESVOLUMEMODULE_H__ +#ifndef __OPENSPACE_MODULE_MULTIRESVOLUME___MULTIRESVOLUMEMODULE___H__ +#define __OPENSPACE_MODULE_MULTIRESVOLUME___MULTIRESVOLUMEMODULE___H__ #include @@ -37,4 +37,4 @@ public: } // namespace openspace -#endif // __MULTIRESVOLUMEMODULE_H__ +#endif // __OPENSPACE_MODULE_MULTIRESVOLUME___MULTIRESVOLUMEMODULE___H__ diff --git a/modules/multiresvolume/rendering/atlasmanager.cpp b/modules/multiresvolume/rendering/atlasmanager.cpp index 65bfbaa4e3..ad54463c76 100644 --- a/modules/multiresvolume/rendering/atlasmanager.cpp +++ b/modules/multiresvolume/rendering/atlasmanager.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * diff --git a/modules/multiresvolume/rendering/atlasmanager.h b/modules/multiresvolume/rendering/atlasmanager.h index b042c57827..5da58ae0c0 100644 --- a/modules/multiresvolume/rendering/atlasmanager.h +++ b/modules/multiresvolume/rendering/atlasmanager.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __ATLASMANAGER_H__ -#define __ATLASMANAGER_H__ +#ifndef __OPENSPACE_MODULE_MULTIRESVOLUME___ATLASMANAGER___H__ +#define __OPENSPACE_MODULE_MULTIRESVOLUME___ATLASMANAGER___H__ #include #include @@ -100,4 +100,4 @@ private: } // namespace openspace -#endif +#endif // __OPENSPACE_MODULE_MULTIRESVOLUME___ATLASMANAGER___H__ diff --git a/modules/multiresvolume/rendering/brickcover.h b/modules/multiresvolume/rendering/brickcover.h index 150f8a2cba..463712e169 100644 --- a/modules/multiresvolume/rendering/brickcover.h +++ b/modules/multiresvolume/rendering/brickcover.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __BRICKCOVER_H__ -#define __BRICKCOVER_H__ +#ifndef __OPENSPACE_MODULE_MULTIRESVOLUME___BRICKCOVER___H__ +#define __OPENSPACE_MODULE_MULTIRESVOLUME___BRICKCOVER___H__ namespace openspace { @@ -63,6 +63,7 @@ struct BrickCover { return child; } }; -} -#endif // __BRICKCOVER_H__ +} // namespace openspace + +#endif // __OPENSPACE_MODULE_MULTIRESVOLUME___BRICKCOVER___H__ diff --git a/modules/multiresvolume/rendering/brickmanager.cpp b/modules/multiresvolume/rendering/brickmanager.cpp index 229e97f62e..7d4d284c07 100644 --- a/modules/multiresvolume/rendering/brickmanager.cpp +++ b/modules/multiresvolume/rendering/brickmanager.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * diff --git a/modules/multiresvolume/rendering/brickmanager.h b/modules/multiresvolume/rendering/brickmanager.h index ddc72c49a1..e0be43600f 100644 --- a/modules/multiresvolume/rendering/brickmanager.h +++ b/modules/multiresvolume/rendering/brickmanager.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __BRICKMANAGER_H__ -#define __BRICKMANAGER_H__ +#ifndef __OPENSPACE_MODULE_MULTIRESVOLUME___BRICKMANAGER___H__ +#define __OPENSPACE_MODULE_MULTIRESVOLUME___BRICKMANAGER___H__ #include @@ -108,4 +108,4 @@ private: } // namespace openspace -#endif \ No newline at end of file +#endif // __OPENSPACE_MODULE_MULTIRESVOLUME___BRICKMANAGER___H__ diff --git a/modules/multiresvolume/rendering/brickselection.h b/modules/multiresvolume/rendering/brickselection.h index c329523994..27d899e3ba 100644 --- a/modules/multiresvolume/rendering/brickselection.h +++ b/modules/multiresvolume/rendering/brickselection.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,12 +22,11 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __BRICKSELECTION_H__ -#define __BRICKSELECTION_H__ +#ifndef __OPENSPACE_MODULE_MULTIRESVOLUME___BRICKSELECTION___H__ +#define __OPENSPACE_MODULE_MULTIRESVOLUME___BRICKSELECTION___H__ #include - namespace openspace { struct BrickSelection { @@ -103,6 +102,7 @@ struct BrickSelection { return a.splitPoints < b.splitPoints; } }; -} -#endif // __BRICKSELECTION_H__ +} // namespace openspace + +#endif // __OPENSPACE_MODULE_MULTIRESVOLUME___BRICKSELECTION___H__ diff --git a/modules/multiresvolume/rendering/brickselector.h b/modules/multiresvolume/rendering/brickselector.h index 8d99fe5b5e..80e5978060 100644 --- a/modules/multiresvolume/rendering/brickselector.h +++ b/modules/multiresvolume/rendering/brickselector.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __BRICKSELECTOR_H__ -#define __BRICKSELECTOR_H__ +#ifndef __OPENSPACE_MODULE_MULTIRESVOLUME___BRICKSELECTOR___H__ +#define __OPENSPACE_MODULE_MULTIRESVOLUME___BRICKSELECTOR___H__ #include @@ -39,4 +39,4 @@ public: } // namespace openspace -#endif // __BRICKSELECTOR_H__ +#endif // __OPENSPACE_MODULE_MULTIRESVOLUME___BRICKSELECTOR___H__ diff --git a/modules/multiresvolume/rendering/errorhistogrammanager.cpp b/modules/multiresvolume/rendering/errorhistogrammanager.cpp index 73f559b9fb..9db36064b4 100644 --- a/modules/multiresvolume/rendering/errorhistogrammanager.cpp +++ b/modules/multiresvolume/rendering/errorhistogrammanager.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * diff --git a/modules/multiresvolume/rendering/errorhistogrammanager.h b/modules/multiresvolume/rendering/errorhistogrammanager.h index 99e793670d..4237335a3a 100644 --- a/modules/multiresvolume/rendering/errorhistogrammanager.h +++ b/modules/multiresvolume/rendering/errorhistogrammanager.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __ERRORHISTOGRAMMANAGER_H__ -#define __ERRORHISTOGRAMMANAGER_H__ +#ifndef __OPENSPACE_MODULE_MULTIRESVOLUME___ERRORHISTOGRAMMANAGER___H__ +#define __OPENSPACE_MODULE_MULTIRESVOLUME___ERRORHISTOGRAMMANAGER___H__ #include #include @@ -73,4 +73,4 @@ private: } // namespace openspace -#endif // __ERRORHISTOGRAMMANAGER_H__ +#endif // __OPENSPACE_MODULE_MULTIRESVOLUME___ERRORHISTOGRAMMANAGER___H__ diff --git a/modules/multiresvolume/rendering/histogrammanager.cpp b/modules/multiresvolume/rendering/histogrammanager.cpp index da0c1b1a8c..d0ad52c000 100644 --- a/modules/multiresvolume/rendering/histogrammanager.cpp +++ b/modules/multiresvolume/rendering/histogrammanager.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * diff --git a/modules/multiresvolume/rendering/histogrammanager.h b/modules/multiresvolume/rendering/histogrammanager.h index 6ddefd14c2..fbdafaee11 100644 --- a/modules/multiresvolume/rendering/histogrammanager.h +++ b/modules/multiresvolume/rendering/histogrammanager.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __HISTOGRAMMANAGER_H__ -#define __HISTOGRAMMANAGER_H__ +#ifndef __OPENSPACE_MODULE_MULTIRESVOLUME___HISTOGRAMMANAGER___H__ +#define __OPENSPACE_MODULE_MULTIRESVOLUME___HISTOGRAMMANAGER___H__ #include #include @@ -51,4 +51,4 @@ private: } // namespace openspace -#endif // __HISTOGRAMMANAGER_H__ +#endif // __OPENSPACE_MODULE_MULTIRESVOLUME___HISTOGRAMMANAGER___H__ diff --git a/modules/multiresvolume/rendering/localerrorhistogrammanager.cpp b/modules/multiresvolume/rendering/localerrorhistogrammanager.cpp index e90de1d97a..1b3926457b 100644 --- a/modules/multiresvolume/rendering/localerrorhistogrammanager.cpp +++ b/modules/multiresvolume/rendering/localerrorhistogrammanager.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * diff --git a/modules/multiresvolume/rendering/localerrorhistogrammanager.h b/modules/multiresvolume/rendering/localerrorhistogrammanager.h index 4184696e02..c76b859aea 100644 --- a/modules/multiresvolume/rendering/localerrorhistogrammanager.h +++ b/modules/multiresvolume/rendering/localerrorhistogrammanager.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __LOCALERRORHISTOGRAMMANAGER_H__ -#define __LOCALERRORHISTOGRAMMANAGER_H__ +#ifndef __OPENSPACE_MODULE_MULTIRESVOLUME___LOCALERRORHISTOGRAMMANAGER___H__ +#define __OPENSPACE_MODULE_MULTIRESVOLUME___LOCALERRORHISTOGRAMMANAGER___H__ #include #include @@ -77,4 +77,4 @@ private: } // namespace openspace -#endif // __LOCALERRORHISTOGRAMMANAGER_H__ +#endif // __OPENSPACE_MODULE_MULTIRESVOLUME___LOCALERRORHISTOGRAMMANAGER___H__ diff --git a/modules/multiresvolume/rendering/localtfbrickselector.cpp b/modules/multiresvolume/rendering/localtfbrickselector.cpp index 009ef735e2..dcfa208c41 100644 --- a/modules/multiresvolume/rendering/localtfbrickselector.cpp +++ b/modules/multiresvolume/rendering/localtfbrickselector.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * diff --git a/modules/multiresvolume/rendering/localtfbrickselector.h b/modules/multiresvolume/rendering/localtfbrickselector.h index cac58a9d7e..62990e10f9 100644 --- a/modules/multiresvolume/rendering/localtfbrickselector.h +++ b/modules/multiresvolume/rendering/localtfbrickselector.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __LOCALTFBRICKSELECTOR_H__ -#define __LOCALTFBRICKSELECTOR_H__ +#ifndef __OPENSPACE_MODULE_MULTIRESVOLUME___LOCALTFBRICKSELECTOR___H__ +#define __OPENSPACE_MODULE_MULTIRESVOLUME___LOCALTFBRICKSELECTOR___H__ #include #include @@ -74,5 +74,4 @@ public: } // namespace openspace -#endif // __LOCALTFBRICKSELECTOR_H__ - +#endif // __OPENSPACE_MODULE_MULTIRESVOLUME___LOCALTFBRICKSELECTOR___H__ diff --git a/modules/multiresvolume/rendering/multiresvolumeraycaster.cpp b/modules/multiresvolume/rendering/multiresvolumeraycaster.cpp index 1d08f19e18..332e5d3ce9 100644 --- a/modules/multiresvolume/rendering/multiresvolumeraycaster.cpp +++ b/modules/multiresvolume/rendering/multiresvolumeraycaster.cpp @@ -149,7 +149,7 @@ bool MultiresVolumeRaycaster::cameraIsInside(const RenderData& data, glm::vec3& glm::vec4 modelPos = (glm::inverse(scaledModelTransform) / divisor) * camWorldPos; - localPosition = (modelPos.xyz() + glm::vec3(0.5)); + localPosition = (glm::vec3(modelPos) + glm::vec3(0.5)); return (localPosition.x > 0 && localPosition.y > 0 && localPosition.z > 0 && localPosition.x < 1 && localPosition.y < 1 && localPosition.z < 1); } diff --git a/modules/multiresvolume/rendering/multiresvolumeraycaster.h b/modules/multiresvolume/rendering/multiresvolumeraycaster.h index 1c48cc1828..bd8784d00b 100644 --- a/modules/multiresvolume/rendering/multiresvolumeraycaster.h +++ b/modules/multiresvolume/rendering/multiresvolumeraycaster.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __MULTIRESVOLUMERAYCASTER_H__ -#define __MULTIRESVOLUMERAYCASTER_H__ +#ifndef __OPENSPACE_MODULE_MULTIRESVOLUME___MULTIRESVOLUMERAYCASTER___H__ +#define __OPENSPACE_MODULE_MULTIRESVOLUME___MULTIRESVOLUMERAYCASTER___H__ #include #include @@ -93,6 +93,6 @@ private: }; // MultiresVolumeRaycaster -} // openspace +} // namespace openspace -#endif // __MULTIRESVOLUMERAYCASTER_H__ +#endif // __OPENSPACE_MODULE_MULTIRESVOLUME___MULTIRESVOLUMERAYCASTER___H__ diff --git a/modules/multiresvolume/rendering/renderablemultiresvolume.cpp b/modules/multiresvolume/rendering/renderablemultiresvolume.cpp index 0db6385d55..2da28a3a05 100644 --- a/modules/multiresvolume/rendering/renderablemultiresvolume.cpp +++ b/modules/multiresvolume/rendering/renderablemultiresvolume.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * diff --git a/modules/multiresvolume/rendering/renderablemultiresvolume.h b/modules/multiresvolume/rendering/renderablemultiresvolume.h index 1f040edfe1..a24315d8de 100644 --- a/modules/multiresvolume/rendering/renderablemultiresvolume.h +++ b/modules/multiresvolume/rendering/renderablemultiresvolume.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERABLEMULTIRESVOLUME_H__ -#define __RENDERABLEMULTIRESVOLUME_H__ +#ifndef __OPENSPACE_MODULE_MULTIRESVOLUME___RENDERABLEMULTIRESVOLUME___H__ +#define __OPENSPACE_MODULE_MULTIRESVOLUME___RENDERABLEMULTIRESVOLUME___H__ #include #include @@ -160,4 +160,4 @@ private: } // namespace openspace -#endif // __RENDERABLEMULTIRESVOLUME_H__ +#endif // __OPENSPACE_MODULE_MULTIRESVOLUME___RENDERABLEMULTIRESVOLUME___H__ diff --git a/modules/multiresvolume/rendering/shenbrickselector.cpp b/modules/multiresvolume/rendering/shenbrickselector.cpp index 8f6e726887..e0549b4859 100644 --- a/modules/multiresvolume/rendering/shenbrickselector.cpp +++ b/modules/multiresvolume/rendering/shenbrickselector.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * diff --git a/modules/multiresvolume/rendering/shenbrickselector.h b/modules/multiresvolume/rendering/shenbrickselector.h index 99bcb252f7..3001b94b56 100644 --- a/modules/multiresvolume/rendering/shenbrickselector.h +++ b/modules/multiresvolume/rendering/shenbrickselector.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SHENBRICKSELECTOR_H__ -#define __SHENBRICKSELECTOR_H__ +#ifndef __OPENSPACE_MODULE_MULTIRESVOLUME___SHENBRICKSELECTOR___H__ +#define __OPENSPACE_MODULE_MULTIRESVOLUME___SHENBRICKSELECTOR___H__ #include #include @@ -74,4 +74,4 @@ private: } // namespace openspace -#endif // __SHENBRICKSELECTOR_H__ +#endif // __OPENSPACE_MODULE_MULTIRESVOLUME___SHENBRICKSELECTOR___H__ diff --git a/modules/multiresvolume/rendering/simpletfbrickselector.cpp b/modules/multiresvolume/rendering/simpletfbrickselector.cpp index 5b874b924d..c409e23666 100644 --- a/modules/multiresvolume/rendering/simpletfbrickselector.cpp +++ b/modules/multiresvolume/rendering/simpletfbrickselector.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * diff --git a/modules/multiresvolume/rendering/simpletfbrickselector.h b/modules/multiresvolume/rendering/simpletfbrickselector.h index 0dadfa90d6..11bbae032d 100644 --- a/modules/multiresvolume/rendering/simpletfbrickselector.h +++ b/modules/multiresvolume/rendering/simpletfbrickselector.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SIMPLETFBRICKSELECTOR_H__ -#define __SIMPLETFBRICKSELECTOR_H__ +#ifndef __OPENSPACE_MODULE_MULTIRESVOLUME___SIMPLETFBRICKSELECTOR___H__ +#define __OPENSPACE_MODULE_MULTIRESVOLUME___SIMPLETFBRICKSELECTOR___H__ #include #include @@ -67,5 +67,4 @@ public: } // namespace openspace -#endif // __SIMPLETFBRICKSELECTOR_H__ - +#endif // __OPENSPACE_MODULE_MULTIRESVOLUME___SIMPLETFBRICKSELECTOR___H__ diff --git a/modules/multiresvolume/rendering/tfbrickselector.cpp b/modules/multiresvolume/rendering/tfbrickselector.cpp index f976b714c6..b0d889bb20 100644 --- a/modules/multiresvolume/rendering/tfbrickselector.cpp +++ b/modules/multiresvolume/rendering/tfbrickselector.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * diff --git a/modules/multiresvolume/rendering/tfbrickselector.h b/modules/multiresvolume/rendering/tfbrickselector.h index 2a48004406..e411b453c6 100644 --- a/modules/multiresvolume/rendering/tfbrickselector.h +++ b/modules/multiresvolume/rendering/tfbrickselector.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,15 +22,14 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __TFBRICKSELECTOR_H__ -#define __TFBRICKSELECTOR_H__ +#ifndef __OPENSPACE_MODULE_MULTIRESVOLUME___TFBRICKSELECTOR___H__ +#define __OPENSPACE_MODULE_MULTIRESVOLUME___TFBRICKSELECTOR___H__ #include #include #include #include - namespace openspace { class TSP; @@ -69,5 +68,4 @@ public: } // namespace openspace -#endif // __TFBRICKSELECTOR_H__ - +#endif // __OPENSPACE_MODULE_MULTIRESVOLUME___TFBRICKSELECTOR___H__ diff --git a/modules/multiresvolume/rendering/tsp.cpp b/modules/multiresvolume/rendering/tsp.cpp index 49b39f4782..74c1cf0400 100644 --- a/modules/multiresvolume/rendering/tsp.cpp +++ b/modules/multiresvolume/rendering/tsp.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * diff --git a/modules/multiresvolume/rendering/tsp.h b/modules/multiresvolume/rendering/tsp.h index 6addb710ba..d182238284 100644 --- a/modules/multiresvolume/rendering/tsp.h +++ b/modules/multiresvolume/rendering/tsp.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,17 +22,15 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __TSP_H__ -#define __TSP_H__ +#ifndef __OPENSPACE_MODULE_MULTIRESVOLUME___TSP___H__ +#define __OPENSPACE_MODULE_MULTIRESVOLUME___TSP___H__ -// std includes #include #include #include #include #include -// ghoul includes #include namespace openspace { @@ -143,6 +141,7 @@ private: float medianTemporalError_; }; // class TSP + } // namespace openspace -#endif +#endif // __OPENSPACE_MODULE_MULTIRESVOLUME___TSP___H__ diff --git a/modules/newhorizons/CMakeLists.txt b/modules/newhorizons/CMakeLists.txt index 131d181ccf..ee275651ac 100644 --- a/modules/newhorizons/CMakeLists.txt +++ b/modules/newhorizons/CMakeLists.txt @@ -31,7 +31,6 @@ set(HEADER_FILES ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableplanetprojection.h ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableshadowcylinder.h ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablemodelprojection.h - ${CMAKE_CURRENT_SOURCE_DIR}/rendering/writeToTexture.h ${CMAKE_CURRENT_SOURCE_DIR}/util/decoder.h ${CMAKE_CURRENT_SOURCE_DIR}/util/hongkangparser.h ${CMAKE_CURRENT_SOURCE_DIR}/util/instrumenttimesparser.h diff --git a/modules/newhorizons/include.cmake b/modules/newhorizons/include.cmake index ffea0ac430..3c69ad5f63 100644 --- a/modules/newhorizons/include.cmake +++ b/modules/newhorizons/include.cmake @@ -1 +1,5 @@ set(DEFAULT_MODULE ON) + +set (OPENSPACE_DEPENDENCIES + space +) \ No newline at end of file diff --git a/modules/newhorizons/newhorizonsmodule.cpp b/modules/newhorizons/newhorizonsmodule.cpp index 72caa9b844..59168a207c 100644 --- a/modules/newhorizons/newhorizonsmodule.cpp +++ b/modules/newhorizons/newhorizonsmodule.cpp @@ -24,23 +24,21 @@ #include -#include -#include - -#include - #include -#include #include +#include #include #include -#include +#include #include #include #include -#include +#include +#include + +#include namespace openspace { @@ -71,4 +69,12 @@ void NewHorizonsModule::internalInitialize() { fDecoder->registerClass("Target"); } +std::vector NewHorizonsModule::documentations() const { + return { + RenderableModelProjection::Documentation(), + RenderablePlanetProjection::Documentation(), + ProjectionComponent::Documentation() + }; +} + } // namespace openspace diff --git a/modules/newhorizons/newhorizonsmodule.h b/modules/newhorizons/newhorizonsmodule.h index e4b57eaa7a..8bd39cbce4 100644 --- a/modules/newhorizons/newhorizonsmodule.h +++ b/modules/newhorizons/newhorizonsmodule.h @@ -33,6 +33,8 @@ class NewHorizonsModule : public OpenSpaceModule { public: NewHorizonsModule(); + std::vector documentations() const override; + protected: void internalInitialize() override; }; diff --git a/modules/newhorizons/rendering/renderablecrawlingline.cpp b/modules/newhorizons/rendering/renderablecrawlingline.cpp index 4c538c180a..7a78fa451c 100644 --- a/modules/newhorizons/rendering/renderablecrawlingline.cpp +++ b/modules/newhorizons/rendering/renderablecrawlingline.cpp @@ -32,11 +32,11 @@ namespace { const std::string _loggerCat = "RenderableCrawlingLine"; - const std::string KeySource = "Source"; - const std::string KeyTarget = "Target"; - const std::string KeyInstrument = "Instrument"; - const std::string KeyReferenceFrame = "Frame"; - const std::string keyColor = "RGB"; + const char* KeySource = "Source"; + const char* KeyTarget = "Target"; + const char* KeyInstrument = "Instrument"; + const char* KeyReferenceFrame = "Frame"; + const char* KeyColor = "RGB"; static const int SourcePosition = 0; static const int TargetPosition = 1; @@ -59,10 +59,12 @@ RenderableCrawlingLine::RenderableCrawlingLine(const ghoul::Dictionary& dictiona dictionary.getValue(KeyReferenceFrame, _referenceFrame); - if (dictionary.hasKeyAndValue(keyColor)) - dictionary.getValue(keyColor, _lineColor); - else + if (dictionary.hasKeyAndValue(KeyColor)) { + dictionary.getValue(KeyColor, _lineColor); + } + else { _lineColor = glm::vec3(1); + } } bool RenderableCrawlingLine::isReady() const { @@ -132,7 +134,7 @@ void RenderableCrawlingLine::render(const RenderData& data) { _program->setUniform("ModelTransform", transform); int frame = _frameCounter % 60; - float fadingFactor = static_cast(sin((frame * pi_c()) / 60)); + float fadingFactor = static_cast(sin((frame * 3.14159) / 60)); float alpha = 0.6f + fadingFactor*0.4f; glLineWidth(2.f); diff --git a/modules/newhorizons/rendering/renderablecrawlingline.h b/modules/newhorizons/rendering/renderablecrawlingline.h index 2e8df6991b..3b8728914e 100644 --- a/modules/newhorizons/rendering/renderablecrawlingline.h +++ b/modules/newhorizons/rendering/renderablecrawlingline.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERABLECRAWLINGLINE_H__ -#define __RENDERABLECRAWLINGLINE_H__ +#ifndef __OPENSPACE_MODULE_NEWHORIZONS___RENDERABLECRAWLINGLINE___H__ +#define __OPENSPACE_MODULE_NEWHORIZONS___RENDERABLECRAWLINGLINE___H__ #include @@ -62,4 +62,4 @@ private: } // namespace openspace -#endif // __RENDERABLECRAWLINGLINE_H__ +#endif // __OPENSPACE_MODULE_NEWHORIZONS___RENDERABLECRAWLINGLINE___H__ diff --git a/modules/newhorizons/rendering/renderablefov.cpp b/modules/newhorizons/rendering/renderablefov.cpp index 878d833186..f906129321 100644 --- a/modules/newhorizons/rendering/renderablefov.cpp +++ b/modules/newhorizons/rendering/renderablefov.cpp @@ -38,14 +38,15 @@ namespace { const std::string _loggerCat = "RenderableFov"; - const std::string keyBody = "Body"; - const std::string keyFrame = "Frame"; - const std::string keyPathModule = "ModulePath"; - const std::string keyColor = "RGB"; - const std::string keyInstrument = "Instrument.Name"; - const std::string keyInstrumentMethod = "Instrument.Method"; - const std::string keyInstrumentAberration = "Instrument.Aberration"; - const std::string keyPotentialTargets = "PotentialTargets"; + const char* keyBody = "Body"; + const char* keyFrame = "Frame"; + const char* keyPathModule = "ModulePath"; + const char* keyColor = "RGB"; + const char* keyInstrument = "Instrument.Name"; + const char* keyInstrumentMethod = "Instrument.Method"; + const char* keyInstrumentAberration = "Instrument.Aberration"; + const char* keyPotentialTargets = "PotentialTargets"; + const char* keyFrameConversions = "FrameConversions"; const int InterpolationSteps = 10; const int Stride = 8; @@ -94,6 +95,17 @@ RenderableFov::RenderableFov(const ghoul::Dictionary& dictionary) _potentialTargets[i] = target; } + ghoul::Dictionary frameConversions; + success = dictionary.getValue(keyFrameConversions, frameConversions); + if (success) { + for (const std::string& key : frameConversions.keys()) { + openspace::SpiceManager::ref().addFrame( + key, + frameConversions.value(key) + ); + } + } + addProperty(_lineWidth); addProperty(_drawSolid); } @@ -147,7 +159,7 @@ bool RenderableFov::deinitialize() { } bool RenderableFov::isReady() const { - return _programObject != nullptr; + return _programObject != nullptr && !_bounds.empty(); } void RenderableFov::sendToGPU() { @@ -266,7 +278,7 @@ psc RenderableFov::orthogonalProjection(glm::dvec3 vecFov) { glm::dvec3 p = glm::proj(vecToTarget, vecFov); psc projection = PowerScaledCoordinate::CreatePowerScaledCoordinate(p[0], p[1], p[2]); - projection[3] += 3; + projection[3] += 3; return projection; } @@ -310,7 +322,6 @@ glm::dvec3 RenderableFov::bisection(glm::dvec3 p1, glm::dvec3 p2) { } } - void RenderableFov::fovSurfaceIntercept(bool H[], std::vector bounds) { _nrInserted = 0; _fovPlane.clear(); // empty the array @@ -472,7 +483,7 @@ void RenderableFov::determineTarget() { } void RenderableFov::computeIntercepts(const RenderData& data) { - PerfMeasure("computeIntercepts"); + //PerfMeasure("computeIntercepts"); // for each FOV vector _fovBounds.clear(); for (int i = 0; i <= _bounds.size(); ++i) { @@ -577,7 +588,7 @@ void RenderableFov::render(const RenderData& data) { if (_drawFOV) { // update only when time progresses. if (_oldTime != _time) { - PerfMeasure("Total"); + //PerfMeasure("Total"); determineTarget(); computeColors(); computeIntercepts(data); diff --git a/modules/newhorizons/rendering/renderablefov.h b/modules/newhorizons/rendering/renderablefov.h index c752f49d9d..58292e39d1 100644 --- a/modules/newhorizons/rendering/renderablefov.h +++ b/modules/newhorizons/rendering/renderablefov.h @@ -22,11 +22,13 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERABLEFOV_H__ -#define __RENDERABLEFOV_H__ +#ifndef __OPENSPACE_MODULE_NEWHORIZONS___RENDERABLEFOV___H__ +#define __OPENSPACE_MODULE_NEWHORIZONS___RENDERABLEFOV___H__ #include +#include +#include #include #include @@ -130,4 +132,4 @@ public: } // namespace openspace -#endif // __RENDERABLEFOV_H__ +#endif // __OPENSPACE_MODULE_NEWHORIZONS___RENDERABLEFOV___H__ diff --git a/modules/newhorizons/rendering/renderablemodelprojection.cpp b/modules/newhorizons/rendering/renderablemodelprojection.cpp index 3daadde566..29b5b5a05e 100644 --- a/modules/newhorizons/rendering/renderablemodelprojection.cpp +++ b/modules/newhorizons/rendering/renderablemodelprojection.cpp @@ -24,31 +24,82 @@ #include +#include + +#include #include #include #include #include #include +#include #include #include +#include +#include #include namespace { const std::string _loggerCat = "RenderableModelProjection"; - const std::string keySource = "Rotation.Source"; - const std::string keyDestination = "Rotation.Destination"; - const std::string keyBody = "Body"; - const std::string keyGeometry = "Geometry"; - const std::string keyBoundingSphereRadius = "BoundingSphereRadius"; + const char* keySource = "Rotation.Source"; + const char* keyDestination = "Rotation.Destination"; + const char* keyGeometry = "Geometry"; + const char* keyProjection = "Projection"; + const char* keyBoundingSphereRadius = "BoundingSphereRadius"; - const std::string keyTextureColor = "Textures.Color"; - const std::string keyTextureProject = "Textures.Project"; - const std::string keyTextureDefault = "Textures.Default"; + const char* keyTextureColor = "Textures.Color"; + + const char* _destination = "GALACTIC"; } namespace openspace { +Documentation RenderableModelProjection::Documentation() { + using namespace documentation; + + return { + "Renderable Model Projection", + "newhorizons_renderable_modelprojection", + { + { + "Type", + new StringEqualVerifier("RenderableModelProjection"), + "", + Optional::No + }, + { + keyGeometry, + new ReferencingVerifier("base_geometry_model"), + "The geometry that is used for rendering this model.", + Optional::No + }, + { + keyProjection, + new ReferencingVerifier("newhorizons_projectioncomponent"), + "Contains information about projecting onto this planet.", + Optional::No + }, + { + keyTextureColor, + new StringVerifier, + "The base texture for the model that is shown before any projection " + "occurred.", + Optional::No + }, + { + keyBoundingSphereRadius, + new DoubleVerifier, + "The radius of the bounding sphere of this object. This has to be a " + "radius that is larger than anything that is rendered by it. It has to " + "be at least as big as the convex hull of the object. The default value " + "is 10e9 meters.", + Optional::Yes + } + } + }; +} + RenderableModelProjection::RenderableModelProjection(const ghoul::Dictionary& dictionary) : Renderable(dictionary) , _colorTexturePath("colorTexture", "Color Texture") @@ -59,44 +110,35 @@ RenderableModelProjection::RenderableModelProjection(const ghoul::Dictionary& di , _geometry(nullptr) , _performShading("performShading", "Perform Shading", true) { + documentation::testSpecificationAndThrow( + Documentation(), + dictionary, + "RenderableModelProjection" + ); + std::string name; bool success = dictionary.getValue(SceneGraphNode::KeyName, name); ghoul_assert(success, "Name was not passed to RenderableModelProjection"); - ghoul::Dictionary geometryDictionary; - success = dictionary.getValue(keyGeometry, geometryDictionary); - if (success) { - using modelgeometry::ModelGeometry; - geometryDictionary.setValue(SceneGraphNode::KeyName, name); - _geometry = std::unique_ptr( - ModelGeometry::createFromDictionary(geometryDictionary) - ); - } + using ghoul::Dictionary; + Dictionary geometryDictionary = dictionary.value(keyGeometry); + using modelgeometry::ModelGeometry; + geometryDictionary.setValue(SceneGraphNode::KeyName, name); + _geometry = std::unique_ptr( + ModelGeometry::createFromDictionary(geometryDictionary) + ); - std::string texturePath = ""; - success = dictionary.getValue(keyTextureColor, texturePath); - if (success) - _colorTexturePath = absPath(texturePath); + _colorTexturePath = absPath(dictionary.value(keyTextureColor)); - success = dictionary.getValue(keyTextureDefault, texturePath); - if (success) - _defaultProjImage = absPath(texturePath); - addPropertySubOwner(_geometry.get()); addPropertySubOwner(_projectionComponent); addProperty(_colorTexturePath); _colorTexturePath.onChange(std::bind(&RenderableModelProjection::loadTextures, this)); - dictionary.getValue(keySource, _source); - dictionary.getValue(keyDestination, _destination); - dictionary.getValue(keyBody, _target); - - - bool completeSuccess = true; - completeSuccess &= _projectionComponent.initializeProjectionSettings(dictionary); - - openspace::SpiceManager::ref().addFrame(_target, _source); + _projectionComponent.initialize( + dictionary.value(keyProjection) + ); float boundingSphereRadius = 1.0e9; dictionary.getValue(keyBoundingSphereRadius, boundingSphereRadius); @@ -104,11 +146,14 @@ RenderableModelProjection::RenderableModelProjection(const ghoul::Dictionary& di Renderable::addProperty(_performShading); Renderable::addProperty(_rotation); - - success = _projectionComponent.initializeParser(dictionary); - ghoul_assert(success, ""); } +RenderableModelProjection::~RenderableModelProjection() { + // This empty method needs to be here in order to use forward declaration with + // std::unique_ptr +} + + bool RenderableModelProjection::isReady() const { bool ready = true; ready &= (_programObject != nullptr); @@ -139,15 +184,12 @@ bool RenderableModelProjection::initialize() { completeSuccess &= loadTextures(); - completeSuccess &= _projectionComponent.initialize(); + completeSuccess &= _projectionComponent.initializeGL(); auto bs = getBoundingSphere(); completeSuccess &= _geometry->initialize(this); setBoundingSphere(bs); // ignore bounding sphere set by geometry. - completeSuccess &= !_source.empty(); - completeSuccess &= !_destination.empty(); - return completeSuccess; } @@ -246,18 +288,12 @@ void RenderableModelProjection::update(const UpdateData& data) { } } - // set spice-orientation in accordance to timestamp - if (!_source.empty()) { - _stateMatrix = SpiceManager::ref().positionTransformMatrix( - _source, _destination, _time - ); - } - - double lt; + _stateMatrix = data.modelTransform.rotation; + glm::dvec3 p = - openspace::SpiceManager::ref().targetPosition( - "SUN", _target, "GALACTIC", {}, _time, lt - ); + OsEng.renderEngine().scene()->sceneGraphNode("Sun")->worldPosition() - + data.modelTransform.translation; + _sunPosition = PowerScaledCoordinate::CreatePowerScaledCoordinate(p.x, p.y, p.z); } @@ -308,7 +344,6 @@ void RenderableModelProjection::imageProjectGPU( void RenderableModelProjection::attitudeParameters(double time) { try { - _stateMatrix = SpiceManager::ref().positionTransformMatrix(_source, _destination, time); _instrumentMatrix = SpiceManager::ref().positionTransformMatrix(_projectionComponent.instrumentId(), _destination, time); } catch (const SpiceManager::SpiceException& e) { diff --git a/modules/newhorizons/rendering/renderablemodelprojection.h b/modules/newhorizons/rendering/renderablemodelprojection.h index 1a0ef2c259..4beaa8a52e 100644 --- a/modules/newhorizons/rendering/renderablemodelprojection.h +++ b/modules/newhorizons/rendering/renderablemodelprojection.h @@ -22,25 +22,31 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERABLEMODELPROJECTION_H__ -#define __RENDERABLEMODELPROJECTION_H__ +#ifndef __OPENSPACE_MODULE_NEWHORIZONS___RENDERABLEMODELPROJECTION___H__ +#define __OPENSPACE_MODULE_NEWHORIZONS___RENDERABLEMODELPROJECTION___H__ #include + #include -#include +#include #include -#include #include -#include -#include +#include -#include -#include +namespace ghoul { +namespace opengl { +class ProgramObject; +class Texture; +} +} namespace openspace { +struct RenderData; +struct UpdateData; + namespace modelgeometry { class ModelGeometry; } @@ -48,6 +54,7 @@ namespace modelgeometry { class RenderableModelProjection : public Renderable { public: RenderableModelProjection(const ghoul::Dictionary& dictionary); + ~RenderableModelProjection(); bool initialize() override; bool deinitialize() override; @@ -59,6 +66,8 @@ public: ghoul::opengl::Texture& baseTexture() const; + static openspace::Documentation Documentation(); + private: bool loadTextures(); void attitudeParameters(double time); @@ -83,11 +92,6 @@ private: glm::dmat3 _stateMatrix; glm::dmat3 _instrumentMatrix; - std::string _defaultProjImage; - std::string _source; - std::string _destination; - std::string _target; - // uniforms glm::vec2 _camScaling; glm::vec3 _up; @@ -104,6 +108,6 @@ private: properties::BoolProperty _performShading; }; -} // namespace openspace +} // namespace openspace -#endif // __RENDERABLEMODELPROJECTION_H__ \ No newline at end of file +#endif // __OPENSPACE_MODULE_NEWHORIZONS___RENDERABLEMODELPROJECTION___H__ diff --git a/modules/newhorizons/rendering/renderableplaneprojection.cpp b/modules/newhorizons/rendering/renderableplaneprojection.cpp index aebafda854..4c405ee4a2 100644 --- a/modules/newhorizons/rendering/renderableplaneprojection.cpp +++ b/modules/newhorizons/rendering/renderableplaneprojection.cpp @@ -24,11 +24,14 @@ #include +#include + #include #include +#include #include #include -#include +#include #include #include @@ -41,13 +44,13 @@ namespace { const std::string _loggerCat = "RenderablePlaneProjection"; - const std::string KeySpacecraft = "Spacecraft"; - const std::string KeyInstrument = "Instrument"; - const std::string KeyMoving = "Moving"; - const std::string KeyTexture = "Texture"; - const std::string KeyName = "Name"; - const std::string KeyTarget = "DefaultTarget"; - const std::string GalacticFrame = "GALACTIC"; + const char* KeySpacecraft = "Spacecraft"; + const char* KeyInstrument = "Instrument"; + const char* KeyMoving = "Moving"; + const char* KeyTexture = "Texture"; + const char* KeyName = "Name"; + const char* KeyTarget = "DefaultTarget"; + const char* GalacticFrame = "GALACTIC"; const double REALLY_FAR = 99999999999; } diff --git a/modules/newhorizons/rendering/renderableplaneprojection.h b/modules/newhorizons/rendering/renderableplaneprojection.h index 7c2ee5b6ac..b38298833a 100644 --- a/modules/newhorizons/rendering/renderableplaneprojection.h +++ b/modules/newhorizons/rendering/renderableplaneprojection.h @@ -1,37 +1,32 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef _RENDERABLEPLANEPROJECTION_H_ -#define _RENDERABLEPLANEPROJECTION_H_ +#ifndef __OPENSPACE_MODULE_NEWHORIZONS___RENDERABLEPLANEPROJECTION___H__ +#define __OPENSPACE_MODULE_NEWHORIZONS___RENDERABLEPLANEPROJECTION___H__ #include -#include -#include -#include -#include - #include namespace ghoul { @@ -45,7 +40,11 @@ namespace ghoul { } namespace openspace { + +struct Image; struct LinePoint; +struct RenderData; +struct UpdateData; struct target { std::string body; @@ -98,4 +97,5 @@ private: }; } // namespace openspace -#endif + +#endif // __OPENSPACE_MODULE_NEWHORIZONS___RENDERABLEPLANEPROJECTION___H__ diff --git a/modules/newhorizons/rendering/renderableplanetprojection.cpp b/modules/newhorizons/rendering/renderableplanetprojection.cpp index 3f892aecb0..3902c44978 100644 --- a/modules/newhorizons/rendering/renderableplanetprojection.cpp +++ b/modules/newhorizons/rendering/renderableplanetprojection.cpp @@ -24,8 +24,9 @@ #include -#include +#include +#include #include #include #include @@ -37,6 +38,14 @@ #include #include +#include + +#include +#include +#include + +#include +#include #ifdef WIN32 #define _USE_MATH_DEFINES #include @@ -45,16 +54,63 @@ namespace { const std::string _loggerCat = "RenderablePlanetProjection"; - const std::string keyFrame = "Frame"; - const std::string keyGeometry = "Geometry"; - const std::string keyRadius = "Geometry.Radius"; - const std::string keyShading = "PerformShading"; - const std::string keyBody = "Body"; - const std::string _mainFrame = "GALACTIC"; + const char* keyGeometry = "Geometry"; + const char* keyProjection = "Projection"; + const char* keyColorTexture = "Textures.Color"; + const char* keyHeightTexture = "Textures.Height"; + + const char* keyRadius = "Geometry.Radius"; + const char* keyShading = "PerformShading"; + const char* _mainFrame = "GALACTIC"; } namespace openspace { +Documentation RenderablePlanetProjection::Documentation() { + using namespace openspace::documentation; + return { + "Renderable Planet Projection", + "newhorizons_renderable_planetprojection", + { + { + "Type", + new StringEqualVerifier("RenderablePlanetProjection"), + "", + Optional::No + }, + { + keyGeometry, + new ReferencingVerifier("base_geometry_planet"), + "The geometry that is used for rendering this planet.", + Optional::No + }, + { + keyProjection, + new ReferencingVerifier("newhorizons_projectioncomponent"), + "Contains information about projecting onto this planet.", + Optional::No + }, + { + keyColorTexture, + new StringVerifier, + "The path to the base color texture that is used on the planet prior to " + "any image projection. The path can use tokens of the form '${...}' or " + "be specified relative to the directory of the mod file.", + Optional::No + }, + { + keyHeightTexture, + new StringVerifier, + "The path to the height map texture that is used on the planet. The path " + "can use tokens of the form '${...}' or be specified relative to the " + "directory of the mod file. If no height map is specified the planet " + "does not use a height field.", + Optional::Yes + } + } + }; +} + RenderablePlanetProjection::RenderablePlanetProjection(const ghoul::Dictionary& dictionary) : Renderable(dictionary) , _colorTexturePath("planetTexture", "RGB Texture") @@ -68,6 +124,12 @@ RenderablePlanetProjection::RenderablePlanetProjection(const ghoul::Dictionary& , _heightMapTexture(nullptr) , _capture(false) { + documentation::testSpecificationAndThrow( + Documentation(), + dictionary, + "RenderablePlanetProject" + ); + std::string name; bool success = dictionary.getValue(SceneGraphNode::KeyName, name); ghoul_assert(success, ""); @@ -83,11 +145,7 @@ RenderablePlanetProjection::RenderablePlanetProjection(const ghoul::Dictionary& ); } - dictionary.getValue(keyFrame, _frame); - dictionary.getValue(keyBody, _body); - - success = _projectionComponent.initializeProjectionSettings(dictionary); - ghoul_assert(success, ""); + _projectionComponent.initialize(dictionary.value(keyProjection)); // TODO: textures need to be replaced by a good system similar to the geometry as soon // as the requirements are fixed (ab) @@ -117,9 +175,6 @@ RenderablePlanetProjection::RenderablePlanetProjection(const ghoul::Dictionary& addProperty(_heightExaggeration); addProperty(_debugProjectionTextureRotation); - - success = _projectionComponent.initializeParser(dictionary); - ghoul_assert(success, ""); } RenderablePlanetProjection::~RenderablePlanetProjection() {} @@ -138,7 +193,7 @@ bool RenderablePlanetProjection::initialize() { ); completeSuccess &= loadTextures(); - completeSuccess &= _projectionComponent.initialize(); + completeSuccess &= _projectionComponent.initializeGL(); completeSuccess &= _geometry->initialize(this); if (completeSuccess) { @@ -233,7 +288,6 @@ void RenderablePlanetProjection::imageProjectGPU( void RenderablePlanetProjection::attitudeParameters(double time) { // precomputations for shader - _stateMatrix = SpiceManager::ref().positionTransformMatrix(_frame, _mainFrame, time); _instrumentMatrix = SpiceManager::ref().positionTransformMatrix( _projectionComponent.instrumentId(), _mainFrame, time ); @@ -256,12 +310,7 @@ void RenderablePlanetProjection::attitudeParameters(double time) { glm::vec3(0, 1, 0) ); - for (int i = 0; i < 3; i++){ - for (int j = 0; j < 3; j++){ - _transform[i][j] = static_cast(_stateMatrix[i][j]); - } - } - _transform = _transform * rot * roty * rotProp; + _transform = glm::mat4(_stateMatrix) * rot * roty * rotProp; glm::dvec3 bs; try { @@ -411,6 +460,7 @@ void RenderablePlanetProjection::update(const UpdateData& data) { } } + _stateMatrix = data.modelTransform.rotation; } bool RenderablePlanetProjection::loadTextures() { @@ -419,7 +469,7 @@ bool RenderablePlanetProjection::loadTextures() { if (_colorTexturePath.value() != "") { _baseTexture = ghoul::io::TextureReader::ref().loadTexture(_colorTexturePath); if (_baseTexture) { - ghoul::opengl::convertTextureFormat(Texture::Format::RGB, *_baseTexture); + ghoul::opengl::convertTextureFormat(*_baseTexture, Texture::Format::RGB); _baseTexture->uploadTexture(); _baseTexture->setFilter(Texture::FilterMode::Linear); } @@ -429,7 +479,7 @@ bool RenderablePlanetProjection::loadTextures() { if (_heightMapTexturePath.value() != "") { _heightMapTexture = ghoul::io::TextureReader::ref().loadTexture(_heightMapTexturePath); if (_heightMapTexture) { - ghoul::opengl::convertTextureFormat(Texture::Format::RGB, *_heightMapTexture); + ghoul::opengl::convertTextureFormat(*_heightMapTexture, Texture::Format::RGB); _heightMapTexture->uploadTexture(); _heightMapTexture->setFilter(Texture::FilterMode::Linear); } diff --git a/modules/newhorizons/rendering/renderableplanetprojection.h b/modules/newhorizons/rendering/renderableplanetprojection.h index c5f2553183..5cc7c6d425 100644 --- a/modules/newhorizons/rendering/renderableplanetprojection.h +++ b/modules/newhorizons/rendering/renderableplanetprojection.h @@ -22,23 +22,19 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERABLEPLANETPROJECTION_H__ -#define __RENDERABLEPLANETPROJECTION_H__ +#ifndef __OPENSPACE_MODULE_NEWHORIZONS___RENDERABLEPLANETPROJECTION___H__ +#define __OPENSPACE_MODULE_NEWHORIZONS___RENDERABLEPLANETPROJECTION___H__ #include + #include -#include - #include -#include -#include - -#include -#include namespace openspace { +struct Image; + namespace planetgeometry { class PlanetGeometry; } @@ -56,6 +52,8 @@ public: void update(const UpdateData& data) override; ghoul::opengl::Texture& baseTexture() const; + static openspace::Documentation Documentation(); + protected: bool loadTextures(); void attitudeParameters(double time); @@ -95,15 +93,14 @@ private: std::vector _imageTimes; - std::string _body; std::string _frame; bool _capture; GLuint _quad; GLuint _vertexPositionBuffer; - }; + } // namespace openspace -#endif // __RENDERABLEPLANETPROJECTION_H__ +#endif // __OPENSPACE_MODULE_NEWHORIZONS___RENDERABLEPLANETPROJECTION___H__ diff --git a/modules/newhorizons/rendering/renderableshadowcylinder.cpp b/modules/newhorizons/rendering/renderableshadowcylinder.cpp index 6e4b9930cd..2c1d588011 100644 --- a/modules/newhorizons/rendering/renderableshadowcylinder.cpp +++ b/modules/newhorizons/rendering/renderableshadowcylinder.cpp @@ -28,6 +28,7 @@ #include #include #include +#include #include @@ -35,13 +36,13 @@ namespace { const std::string _loggerCat = "RenderablePlane"; - const std::string KeyType = "TerminatorType"; - const std::string KeyLightSource = "LightSource"; - const std::string KeyObserver = "Observer"; - const std::string KeyBody = "Body"; - const std::string KeyBodyFrame = "BodyFrame"; - const std::string KeyMainFrame = "MainFrame"; - const std::string KeyAberration = "Aberration"; + const char* KeyType = "TerminatorType"; + const char* KeyLightSource = "LightSource"; + const char* KeyObserver = "Observer"; + const char* KeyBody = "Body"; + const char* KeyBodyFrame = "BodyFrame"; + const char* KeyMainFrame = "MainFrame"; + const char* KeyAberration = "Aberration"; } namespace openspace { @@ -76,7 +77,7 @@ bool RenderableShadowCylinder::initialize() { RenderEngine& renderEngine = OsEng.renderEngine(); _shader = renderEngine.buildRenderProgram( - "ShadowProgram", + "ShadowCylinderProgram", "${MODULE_NEWHORIZONS}/shaders/terminatorshadow_vs.glsl", "${MODULE_NEWHORIZONS}/shaders/terminatorshadow_fs.glsl" ); diff --git a/modules/newhorizons/rendering/renderableshadowcylinder.h b/modules/newhorizons/rendering/renderableshadowcylinder.h index bd05fda49a..8d33d95168 100644 --- a/modules/newhorizons/rendering/renderableshadowcylinder.h +++ b/modules/newhorizons/rendering/renderableshadowcylinder.h @@ -22,14 +22,15 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERABLESHADOWCYLINDER_H__ -#define __RENDERABLESHADOWCYLINDER_H__ +#ifndef __OPENSPACE_MODULE_NEWHORIZONS___RENDERABLESHADOWCYLINDER___H__ +#define __OPENSPACE_MODULE_NEWHORIZONS___RENDERABLESHADOWCYLINDER___H__ #include -#include -#include -#include +#include +#include +#include + #include namespace ghoul { @@ -39,7 +40,10 @@ class ProgramObject; } namespace openspace { - + +struct RenderData; +struct UpdateData; + class RenderableShadowCylinder : public Renderable { public: RenderableShadowCylinder(const ghoul::Dictionary& dictionary); @@ -81,4 +85,4 @@ private: } // namespace openspace -#endif // __RENDERABLESHADOWCYLINDER_H__ +#endif // __OPENSPACE_MODULE_NEWHORIZONS___RENDERABLESHADOWCYLINDER___H__ diff --git a/modules/newhorizons/util/decoder.cpp b/modules/newhorizons/util/decoder.cpp index 74e1c9b87a..76874d7e79 100644 --- a/modules/newhorizons/util/decoder.cpp +++ b/modules/newhorizons/util/decoder.cpp @@ -26,20 +26,15 @@ #include -#include +#include #include -namespace { -const std::string _loggerCat = "Decoder"; -} - namespace openspace { std::unique_ptr Decoder::createFromDictionary( const ghoul::Dictionary& dictionary, const std::string& type) { - ghoul::TemplateFactory* factory - = FactoryManager::ref().factory(); + ghoul::TemplateFactory* factory = FactoryManager::ref().factory(); Decoder* result = factory->create(type, dictionary); if (result == nullptr) { @@ -53,4 +48,4 @@ std::unique_ptr Decoder::createFromDictionary( Decoder::~Decoder() {} -} // namespace openspace \ No newline at end of file +} // namespace openspace diff --git a/modules/newhorizons/util/decoder.h b/modules/newhorizons/util/decoder.h index 700cf06452..dc112edbec 100644 --- a/modules/newhorizons/util/decoder.h +++ b/modules/newhorizons/util/decoder.h @@ -22,12 +22,16 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __DECODER_H__ -#define __DECODER_H__ - -#include +#ifndef __OPENSPACE_MODULE_NEWHORIZONS___DECODER___H__ +#define __OPENSPACE_MODULE_NEWHORIZONS___DECODER___H__ #include +#include +#include + +namespace ghoul { +class Dictionary; +} namespace openspace { @@ -47,4 +51,4 @@ protected: } // namespace openspace -#endif // __DECODER_H__ +#endif // __OPENSPACE_MODULE_NEWHORIZONS___DECODER___H__ diff --git a/modules/newhorizons/util/hongkangparser.cpp b/modules/newhorizons/util/hongkangparser.cpp index bd8a20b7ac..1d0f6fdd83 100644 --- a/modules/newhorizons/util/hongkangparser.cpp +++ b/modules/newhorizons/util/hongkangparser.cpp @@ -27,28 +27,23 @@ #include #include -#include #include #include +#include #include -#include #include -#include -#include -#include - namespace { - const std::string _loggerCat = "HongKangParser"; - const std::string keyTranslation = "DataInputTranslation"; + const char* keyTranslation = "DataInputTranslation"; - const std::string PlaybookIdentifierName = "HongKang"; + const char* PlaybookIdentifierName = "HongKang"; } namespace openspace { -HongKangParser::HongKangParser(std::string name, std::string fileName, + +HongKangParser::HongKangParser(std::string name, std::string fileName, std::string spacecraft, ghoul::Dictionary translationDictionary, std::vector potentialTargets) @@ -91,12 +86,12 @@ void HongKangParser::findPlaybookSpecifiedTarget(std::string line, std::string& std::vector ptarg = _potentialTargets; for (const auto& p : ptarg) { // loop over all targets and determine from 4th col which target this instrument points to - if (line.find(p) != std::string::npos){ + if (line.find(p) != std::string::npos) { target = p; break; } else { - // not found - we set void until we have more info. + // not found - we set void until we have more info. target = "VOID"; } } @@ -105,28 +100,31 @@ void HongKangParser::findPlaybookSpecifiedTarget(std::string line, std::string& bool HongKangParser::create() { //check input for errors. bool hasObserver = SpiceManager::ref().hasNaifId(_spacecraft); - if (!hasObserver){ - LERROR("SPICE navigation system has no pooled observer: '" << _spacecraft << "' in kernel" << - "Please check that all necessary kernels are loaded"<< - "along with correct modfile definition."); - return hasObserver; + if (!hasObserver) { + throw ghoul::RuntimeError( + "SPICE has no observer: '" + _spacecraft + "' in kernel pool", + "HongKangParser" + ); } - if (_potentialTargets.size() == 0){ - LERROR("In order to find targeting from event file user has to provide list of potential targets " - << "please check modfile"); + if (_potentialTargets.size() == 0) { + throw ghoul::RuntimeError( + "List of potential target is missing in order to parse the event file", + "HongKangParser" + ); } if (size_t position = _fileName.find_last_of(".") + 1){ if (position != std::string::npos){ std::string extension = ghoul::filesystem::File(_fileName).fileExtension(); - if (extension == "txt") {// Hong Kang. pre-parsed playbook - LINFO("Using Preparsed Playbook V9H"); - std::ifstream file(_fileName , std::ios::binary); - if (!file.good()){ - LERROR("Failed to open event file '" << _fileName << "'"); - return false; - } + if (extension == "txt") { // Hong Kang. pre-parsed playbook + std::ifstream file; + file.exceptions(std::ofstream::failbit | std::ofstream::badbit); + //std::ifstream file(_fileName , std::ios::binary); + //if (!file.good()){ + // LERROR("Failed to open event file '" << _fileName << "'"); + // return false; + //} std::string line = ""; double shutter = 0.01; @@ -149,7 +147,7 @@ bool HongKangParser::create() { std::string cameraTarget = "VOID"; std::string scannerTarget = "VOID"; - while (!file.eof()){ + while (!file.eof()) { std::getline(file, line); std::string event = line.substr(0, line.find_first_of(" ")); @@ -164,8 +162,8 @@ bool HongKangParser::create() { //store the time, this is used for getNextCaptureTime() _captureProgression.push_back(time); - if (it->second->getDecoderType() == "CAMERA"){ - if (capture_start == -1){ + if (it->second->getDecoderType() == "CAMERA") { + if (capture_start == -1) { //encountered new camera sequence- store start time capture_start = time; previousCamera = it->first; @@ -187,7 +185,7 @@ bool HongKangParser::create() { //createImage(image, time, time + shutter, cameraSpiceID, cameraTarget, _defaultCaptureImage); //IFF spaccraft has decided to switch target, store in target map (used for: 'next observation focus') - if (previousTarget != image.target){ + if (previousTarget != image.target) { previousTarget = image.target; std::pair v_target = std::make_pair(time, image.target); _targetTimes.push_back(v_target); @@ -198,7 +196,7 @@ bool HongKangParser::create() { //compute and store the range for each subset _subsetMap[image.target]._range.include(time); } - if (it->second->getDecoderType() == "SCANNER"){ // SCANNER START + if (it->second->getDecoderType() == "SCANNER") { // SCANNER START scan_start = time; InstrumentDecoder* scanner = static_cast(it->second.get()); @@ -208,10 +206,10 @@ bool HongKangParser::create() { std::streampos len = file.tellg(); std::string linePeek; bool foundstop = false; - while (!file.eof() && !foundstop){ + while (!file.eof() && !foundstop) { //continue grabbing next line until we find what we need getline(file, linePeek); - if (linePeek.find(endNominal) != std::string::npos){ + if (linePeek.find(endNominal) != std::string::npos) { foundstop = true; met = linePeek.substr(25, 9); @@ -240,8 +238,8 @@ bool HongKangParser::create() { file.seekg(len, std::ios_base::beg); } } - else{ // we have reached the end of a scan or consecutive capture sequence! - if (capture_start != -1){ + else { // we have reached the end of a scan or consecutive capture sequence! + if (capture_start != -1) { //end of capture sequence for camera, store end time of this sequence capture_stop = time; cameraRange = { capture_start, capture_stop }; @@ -256,13 +254,11 @@ bool HongKangParser::create() { } } - sendPlaybookInformation(PlaybookIdentifierName); return true; } -bool HongKangParser::augmentWithSpice(Image& image, - std::string spacecraft, +bool HongKangParser::augmentWithSpice(Image& image, std::string spacecraft, std::vector payload, std::vector potentialTargets) { @@ -280,7 +276,7 @@ bool HongKangParser::augmentWithSpice(Image& image, bool _withinFOV = false; for (int j = 0; j < image.activeInstruments.size(); ++j) { double time = image.timeRange.start; - for (int k = 0; k < exposureTime; k++){ + for (int k = 0; k < exposureTime; k++) { time += k; _withinFOV = SpiceManager::ref().isTargetInFieldOfView( potentialTargets[i], @@ -301,54 +297,34 @@ bool HongKangParser::augmentWithSpice(Image& image, return false; } -//Image HongKangParser::createImage(double startTime, double stopTime, std::vector instr, std::string targ, std::string path) { -// image.startTime = startTime; -// image.stopTime = stopTime; -// image.path = path; -// for (int i = 0; i < instr.size(); i++){ -// image.activeInstruments.push_back(instr[i]); -// } -// image.target = targ; -// image.projected = false; -// image.isPlaceholder = true; -//} - -double HongKangParser::getETfromMet(std::string line){ +double HongKangParser::getETfromMet(std::string line) { std::string::size_type sz; return getETfromMet(std::stod(line, &sz)); } -double HongKangParser::getETfromMet(double met){ - double diff; - double referenceET = +double HongKangParser::getETfromMet(double met) { + const double referenceET = SpiceManager::ref().ephemerisTimeFromDate("2015-07-14T11:50:00.00"); - double et = referenceET; //_metRef += 3; // MET reference time is off by 3 sec? - diff = std::abs(met - _metRef); - if (met > _metRef){ - et = referenceET + diff; - } else if (met < _metRef){ - et = referenceET - diff; + const double diff = std::abs(met - _metRef); + if (met > _metRef) { + return referenceET + diff; + } else if (met < _metRef) { + return referenceET - diff; } - return et; } - -double HongKangParser::getMetFromET(double et){ - double met; - double referenceET = +double HongKangParser::getMetFromET(double et) { + const double referenceET = SpiceManager::ref().ephemerisTimeFromDate("2015-07-14T11:50:00.00"); - if (et >= referenceET){ - met = _metRef + (et - referenceET); - }else{ - met = _metRef - (referenceET - et); + if (et >= referenceET) { + return _metRef + (et - referenceET); + }else { + return _metRef - (referenceET - et); } - - return met; } - -} \ No newline at end of file +} // namespace openspace \ No newline at end of file diff --git a/modules/newhorizons/util/hongkangparser.h b/modules/newhorizons/util/hongkangparser.h index a1959c923e..d8ba56ba30 100644 --- a/modules/newhorizons/util/hongkangparser.h +++ b/modules/newhorizons/util/hongkangparser.h @@ -1,48 +1,39 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __HONGKANGPARSER_H__ -#define __HONGKANGPARSER_H__ +#ifndef __OPENSPACE_MODULE_NEWHORIZONS___HONGKANGPARSER___H__ +#define __OPENSPACE_MODULE_NEWHORIZONS___HONGKANGPARSER___H__ -#include #include -#include - -#include -#include -#include - namespace openspace { class HongKangParser : public SequenceParser { public: HongKangParser(); - HongKangParser(std::string name, std::string fileName, - std::string spacecraft, - ghoul::Dictionary dictionary, - std::vector potentialTargets); + HongKangParser(std::string name, std::string fileName, std::string spacecraft, + ghoul::Dictionary dictionary, std::vector potentialTargets); bool create() override; void findPlaybookSpecifiedTarget(std::string line, std::string& target); @@ -52,16 +43,8 @@ private: double getETfromMet(std::string timestr); double getETfromMet(double met); - //Image createImage(double startTime, - // double stopTime, - // std::vector instr, - // std::string targ, - // std::string pot); - - bool augmentWithSpice(Image& image, - std::string spacecraft, - std::vector payload, - std::vector potentialTargets); + bool augmentWithSpice(Image& image, std::string spacecraft, + std::vector payload, std::vector potentialTargets); std::string _defaultCaptureImage; double _metRef = 299180517; @@ -73,5 +56,6 @@ private: std::vector _potentialTargets; }; -} -#endif //__HONGKANGPARSER_H__ +} // namespace openspace + +#endif //__OPENSPACE_MODULE_NEWHORIZONS___HONGKANGPARSER___H__ diff --git a/modules/newhorizons/util/imagesequencer.cpp b/modules/newhorizons/util/imagesequencer.cpp index e5e1f5233e..641d171fe5 100644 --- a/modules/newhorizons/util/imagesequencer.cpp +++ b/modules/newhorizons/util/imagesequencer.cpp @@ -23,6 +23,7 @@ ****************************************************************************************/ #include + #include #include #include @@ -30,14 +31,23 @@ #include #include +#include #include #include #include #include #include +#include +#include +#include +#include +#include +#include +#include + namespace { -const std::string _loggerCat = "ImageSequencer"; + const std::string _loggerCat = "ImageSequencer"; } namespace openspace { @@ -53,13 +63,14 @@ ImageSequencer::ImageSequencer() {} ImageSequencer& ImageSequencer::ref() { - assert(_instance != nullptr); + ghoul_assert(_instance != nullptr, "Instance has not been initialized"); return *_instance; } void ImageSequencer::initialize() { - assert(_instance == nullptr); + ghoul_assert(_instance == nullptr, "Instance already has been initialized"); _instance = new ImageSequencer; - _instance->_defaultCaptureImage = absPath("${OPENSPACE_DATA}/scene/common/textures/placeholder_blank.png"); + _instance->_defaultCaptureImage = + absPath("${OPENSPACE_DATA}/scene/common/textures/placeholder_blank.png"); } void ImageSequencer::deinitialize() { @@ -89,12 +100,19 @@ std::pair ImageSequencer::getNextTarget() { }; std::pair findEqualToThis; findEqualToThis.first = _currentTime; - auto it = std::lower_bound(_targetTimes.begin(), _targetTimes.end(), findEqualToThis, compareTime); + auto it = std::lower_bound( + _targetTimes.begin(), + _targetTimes.end(), + findEqualToThis, + compareTime + ); - if (it != _targetTimes.end() && it != _targetTimes.begin()) + if (it != _targetTimes.end() && it != _targetTimes.begin()) { return (*it); - else - return std::make_pair(0.0, ""); + } + else { + return { 0.0, "" }; + } } std::pair ImageSequencer::getCurrentTarget() { @@ -104,26 +122,39 @@ std::pair ImageSequencer::getCurrentTarget() { }; std::pair findEqualToThis; findEqualToThis.first = _currentTime; - auto it = std::lower_bound(_targetTimes.begin(), _targetTimes.end(), findEqualToThis, compareTime); + auto it = std::lower_bound( + _targetTimes.begin(), + _targetTimes.end(), + findEqualToThis, + compareTime + ); if (it != _targetTimes.end() && it != _targetTimes.begin()){ - return *std::prev(it); + return *(std::prev(it)); } else - return std::make_pair(0.0, "No Target"); + return { 0.0, "No Target" }; } -std::pair> ImageSequencer::getIncidentTargetList(int range) { +std::pair> ImageSequencer::getIncidentTargetList( + int range) +{ std::pair> incidentTargets; - auto compareTime = [](const std::pair &a, - const std::pair &b)->bool{ + auto compareTime = [](const std::pair& a, + const std::pair& b) -> bool { return a.first < b.first; }; + // what to look for std::pair findEqualToThis; findEqualToThis.first = _currentTime; - auto it = std::lower_bound(_targetTimes.begin(), _targetTimes.end(), findEqualToThis, compareTime); + auto it = std::lower_bound( + _targetTimes.begin(), + _targetTimes.end(), + findEqualToThis, + compareTime + ); if (it != _targetTimes.end() && it != _targetTimes.begin()){ // move the iterator to the first element of the range @@ -134,17 +165,18 @@ std::pair> ImageSequencer::getIncidentTargetLis incidentTargets.first = it->first; incidentTargets.second.push_back(it->second); it++; - if (it == _targetTimes.end()) + if (it == _targetTimes.end()) { break; + } } } return incidentTargets; } -double ImageSequencer::getIntervalLength(){ +double ImageSequencer::getIntervalLength() { double upcoming = getNextCaptureTime(); - if (_nextCapture != upcoming){ + if (_nextCapture != upcoming) { _nextCapture = upcoming; _intervalLength = upcoming - _currentTime; } @@ -152,46 +184,56 @@ double ImageSequencer::getIntervalLength(){ } double ImageSequencer::getNextCaptureTime(){ - auto compareTime = [](const double &a, const double &b)->bool{ + auto compareTime = [](const double &a, const double &b) -> bool { return a < b; }; double nextCaptureTime = 0; - auto it = std::lower_bound(_captureProgression.begin(), _captureProgression.end(), _currentTime, compareTime); - if (it != _captureProgression.end()) + auto it = std::lower_bound( + _captureProgression.begin(), + _captureProgression.end(), + _currentTime, + compareTime + ); + if (it != _captureProgression.end()) { nextCaptureTime = *it; + } return nextCaptureTime; } -Image ImageSequencer::getLatestImageForInstrument(const std::string& _instrumentID){ + +Image ImageSequencer::getLatestImageForInstrument(const std::string& _instrumentID) { auto it = _latestImages.find(_instrumentID); - if (it != _latestImages.end()) + if (it != _latestImages.end()) { return _latestImages[_instrumentID]; + } else { return Image(); } } -std::map ImageSequencer::getActiveInstruments(){ +std::map ImageSequencer::getActiveInstruments() { // first set all instruments to off - for (auto i : _switchingMap) + for (const auto& i : _switchingMap) { _switchingMap[i.first] = false; + } + // go over the filetranslation map - for (const auto &key : _fileTranslation){ + for (const auto& key : _fileTranslation) { // for each spice-instrument - for (const auto &instrumentID : key.second->getTranslation()){ + for (const auto& instrumentID : key.second->getTranslation()) { // check if the spice-instrument is active - if (instrumentActive(instrumentID)){ - // go over switching map - for (const auto &instrument : _switchingMap){ - // if instrument is present in switching map - if (instrumentID == instrument.first){ - // set as active - _switchingMap[instrumentID] = true; - } + if (instrumentActive(instrumentID)) { + // go over switching map + for (const auto& instrument : _switchingMap) { + // if instrument is present in switching map + if (instrumentID == instrument.first) { + // set as active + _switchingMap[instrumentID] = true; } } } } + } // return entire map, seen in GUI. return _switchingMap; } @@ -203,7 +245,7 @@ bool ImageSequencer::instrumentActive(std::string instrumentID) { //if so, then get the corresponding spiceID std::vector spiceIDs = _fileTranslation[i.first]->getTranslation(); //check which specific subinstrument is firing - for (auto s : spiceIDs) { + for (const auto& s : spiceIDs) { if (s == instrumentID) { return true; } diff --git a/modules/newhorizons/util/imagesequencer.h b/modules/newhorizons/util/imagesequencer.h index 4729dab641..3b4c85a28a 100644 --- a/modules/newhorizons/util/imagesequencer.h +++ b/modules/newhorizons/util/imagesequencer.h @@ -22,36 +22,33 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __IMAGESEQUENCER_H__ -#define __IMAGESEQUENCER_H__ - -// open space includes -#include -#include -#include -#include -#include -#include -#include - +#ifndef __OPENSPACE_MODULE_NEWHORIZONS___IMAGESEQUENCER___H__ +#define __OPENSPACE_MODULE_NEWHORIZONS___IMAGESEQUENCER___H__ #include +#include +#include +#include +#include namespace openspace { - /** - * The ImageSequencer singleton main function is to manage the timekeeping and - * distribution of large image data-sets across all openspace renderable instances, - * both for past and future unmanned-spacecraft missions. To load the instance with - * data the client must provide a parser inherited from the abstract base class - * SequenceParser. Hence, there is no restriction imposed on data input, whether its - * data in the form of existing images or in the form of a planned observation schedule. - * Notably, in order for the sequencer to function the client must provide or write a - * parser that fills the ImageSequencers private members. - * \see SequenceParser - * \see ImageSequencer::runSequenceParser(SequenceParser* parser) - * std::map - */ + +class SequenceParser; + +/** +* The ImageSequencer singleton main function is to manage the timekeeping and +* distribution of large image data-sets across all openspace renderable instances, +* both for past and future unmanned-spacecraft missions. To load the instance with +* data the client must provide a parser inherited from the abstract base class +* SequenceParser. Hence, there is no restriction imposed on data input, whether its +* data in the form of existing images or in the form of a planned observation schedule. +* Notably, in order for the sequencer to function the client must provide or write a +* parser that fills the ImageSequencers private members. +* \see SequenceParser +* \see ImageSequencer::runSequenceParser(SequenceParser* parser) +* std::map +*/ class ImageSequencer { public: ImageSequencer(); @@ -204,6 +201,4 @@ private: } // namespace openspace - -#endif // __IMAGESEQUENCER_H__ - +#endif // __OPENSPACE_MODULE_NEWHORIZONS___IMAGESEQUENCER___H__ diff --git a/modules/newhorizons/util/instrumentdecoder.cpp b/modules/newhorizons/util/instrumentdecoder.cpp index b575f0cf32..3f6b168c09 100644 --- a/modules/newhorizons/util/instrumentdecoder.cpp +++ b/modules/newhorizons/util/instrumentdecoder.cpp @@ -26,12 +26,12 @@ #include #include - +#include namespace { const std::string _loggerCat = "InstrumentDecoder"; - const std::string keyDetector = "DetectorType"; - const std::string keySpice = "Spice"; - const std::string keyStopCommand = "StopCommand"; + const char* keyDetector = "DetectorType"; + const char* keySpice = "Spice"; + const char* keyStopCommand = "StopCommand"; } namespace openspace { diff --git a/modules/newhorizons/util/instrumentdecoder.h b/modules/newhorizons/util/instrumentdecoder.h index 1f4a22482e..a8c871bd60 100644 --- a/modules/newhorizons/util/instrumentdecoder.h +++ b/modules/newhorizons/util/instrumentdecoder.h @@ -22,13 +22,11 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __INSTRUMENTDECODER_H__ -#define __INSTRUMENTDECODER_H__ +#ifndef __OPENSPACE_MODULE_NEWHORIZONS___INSTRUMENTDECODER___H__ +#define __OPENSPACE_MODULE_NEWHORIZONS___INSTRUMENTDECODER___H__ #include -#include - namespace openspace { class InstrumentDecoder : public Decoder { @@ -45,4 +43,4 @@ private: } // namespace openspace -#endif // __INSTRUMENTDECODER_H__ +#endif // __OPENSPACE_MODULE_NEWHORIZONS___INSTRUMENTDECODER___H__ diff --git a/modules/newhorizons/util/instrumenttimesparser.cpp b/modules/newhorizons/util/instrumenttimesparser.cpp index 92765eb190..f36fe308e5 100644 --- a/modules/newhorizons/util/instrumenttimesparser.cpp +++ b/modules/newhorizons/util/instrumenttimesparser.cpp @@ -36,14 +36,22 @@ #include #include +#include + +#include + +#include +#include +#include + namespace { const std::string _loggerCat = "InstrumentTimesParser"; - const std::string PlaybookIdentifierName = "InstrumentTimesParser"; - const std::string KeyTargetBody = "Target.Body"; - const std::string KeyInstruments = "Instruments"; - const std::string KeyInstrument = "Instrument"; - const std::string KeyInstrumentFiles = "Files"; + const char* PlaybookIdentifierName = "InstrumentTimesParser"; + const char* KeyTargetBody = "Target.Body"; + const char* KeyInstruments = "Instruments"; + const char* KeyInstrument = "Instrument"; + const char* KeyInstrumentFiles = "Files"; } namespace openspace { diff --git a/modules/newhorizons/util/instrumenttimesparser.h b/modules/newhorizons/util/instrumenttimesparser.h index 86f4e6648e..30f3ab2372 100644 --- a/modules/newhorizons/util/instrumenttimesparser.h +++ b/modules/newhorizons/util/instrumenttimesparser.h @@ -1,42 +1,37 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __INSTRUMENTTIMESPARSER_H__ -#define __INSTRUMENTTIMESPARSER_H__ +#ifndef __OPENSPACE_MODULE_NEWHORIZONS___INSTRUMENTTIMESPARSER___H__ +#define __OPENSPACE_MODULE_NEWHORIZONS___INSTRUMENTTIMESPARSER___H__ -#include #include -#include - -#include -#include -#include #include namespace openspace { -class InstrumentTimesParser : public SequenceParser{ + +class InstrumentTimesParser : public SequenceParser { public: InstrumentTimesParser( const std::string& name, @@ -61,5 +56,7 @@ private: std::string _sequenceID; bool _badDecoding; }; -} -#endif //__INSTRUMENTTIMESPARSER_H__ \ No newline at end of file + +} // namespace openspace + +#endif //__OPENSPACE_MODULE_NEWHORIZONS___INSTRUMENTTIMESPARSER___H__ diff --git a/modules/newhorizons/util/labelparser.cpp b/modules/newhorizons/util/labelparser.cpp index bccdb49ff6..aee435c75c 100644 --- a/modules/newhorizons/util/labelparser.cpp +++ b/modules/newhorizons/util/labelparser.cpp @@ -39,13 +39,18 @@ #include #include +#include + +#include +#include +#include namespace { const std::string _loggerCat = "LabelParser"; - const std::string keySpecs = "Read"; - const std::string keyConvert = "Convert"; + const char* keySpecs = "Read"; + const char* keyConvert = "Convert"; - const std::string PlaybookIdentifierName = "LabelParser"; + const char* PlaybookIdentifierName = "LabelParser"; } namespace openspace { diff --git a/modules/newhorizons/util/labelparser.h b/modules/newhorizons/util/labelparser.h index a65eaf1543..6d914dce77 100644 --- a/modules/newhorizons/util/labelparser.h +++ b/modules/newhorizons/util/labelparser.h @@ -1,36 +1,32 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __LABELPARSER_H__ -#define __LABELPARSER_H__ +#ifndef __OPENSPACE_MODULE_NEWHORIZONS___LABELPARSER___H__ +#define __OPENSPACE_MODULE_NEWHORIZONS___LABELPARSER___H__ -#include #include -#include -#include -#include namespace openspace { class LabelParser : public SequenceParser{ @@ -73,5 +69,7 @@ private: std::string _sequenceID; bool _badDecoding; }; -} -#endif //__LABELPARSER_H__ + +} // namespace openspace + +#endif //__OPENSPACE_MODULE_NEWHORIZONS___LABELPARSER___H__ diff --git a/modules/newhorizons/util/projectioncomponent.cpp b/modules/newhorizons/util/projectioncomponent.cpp index 21a36cbd61..bb4a7b8d64 100644 --- a/modules/newhorizons/util/projectioncomponent.cpp +++ b/modules/newhorizons/util/projectioncomponent.cpp @@ -29,42 +29,46 @@ #include #include +#include #include #include #include +#include #include #include +#include #include namespace { - const std::string keyPotentialTargets = "PotentialTargets"; + const char* keyPotentialTargets = "PotentialTargets"; - const std::string keyInstrument = "Instrument.Name"; - const std::string keyInstrumentFovy = "Instrument.Fovy"; - const std::string keyInstrumentAspect = "Instrument.Aspect"; + const char* keyInstrument = "Instrument.Name"; + const char* keyInstrumentFovy = "Instrument.Fovy"; + const char* keyInstrumentAspect = "Instrument.Aspect"; - const std::string keyProjObserver = "Projection.Observer"; - const std::string keyProjTarget = "Projection.Target"; - const std::string keyProjAberration = "Projection.Aberration"; + const char* keyTranslation = "DataInputTranslation"; - const std::string keySequenceDir = "Projection.Sequence"; - const std::string keySequenceType = "Projection.SequenceType"; - const std::string keyTranslation = "DataInputTranslation"; + const char* keyProjObserver = "Observer"; + const char* keyProjTarget = "Target"; + const char* keyProjAberration = "Aberration"; - const std::string keyNeedsTextureMapDilation = "Projection.TextureMap"; - const std::string keyNeedsShadowing = "Projection.ShadowMap"; - const std::string keyTextureMapAspectRatio = "Projection.AspectRatio"; + const char* keySequenceDir = "Sequence"; + const char* keySequenceType = "SequenceType"; - const std::string sequenceTypeImage = "image-sequence"; - const std::string sequenceTypePlaybook = "playbook"; - const std::string sequenceTypeHybrid = "hybrid"; - const std::string sequenceTypeInstrumentTimes = "instrument-times"; + const char* keyNeedsTextureMapDilation = "TextureMap"; + const char* keyNeedsShadowing = "ShadowMap"; + const char* keyTextureMapAspectRatio = "AspectRatio"; - const std::string placeholderFile = + const char* sequenceTypeImage = "image-sequence"; + const char* sequenceTypePlaybook = "playbook"; + const char* sequenceTypeHybrid = "hybrid"; + const char* sequenceTypeInstrumentTimes = "instrument-times"; + + const char* placeholderFile = "${OPENSPACE_DATA}/scene/common/textures/placeholder.png"; - const std::string _loggerCat = "ProjectionComponent"; + const char* _loggerCat = "ProjectionComponent"; } namespace openspace { @@ -72,6 +76,94 @@ namespace openspace { using ghoul::Dictionary; using glm::ivec2; +Documentation ProjectionComponent::Documentation() { + using namespace documentation; + return { + "Projection Component", + "newhorizons_projectioncomponent", + { + { + keyInstrument, + new StringAnnotationVerifier("A SPICE name of an instrument"), + "The instrument that is used to perform the projections", + Optional::No + }, + { + keyInstrumentFovy, + new DoubleVerifier, + "The field of view in degrees along the y axis", + Optional::No + }, + { + keyInstrumentAspect, + new DoubleVerifier, + "The aspect ratio of the instrument in relation between x and y axis", + Optional::No + }, + { + keyProjObserver, + new StringAnnotationVerifier("A SPICE name of the observing object"), + "The observer that is doing the projection. This has to be a valid SPICE " + "name or SPICE integer.", + Optional::No + }, + { + keyProjTarget, + new StringAnnotationVerifier("A SPICE name of the observed object"), + "The observed object that is projected on. This has to be a valid SPICE " + "name or SPICE integer.", + Optional::No + }, + { + keyProjAberration, + new StringInListVerifier({ + // from SpiceManager::AberrationCorrection::AberrationCorrection + "NONE", "LT", "LT+S", "CN", "CN+S", "XLT", "XLT+S", "XCN", "XCN+S" + }), + "The aberration correction that is supposed to be used for the " + "projection. The values for the correction correspond to the SPICE " + "definition as described in " + "ftp://naif.jpl.nasa.gov/pub/naif/toolkit_docs/IDL/cspice/spkezr_c.html", + Optional::No + }, + { + keyPotentialTargets, + new StringListVerifier, + "The list of potential targets that are involved with the image " + "projection", + Optional::Yes + }, + { + keyNeedsTextureMapDilation, + new BoolVerifier, + "Determines whether a dilation step of the texture map has to be " + "performed after each projection. This is necessary if the texture of " + "the projected object is a texture map where the borders are not " + "touching. The default value is 'false'.", + Optional::Yes + }, + { + keyNeedsShadowing, + new BoolVerifier, + "Determines whether the object requires a self-shadowing algorithm. This " + "is necessary if the object is concave and might cast a shadow on itself " + "during presentation. The default value is 'false'.", + Optional::Yes + }, + { + keyTextureMapAspectRatio, + new DoubleVerifier, + "Sets the desired aspect ratio of the projected texture. This might be " + "necessary as planets usually have 2x1 aspect ratios, whereas this does " + "not hold for non-planet objects (comets, asteroids, etc). The default " + "value is '1.0'.", + Optional::Yes + } + + } + }; +} + ProjectionComponent::ProjectionComponent() : properties::PropertyOwner() , _performProjection("performProjection", "Perform Projections", true) @@ -96,7 +188,123 @@ ProjectionComponent::ProjectionComponent() _applyTextureSize.onChange([this]() { _textureSizeDirty = true; }); } -bool ProjectionComponent::initialize() { +void ProjectionComponent::initialize(const ghoul::Dictionary& dictionary) { + documentation::testSpecificationAndThrow( + Documentation(), + dictionary, + "ProjectionComponent" + ); + _instrumentID = dictionary.value(keyInstrument); + _projectorID = dictionary.value(keyProjObserver); + _projecteeID = dictionary.value(keyProjTarget); + _fovy = dictionary.value(keyInstrumentFovy); + _aspectRatio = dictionary.value(keyInstrumentAspect); + + _aberration = SpiceManager::AberrationCorrection( + dictionary.value(keyProjAberration) + ); + + if (dictionary.hasKeyAndValue(keyPotentialTargets)) { + ghoul::Dictionary potentialTargets = dictionary.value( + keyPotentialTargets + ); + + _potentialTargets.reserve(potentialTargets.size()); + for (int i = 1; i <= potentialTargets.size(); ++i) { + _potentialTargets.emplace_back( + potentialTargets.value(std::to_string(i)) + ); + } + } + + if (dictionary.hasKeyAndValue(keyNeedsTextureMapDilation)) { + _dilation.isEnabled = dictionary.value(keyNeedsTextureMapDilation); + } + + if (dictionary.hasKeyAndValue(keyNeedsShadowing)) { + _shadowing.isEnabled = dictionary.value(keyNeedsShadowing); + } + + _projectionTextureAspectRatio = 1.f; + if (dictionary.hasKeyAndValue(keyTextureMapAspectRatio)) { + _projectionTextureAspectRatio = + static_cast(dictionary.value(keyTextureMapAspectRatio)); + } + + std::string name; + dictionary.getValue(SceneGraphNode::KeyName, name); + + std::vector parsers; + + std::string sequenceSource; + std::string sequenceType; + bool foundSequence = dictionary.getValue(keySequenceDir, sequenceSource); + if (foundSequence) { + sequenceSource = absPath(sequenceSource); + + foundSequence = dictionary.getValue(keySequenceType, sequenceType); + //Important: client must define translation-list in mod file IFF playbook + if (dictionary.hasKey(keyTranslation)) { + ghoul::Dictionary translationDictionary; + //get translation dictionary + dictionary.getValue(keyTranslation, translationDictionary); + + if (sequenceType == sequenceTypePlaybook) { + parsers.push_back(new HongKangParser( + name, + sequenceSource, + _projectorID, + translationDictionary, + _potentialTargets)); + } + else if (sequenceType == sequenceTypeImage) { + parsers.push_back(new LabelParser( + name, + sequenceSource, + translationDictionary)); + } + else if (sequenceType == sequenceTypeHybrid) { + //first read labels + parsers.push_back(new LabelParser( + name, + sequenceSource, + translationDictionary)); + + std::string _eventFile; + bool foundEventFile = dictionary.getValue("Projection.EventFile", _eventFile); + if (foundEventFile) { + //then read playbook + _eventFile = absPath(_eventFile); + parsers.push_back(new HongKangParser( + name, + _eventFile, + _projectorID, + translationDictionary, + _potentialTargets)); + } + else { + LWARNING("No eventfile has been provided, please check modfiles"); + } + } + else if (sequenceType == sequenceTypeInstrumentTimes) { + parsers.push_back(new InstrumentTimesParser( + name, + sequenceSource, + translationDictionary)); + } + + for (SequenceParser* parser : parsers) { + openspace::ImageSequencer::ref().runSequenceParser(parser); + delete parser; + } + } + else { + LWARNING("No playbook translation provided, please make sure all spice calls match playbook!"); + } + } +} + +bool ProjectionComponent::initializeGL() { int maxSize = OpenGLCap.max2DTextureSize(); glm::ivec2 size; @@ -193,131 +401,6 @@ bool ProjectionComponent::isReady() const { return (_projectionTexture != nullptr); } -bool ProjectionComponent::initializeProjectionSettings(const Dictionary& dictionary) { - bool completeSuccess = true; - completeSuccess &= dictionary.getValue(keyInstrument, _instrumentID); - completeSuccess &= dictionary.getValue(keyProjObserver, _projectorID); - completeSuccess &= dictionary.getValue(keyProjTarget, _projecteeID); - completeSuccess &= dictionary.getValue(keyInstrumentFovy, _fovy); - completeSuccess &= dictionary.getValue(keyInstrumentAspect, _aspectRatio); - - ghoul_assert(completeSuccess, "All neccessary attributes not found in modfile"); - - std::string a = "NONE"; - bool s = dictionary.getValue(keyProjAberration, a); - _aberration = SpiceManager::AberrationCorrection(a); - completeSuccess &= s; - ghoul_assert(completeSuccess, "All neccessary attributes not found in modfile"); - - - if (dictionary.hasKeyAndValue(keyPotentialTargets)) { - ghoul::Dictionary potentialTargets = dictionary.value( - keyPotentialTargets - ); - - _potentialTargets.resize(potentialTargets.size()); - for (int i = 0; i < potentialTargets.size(); ++i) { - std::string target; - potentialTargets.getValue(std::to_string(i + 1), target); - _potentialTargets[i] = target; - } - } - - if (dictionary.hasKeyAndValue(keyNeedsTextureMapDilation)) { - _dilation.isEnabled = dictionary.value(keyNeedsTextureMapDilation); - } - - if (dictionary.hasKeyAndValue(keyNeedsShadowing)) { - _shadowing.isEnabled = dictionary.value(keyNeedsShadowing); - } - - _projectionTextureAspectRatio = 1.f; - if (dictionary.hasKeyAndValue(keyTextureMapAspectRatio)) { - _projectionTextureAspectRatio = - static_cast(dictionary.value(keyTextureMapAspectRatio)); - } - - return completeSuccess; -} - -bool ProjectionComponent::initializeParser(const ghoul::Dictionary& dictionary) { - bool completeSuccess = true; - - std::string name; - dictionary.getValue(SceneGraphNode::KeyName, name); - - std::vector parsers; - - std::string sequenceSource; - std::string sequenceType; - bool foundSequence = dictionary.getValue(keySequenceDir, sequenceSource); - if (foundSequence) { - sequenceSource = absPath(sequenceSource); - - foundSequence = dictionary.getValue(keySequenceType, sequenceType); - //Important: client must define translation-list in mod file IFF playbook - if (dictionary.hasKey(keyTranslation)) { - ghoul::Dictionary translationDictionary; - //get translation dictionary - dictionary.getValue(keyTranslation, translationDictionary); - - if (sequenceType == sequenceTypePlaybook) { - parsers.push_back(new HongKangParser( - name, - sequenceSource, - _projectorID, - translationDictionary, - _potentialTargets)); - } - else if (sequenceType == sequenceTypeImage) { - parsers.push_back(new LabelParser( - name, - sequenceSource, - translationDictionary)); - } - else if (sequenceType == sequenceTypeHybrid) { - //first read labels - parsers.push_back(new LabelParser( - name, - sequenceSource, - translationDictionary)); - - std::string _eventFile; - bool foundEventFile = dictionary.getValue("Projection.EventFile", _eventFile); - if (foundEventFile) { - //then read playbook - _eventFile = absPath(_eventFile); - parsers.push_back(new HongKangParser( - name, - _eventFile, - _projectorID, - translationDictionary, - _potentialTargets)); - } - else { - LWARNING("No eventfile has been provided, please check modfiles"); - } - } - else if (sequenceType == sequenceTypeInstrumentTimes) { - parsers.push_back(new InstrumentTimesParser( - name, - sequenceSource, - translationDictionary)); - } - - for(SequenceParser* parser : parsers){ - openspace::ImageSequencer::ref().runSequenceParser(parser); - delete parser; - } - } - else { - LWARNING("No playbook translation provided, please make sure all spice calls match playbook!"); - } - } - - return completeSuccess; -} - void ProjectionComponent::imageProjectBegin() { // keep handle to the current bound FBO glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_defaultFBO); @@ -793,7 +876,7 @@ std::shared_ptr ProjectionComponent::loadProjectionTextu unique_ptr texture = TextureReader::ref().loadTexture(absPath(texturePath)); if (texture) { if (texture->format() == Texture::Format::Red) - ghoul::opengl::convertTextureFormat(ghoul::opengl::Texture::Format::RGB, *texture); + ghoul::opengl::convertTextureFormat(*texture, Texture::Format::RGB); texture->uploadTexture(); // TODO: AnisotropicMipMap crashes on ATI cards ---abock //_textureProj->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); diff --git a/modules/newhorizons/util/projectioncomponent.h b/modules/newhorizons/util/projectioncomponent.h index 6bae9afa6f..6d82b6d0c2 100644 --- a/modules/newhorizons/util/projectioncomponent.h +++ b/modules/newhorizons/util/projectioncomponent.h @@ -22,19 +22,25 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __PROJECTIONCOMPONENT_H__ -#define __PROJECTIONCOMPONENT_H__ +#ifndef __OPENSPACE_MODULE_NEWHORIZONS___PROJECTIONCOMPONENT___H__ +#define __OPENSPACE_MODULE_NEWHORIZONS___PROJECTIONCOMPONENT___H__ #include -#include + +#include #include -#include +#include +#include +#include +#include #include -#include #include namespace ghoul { + +class Dictionary; + namespace opengl { class ProgramObject; @@ -48,14 +54,12 @@ class ProjectionComponent : public properties::PropertyOwner { public: ProjectionComponent(); - bool initialize(); + void initialize(const ghoul::Dictionary& dictionary); + bool initializeGL(); bool deinitialize(); bool isReady() const; - bool initializeProjectionSettings(const ghoul::Dictionary& dictionary); - bool initializeParser(const ghoul::Dictionary& dictionary); - ghoul::opengl::Texture& depthTexture(); void imageProjectBegin(); void imageProjectEnd(); @@ -101,6 +105,8 @@ public: float fieldOfViewY() const; float aspectRatio() const; + static openspace::Documentation Documentation(); + private: bool generateProjectionLayerTexture(const glm::ivec2& size); bool generateDepthTexture(const glm::ivec2& size); @@ -151,4 +157,4 @@ protected: } // namespace openspace -#endif // __PROJECTIONCOMPONENT_H__ +#endif // __OPENSPACE_MODULE_NEWHORIZONS___PROJECTIONCOMPONENT___H__ diff --git a/modules/newhorizons/util/scannerdecoder.cpp b/modules/newhorizons/util/scannerdecoder.cpp index aae509a0a9..c1aaa49c80 100644 --- a/modules/newhorizons/util/scannerdecoder.cpp +++ b/modules/newhorizons/util/scannerdecoder.cpp @@ -24,6 +24,8 @@ #include +#include + namespace { const std::string _loggerCat = "ScannerDecoder"; } diff --git a/modules/newhorizons/util/scannerdecoder.h b/modules/newhorizons/util/scannerdecoder.h index 0a2b11f2a4..bd593ff691 100644 --- a/modules/newhorizons/util/scannerdecoder.h +++ b/modules/newhorizons/util/scannerdecoder.h @@ -22,11 +22,10 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SCANNERDECODER_H__ -#define __SCANNERDECODER_H__ +#ifndef __OPENSPACE_MODULE_NEWHORIZONS___SCANNERDECODER___H__ +#define __OPENSPACE_MODULE_NEWHORIZONS___SCANNERDECODER___H__ #include -#include namespace openspace { @@ -45,4 +44,4 @@ private: } // namespace openspace -#endif // __SCANNERDECODER_H__ +#endif // __OPENSPACE_MODULE_NEWHORIZONS___SCANNERDECODER___H__ diff --git a/modules/newhorizons/util/sequenceparser.cpp b/modules/newhorizons/util/sequenceparser.cpp index 6e36361fa6..65d05b64d8 100644 --- a/modules/newhorizons/util/sequenceparser.cpp +++ b/modules/newhorizons/util/sequenceparser.cpp @@ -26,15 +26,14 @@ #include #include -#include #include namespace { const std::string _loggerCat = "SequenceParser"; - const std::string keyTranslation = "DataInputTranslation"; + const char* keyTranslation = "DataInputTranslation"; - const std::string PlaybookIdentifierName = "Playbook"; + const char* PlaybookIdentifierName = "Playbook"; } namespace openspace { @@ -79,7 +78,7 @@ void writeToBuffer(std::vector& buffer, size_t& currentWriteL } void SequenceParser::sendPlaybookInformation(const std::string& name) { - std::string fullName = PlaybookIdentifierName + "_" + name; + std::string fullName = std::string(PlaybookIdentifierName) + "_" + name; _messageIdentifier = OsEng.networkEngine().identifier(fullName); std::vector buffer(1024); diff --git a/modules/newhorizons/util/sequenceparser.h b/modules/newhorizons/util/sequenceparser.h index 258a2b566a..fb42910e98 100644 --- a/modules/newhorizons/util/sequenceparser.h +++ b/modules/newhorizons/util/sequenceparser.h @@ -1,34 +1,33 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * -* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * -* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -****************************************************************************************/ + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ -#ifndef __SEQUENCEPARSER_H__ -#define __SEQUENCEPARSER_H__ +#ifndef __OPENSPACE_MODULE_NEWHORIZONS___SEQUENCEPARSER___H__ +#define __OPENSPACE_MODULE_NEWHORIZONS___SEQUENCEPARSER___H__ #include -#include - #include +#include #include #include @@ -75,4 +74,4 @@ protected: } // namespace openspace -#endif //__SEQUENCEPARSER_H__ +#endif //__OPENSPACE_MODULE_NEWHORIZONS___SEQUENCEPARSER___H__ diff --git a/modules/newhorizons/util/targetdecoder.cpp b/modules/newhorizons/util/targetdecoder.cpp index d0b48033ed..4bc27c8eff 100644 --- a/modules/newhorizons/util/targetdecoder.cpp +++ b/modules/newhorizons/util/targetdecoder.cpp @@ -24,6 +24,8 @@ #include +#include + namespace { const std::string _loggerCat = "TargetDecoder"; } diff --git a/modules/newhorizons/util/targetdecoder.h b/modules/newhorizons/util/targetdecoder.h index ea58c8af9b..04d65f3a56 100644 --- a/modules/newhorizons/util/targetdecoder.h +++ b/modules/newhorizons/util/targetdecoder.h @@ -22,13 +22,11 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __TARGETDECODER_H__ -#define __TARGETDECODER_H__ +#ifndef __OPENSPACE_MODULE_NEWHORIZONS___TARGETDECODER___H__ +#define __OPENSPACE_MODULE_NEWHORIZONS___TARGETDECODER___H__ #include -#include - namespace openspace { class TargetDecoder : public Decoder { @@ -43,4 +41,4 @@ private: } // namespace openspace -#endif // __TARGETDECODER_H__ +#endif // __OPENSPACE_MODULE_NEWHORIZONS___TARGETDECODER___H__ diff --git a/modules/onscreengui/ext/imgui/.gitignore b/modules/onscreengui/ext/imgui/.gitignore deleted file mode 100644 index cc09676fe9..0000000000 --- a/modules/onscreengui/ext/imgui/.gitignore +++ /dev/null @@ -1,23 +0,0 @@ -## Visual Studio files -examples/Debug/* -examples/Release/* -examples/ipch/* -examples/directx9_example/Debug/* -examples/directx9_example/Release/* -examples/directx9_example/ipch/* -examples/directx11_example/Debug/* -examples/directx11_example/Release/* -examples/directx11_example/ipch/* -examples/opengl_example/Debug/* -examples/opengl_example/Release/* -examples/opengl_example/ipch/* -examples/opengl3_example/Debug/* -examples/opengl3_example/Release/* -examples/opengl3_example/ipch/* -*.opensdf -*.sdf -*.suo -*.vcxproj.user - -## Ini files -imgui.ini diff --git a/modules/onscreengui/ext/imgui/CMakeLists.txt b/modules/onscreengui/ext/imgui/CMakeLists.txt index e56e69f742..69ee237b3a 100644 --- a/modules/onscreengui/ext/imgui/CMakeLists.txt +++ b/modules/onscreengui/ext/imgui/CMakeLists.txt @@ -25,5 +25,9 @@ project(Imgui) message(STATUS "Generating Imgui project") -add_library(Imgui ${PROJECT_SOURCE_DIR}/imgui.cpp) +add_library(Imgui + ${PROJECT_SOURCE_DIR}/imgui.cpp + ${PROJECT_SOURCE_DIR}/imgui_demo.cpp + ${PROJECT_SOURCE_DIR}/imgui_draw.cpp +) target_include_directories(Imgui PUBLIC ${PROJECT_SOURCE_DIR}) diff --git a/modules/onscreengui/ext/imgui/README.md b/modules/onscreengui/ext/imgui/README.md index f8ef61d449..9e32e9e26e 100644 --- a/modules/onscreengui/ext/imgui/README.md +++ b/modules/onscreengui/ext/imgui/README.md @@ -1,59 +1,73 @@ -ImGui +dear imgui, ===== [![Build Status](https://travis-ci.org/ocornut/imgui.svg?branch=master)](https://travis-ci.org/ocornut/imgui) [![Coverity Status](https://scan.coverity.com/projects/4720/badge.svg)](https://scan.coverity.com/projects/4720) +(This library is free and will stay free, but needs your support to sustain its development. There are lots of desirable new features and maintenance to do. If you work for a company using ImGui or have the means to do so, please consider financial support) + [![Patreon](https://cloud.githubusercontent.com/assets/8225057/5990484/70413560-a9ab-11e4-8942-1a63607c0b00.png)](http://www.patreon.com/imgui) [![PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5Q73FPZ9C526U) -ImGui is a bloat-free graphical user interface library for C++. It outputs vertex buffers that you can render in your 3D-pipeline enabled application. It is portable, renderer agnostic and carries minimal amount of dependencies. It is based on an "immediate" graphical user interface paradigm which allows you to build user interfaces with ease. +dear imgui (AKA ImGui), is a bloat-free graphical user interface library for C++. It outputs vertex buffers that you can render in your 3D-pipeline enabled application. It is fast, portable, renderer agnostic and self-contained (no external dependencies). -ImGui is designed to enable fast iteration and allow programmers to create "content creation" or "debug" tools (as opposed to UI for the average end-user). It favors simplicity and productivity toward this goal, and thus lacks certain features normally found in more high-level libraries. +ImGui is designed to enable fast iteration and empower programmers to create content creation tools and visualization/debug tools (as opposed to UI for the average end-user). It favors simplicity and productivity toward this goal, and thus lacks certain features normally found in more high-level libraries. -ImGui is particularly suited to integration in 3D applications, fullscreen applications, embedded applications, games, or any applications on consoles platforms where operating system features are non-standard. +ImGui is particularly suited to integration in realtime 3D applications, fullscreen applications, embedded applications, games, or any applications on consoles platforms where operating system features are non-standard. -ImGui is self-contained within 6 files that you can easily copy and compile into your application/engine: +ImGui is self-contained within a few files that you can easily copy and compile into your application/engine: - imgui.cpp - imgui.h + - imgui_demo.cpp + - imgui_draw.cpp + - imgui_internal.h - imconfig.h (empty by default, user-editable) - stb_rect_pack.h - stb_textedit.h - stb_truetype.h +No specific build process is required. You can add the .cpp files to your project or #include them from an existing file. + Your code passes mouse/keyboard inputs and settings to ImGui (see example applications for more details). After ImGui is setup, you can use it like in this example: -![screenshot of sample code alongside its output with ImGui](/web/code_sample_01.png?raw=true) +![screenshot of sample code alongside its output with ImGui](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/code_sample_01.png) -ImGui outputs vertex buffers and simple command-lists that you can render in your application. Because it doesn't know or touch graphics state directly, you can call ImGui commands anywhere in your code (e.g. in the middle of a running algorithm, or in the middle of your own rendering process). Refer to the sample applications in the examples/ folder for instructions on how to integrate ImGui with your existing codebase. +ImGui outputs vertex buffers and simple command-lists that you can render in your application. The number of draw calls and state changes is typically very small. Because it doesn't know or touch graphics state directly, you can call ImGui commands anywhere in your code (e.g. in the middle of a running algorithm, or in the middle of your own rendering process). Refer to the sample applications in the examples/ folder for instructions on how to integrate ImGui with your existing codebase. -ImGui allows you create elaborate tools as well as very short-lived ones. On the extreme side of short-liveness: using the Edit&Continue feature of compilers you can add a few widgets to tweaks variables while your application is running, and remove the code a minute later! ImGui is not just for tweaking values. You can use it to trace a running algorithm by just emitting text commands. You can use it along with your own reflection data to browse your dataset live. You can use it to expose the internals of a subsystem in your engine, to create a logger, an inspection tool, a profiler, a debugger, etc. +ImGui allows you create elaborate tools as well as very short-lived ones. On the extreme side of short-liveness: using the Edit&Continue feature of modern compilers you can add a few widgets to tweaks variables while your application is running, and remove the code a minute later! ImGui is not just for tweaking values. You can use it to trace a running algorithm by just emitting text commands. You can use it along with your own reflection data to browse your dataset live. You can use it to expose the internals of a subsystem in your engine, to create a logger, an inspection tool, a profiler, a debugger, etc. Demo ---- -You should be able to build the examples from sources (tested on Windows/Mac/Linux). If you don't, let me know! If you want to have a quick look at the features of ImGui, you can download binaries of the demo app here. -- [imgui-demo-binaries-20150321.zip](http://www.miracleworld.net/imgui/binaries/imgui-demo-binaries-20150321.zip) (Windows binaries, ImGui 1.37 WIP 2015/03/31, 4 executables, 391 KB) +You should be able to build the examples from sources (tested on Windows/Mac/Linux). If you don't, let me know! If you want to have a quick look at the features of ImGui, you can download Windows binaries of the demo app here. +- [imgui-demo-binaries-20160410.zip](http://www.miracleworld.net/imgui/binaries/imgui-demo-binaries-20160410.zip) (Windows binaries, ImGui 1.48+ 2016/04/10, 4 executables, 534 KB) Gallery ------- -![screenshot 1](/web/test_window_01.png?raw=true) -![screenshot 2](/web/test_window_02.png?raw=true) -![screenshot 3](/web/test_window_03.png?raw=true) -![screenshot 4](/web/test_window_04.png?raw=true) -![screenshot 4](/web/examples_02.png?raw=true) +See the [Screenshots Thread](https://github.com/ocornut/imgui/issues/123) for some user creations. + +![screenshot 1](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/examples_01.png) +![screenshot 2](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/examples_02.png) + +[![profiler](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/profiler-880.jpg)](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/profiler.png) + +![screenshot 2](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/test_window_01.png) +![screenshot 3](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/test_window_02.png) +![screenshot 4](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/test_window_03.png) +![screenshot 5](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v140/test_window_05_menus.png) +![screenshot 6](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/skinning_sample_02.png) +![screenshot 7](https://cloud.githubusercontent.com/assets/8225057/7903336/96f0fb7c-07d0-11e5-95d6-41c6a1595e5a.png) ImGui can load TTF fonts. UTF-8 is supported for text display and input. Here using Arial Unicode font to display Japanese. Initialize custom font with: ``` ImGuiIO& io = ImGui::GetIO(); -io.Fonts->AddFontFromFileTTF("ArialUni.ttf", 18.0f, io.Fonts->GetGlyphRangesJapanese()); -``` -For Microsoft IME, pass your HWND to enable IME positioning: -``` +io.Fonts->AddFontFromFileTTF("ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); + +// For Microsoft IME, pass your HWND to enable IME positioning: io.ImeWindowHandle = my_hwnd; ``` -![Japanese screenshot](/web/code_sample_01_jp.png?raw=true) +![Japanese screenshot](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/code_sample_01_jp.png) References ---------- @@ -64,48 +78,70 @@ The Immediate Mode GUI paradigm may at first appear unusual to some users. This - [Jari Komppa's tutorial on building an ImGui library](http://iki.fi/sol/imgui/). - [Casey Muratori's original video that popularized the concept](https://mollyrocket.com/861). -Frequently Asked Question -------------------------- +See the [Links page](https://github.com/ocornut/imgui/wiki/Links) for third-party bindings to different languages and frameworks. + +Frequently Asked Question (FAQ) +------------------------------- Where is the documentation? -- The documentation is at the top of imgui.cpp + effectively imgui.h. -- Example code is in the ImGui::ShowTestWindow() function. It covers most features of ImGui so you can read the code and call the function itself to see its output. -- Standalone example applications using OpenGL/DirectX are provided in the examples/ folder. +- The documentation is at the top of imgui.cpp + effectively imgui.h. +- Example code is in imgui_demo.cpp and particularly the ImGui::ShowTestWindow() function. It covers most features of ImGui so you can read the code and call the function itself to see its output. +- Standalone example applications using e.g. OpenGL/DirectX are provided in the examples/ folder. +- We obviously needs better documentation! Consider contributing or becoming a [Patron](http://www.patreon.com/imgui) to promote this effort. + +Why the odd dual naming, "dear imgui" vs "ImGui"? + +The library started its life and is best known as "ImGui" only due to the fact that I didn't give it a proper name when I released it. However, the term IMGUI (immediate-mode graphical user interface) was coined before and is being used in variety of other situations. It seemed confusing and unfair to hog the name. To reduce the ambiguity without affecting existing codebases, I have decided on an alternate, longer name "dear imgui" that people can use to refer to this specific library in ambiguous situations. + +How do I update to a newer version of ImGui? +
What is ImTextureID and how do I display an image? +
I integrated ImGui in my engine and the text or lines are blurry.. +
I integrated ImGui in my engine and some elements are disappearing when I move windows around.. +
How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on the purpose of labels/IDs. +
How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application? +
How can I load a different font than the default? +
How can I load multiple fonts? +
How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic? +
How can I use the drawing facilities without an ImGui window? (using ImDrawList API) + +See the FAQ in imgui.cpp for answers. How do you use ImGui on a platform that may not have a mouse or keyboard? -I recommend using [Synergy](http://synergy-project.org) ([sources](https://github.com/synergy/synergy)). In particular, the _src/micro/uSynergy.c_ file contains a small client that you can use on any platform to connect to your host PC. You can seamlessly use your PC input devices from a video game console or a tablet. ImGui allows to increase the hit box of widgets (via the _TouchPadding_ setting) to accomodate a little for the lack of precision of touch inputs, but it is recommended you use a mouse to allow optimising for screen real-estate. - -I integrated ImGui in my engine and the text or lines are blurry.. - -In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f). +I recommend using [Synergy](http://synergy-project.org) ([sources](https://github.com/synergy/synergy)). In particular, the _src/micro/uSynergy.c_ file contains a small client that you can use on any platform to connect to your host PC. You can seamlessly use your PC input devices from a video game console or a tablet. ImGui allows to increase the hit box of widgets (via the _TouchPadding_ setting) to accommodate a little for the lack of precision of touch inputs, but it is recommended you use a mouse to allow optimising for screen real-estate. Can you create elaborate/serious tools with ImGui? -Yes. I have written data browsers, debuggers, profilers and all sort of non-trivial tools with the library. In my experience the simplicity of the API is very empowering. However note that ImGui is programmer centric and the immediate-mode GUI paradigm might requires a bit of adaptation before you can realize its full potential. +Yes. I have written data browsers, debuggers, profilers and all sort of non-trivial tools with the library. In my experience the simplicity of the API is very empowering. Your UI runs close to your live data. Make the tools always-on and everybody in the team will be inclined to create new tools (as opposed to more "offline" UI toolkits where only a fraction of your team effectively creates tools). + +ImGui is very programmer centric and the immediate-mode GUI paradigm might requires you to readjust some habits before you can realize its full potential. Many programmers have unfortunately been taught by their environment to make unnecessarily complicated things. ImGui is about making things that are simple, efficient and powerful. Is ImGui fast? -Down to the fundation of its visual design, ImGui is engineered to be fairly performant both in term of CPU and GPU usage. Running elaborate code and creating elaborate UI will of course have a cost but ImGui aims to minimize it. +Probably fast enough for most uses. Down to the fundation of its visual design, ImGui is engineered to be fairly performant both in term of CPU and GPU usage. Running elaborate code and creating elaborate UI will of course have a cost but ImGui aims to minimize it. Mileage may vary but the following screenshot can give you a rough idea of the cost of running and rendering UI code (In the case of a trivial demo application like this one, your driver/os setup are likely to be the bottleneck. Testing performance as part of a real application is recommended). -![performance screenshot](/web/performance_01.png?raw=true) +![performance screenshot](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v138/performance_01.png) This is showing framerate for the full application loop on my 2011 iMac running Windows 7, OpenGL, AMD Radeon HD 6700M with an optimized executable. In contrast, librairies featuring higher-quality rendering and layouting techniques may have a higher resources footprint. -If you intend to display large lists of items (say, 1000+) it can be beneficial for your code to perform clipping manually - using helpers such as CalcListClipping() - in order to avoid submitting them to ImGui in the first place. Even though ImGui will discard your clipped items it still needs to calculate their size and that overhead will add up if you have thousands of items. If you can handle clipping and height positionning yourself then browsing a list with millions of items isn't a problem. +If you intend to display large lists of items (say, 1000+) it can be beneficial for your code to perform clipping manually - one way is using helpers such as ImGuiListClipper - in order to avoid submitting them to ImGui in the first place. Even though ImGui will discard your clipped items it still needs to calculate their size and that overhead will add up if you have thousands of items. If you can handle clipping and height positionning yourself then browsing a list with millions of items isn't a problem. Can you reskin the look of ImGui? You can alter the look of the interface to some degree: changing colors, sizes, padding, rounding, fonts. However, as ImGui is designed and optimised to create debug tools, the amount of skinning you can apply is limited. There is only so much you can stray away from the default look and feel of the interface. +This is [LumixEngine](https://github.com/nem0/LumixEngine) with a minor skinning hack + a docking/tabs extension (both of which you can find in the Issues section and will eventually be merged). + +[![Skinning in LumixEngine](https://cloud.githubusercontent.com/assets/8225057/13198792/92808c5c-d812-11e5-9507-16b63918b05b.jpg)](https://cloud.githubusercontent.com/assets/8225057/13044612/59f07aec-d3cf-11e5-8ccb-39adf2e13e69.png) + Why using C++ (as opposed to C)? ImGui takes advantage of a few C++ features for convenience but nothing anywhere Boost-insanity/quagmire. In particular, function overloading and default parameters are used to make the API easier to use and code more terse. Doing so I believe the API is sitting on a sweet spot and giving up on those features would make the API more cumbersome. Other features such as namespace, constructors and templates (in the case of the ImVector<> class) are also relied on as a convenience but could be removed. -Shall someone wants to use ImGui from another language, it should be possible to wrap ImGui to be used from a raw C API in the future. +There is an unofficial but reasonably maintained [c-api for ImGui](https://github.com/Extrawurst/cimgui) by Stephan Dilly. I would suggest using your target language functionality to try replicating the function overloading and default parameters used in C++ else the API may be harder to use. It was really designed with C++ in mind and may not make the same amount of sense with another language. Also see [Links](https://github.com/ocornut/imgui/wiki/Links) for third-party bindings to other languages. Donate ------ @@ -114,30 +150,35 @@ Donate [![Patreon](https://cloud.githubusercontent.com/assets/8225057/5990484/70413560-a9ab-11e4-8942-1a63607c0b00.png)](http://www.patreon.com/imgui) [![PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5Q73FPZ9C526U) -I'm currently an independant developer and your contributions are very meaningful to me. I have setup an [**ImGui Patreon page**](http://www.patreon.com/imgui) if you want to donate and enable me to spend more time improving the library. If your company uses ImGui please consider making a contribution. One-off donations are also greatly appreciated (PayPal link above). I am also available for hire to work on or with ImGui. Thanks! +I'm currently an independent developer and your contributions are useful. I have setup an [**ImGui Patreon page**](http://www.patreon.com/imgui) if you want to donate and enable me to spend more time improving the library. If your company uses ImGui please consider making a contribution. One-off donations are also greatly appreciated. I am available for hire to work on or with ImGui. Thanks! Credits ------- Developed by [Omar Cornut](http://www.miracleworld.net) and every direct or indirect contributors to the GitHub. The early version of this library was developed with the support of [Media Molecule](http://www.mediamolecule.com) and first used internally on the game [Tearaway](http://tearaway.mediamolecule.com). +I first discovered imgui principles at [Q-Games](http://www.q-games.com) where Atman had dropped his own simple imgui implementation in the codebase, which I spent quite some time improving and thinking about. It turned out that Atman was exposed to the concept directly by working with Casey. When I moved to Media Molecule I rewrote a new library trying to overcome the flaws and limitations of the first one I've worked with. It became this library and since then I have spent an unreasonable amount of time iterating on it. + Embeds [ProggyClean.ttf](http://upperbounds.net) font by Tristan Grimmer (MIT license). Embeds [stb_textedit.h, stb_truetype.h, stb_rectpack.h](https://github.com/nothings/stb/) by Sean Barrett (public domain). Inspiration, feedback, and testing for early versions: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. And everybody posting feedback, questions and patches on the GitHub. -ImGui is financially supported on [**Patreon**](http://www.patreon.com/imgui). +Ongoing ImGui development is financially supported on [**Patreon**](http://www.patreon.com/imgui). -Special supporters -- Jetha Chan, Mārtiņš Možeiko, Alex Evans, Pastagames, Wild Sheep Studio +Double-chocolate sponsors: +- Media Molecule, Mobigame -And -- Dale Kim, Michel Courtine, Paul Patrashcu, Rui Figueira +Salty caramel supporters: +- Jetha Chan, Wild Sheep Studio, Pastagames, Mārtiņš Možeiko, Daniel Collin, Stefano Cristiano, Chris Genova, ikrima + +Caramel supporters: +- Michel Courtine, César Leblic, Dale Kim, Alex Evans, Rui Figueira, Paul Patrashcu, Jerome Lanquetot, Ctrl Alt Ninja, Paul Fleming, Neil Henning, Stephan Dilly, Neil Blakey-Milner, Aleksei, NeiloGD, Justin Paver, FiniteSol, Vincent Pancaldi, James Billot, Robin Hübner, furrtek, Eric, Simon Barratt, Game Atelier, Julian Bosch, Simon Lundmark, Vincent Hamm, Farhan Wali, Jeff Roberts, Matt Reyer, Colin Riley. And other supporters; thanks! License ------- -ImGui is licensed under the MIT License, see LICENSE for more information. +Dear ImGui is licensed under the MIT License, see LICENSE for more information. diff --git a/modules/onscreengui/ext/imgui/imconfig.h b/modules/onscreengui/ext/imgui/imconfig.h index 24d61148d7..33cbadd17e 100644 --- a/modules/onscreengui/ext/imgui/imconfig.h +++ b/modules/onscreengui/ext/imgui/imconfig.h @@ -6,11 +6,6 @@ #pragma once -//---- Define your own ImVector<> type if you don't want to use the provided implementation defined in imgui.h -//#include -//#define ImVector std::vector -//#define ImVector MyVector - //---- Define assertion handler. Defaults to calling assert(). //#define IM_ASSERT(_EXPR) MyAssert(_EXPR) @@ -18,9 +13,6 @@ //#define IMGUI_API __declspec( dllexport ) //#define IMGUI_API __declspec( dllimport ) -//---- Include imgui_user.inl at the end of imgui.cpp so you can include code that extends ImGui using its private data/functions. -//#define IMGUI_INCLUDE_IMGUI_USER_INL - //---- Include imgui_user.h at the end of imgui.h //#define IMGUI_INCLUDE_IMGUI_USER_H @@ -31,8 +23,11 @@ //---- Don't implement help and test window functionality (ShowUserGuide()/ShowStyleEditor()/ShowTestWindow() methods will be empty) //#define IMGUI_DISABLE_TEST_WINDOWS +//---- Don't define obsolete functions names +//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS + //---- Implement STB libraries in a namespace to avoid conflicts -//#define IMGUI_STB_NAMESPACE ImStb +//#define IMGUI_STB_NAMESPACE ImGuiStb //---- Define constructor and implicit cast operators to convert back<>forth from your math types and ImVec2/ImVec4. /* @@ -45,14 +40,12 @@ operator MyVec4() const { return MyVec4(x,y,z,w); } */ -//---- Freely implement extra functions within the ImGui:: namespace. -//---- Declare helpers or widgets implemented in imgui_user.inl or elsewhere, so end-user doesn't need to include multiple files. -//---- e.g. you can create variants of the ImGui::Value() helper for your low-level math types, or your own widgets/helpers. +//---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files. +//---- e.g. create variants of the ImGui::Value() helper for your low-level math types, or your own widgets/helpers. /* namespace ImGui { - void Value(const char* prefix, const MyVec2& v, const char* float_format = NULL); - void Value(const char* prefix, const MyVec4& v, const char* float_format = NULL); + void Value(const char* prefix, const MyMatrix44& v, const char* float_format = NULL); } */ diff --git a/modules/onscreengui/ext/imgui/imgui.cpp b/modules/onscreengui/ext/imgui/imgui.cpp index b405e5293e..89fac50dbb 100644 --- a/modules/onscreengui/ext/imgui/imgui.cpp +++ b/modules/onscreengui/ext/imgui/imgui.cpp @@ -1,8 +1,13 @@ -// ImGui library v1.39 WIP -// See ImGui::ShowTestWindow() for sample code. -// Read 'Programmer guide' below for notes on how to setup ImGui in your codebase. +// dear imgui, v1.49 +// (main code and documentation) + +// See ImGui::ShowTestWindow() in imgui_demo.cpp for demo code. +// Newcomers, read 'Programmer guide' below for notes on how to setup ImGui in your codebase. // Get latest version at https://github.com/ocornut/imgui -// Developed by Omar Cornut and ImGui contributors. +// Releases change-log at https://github.com/ocornut/imgui/releases +// Developed by Omar Cornut and every direct or indirect contributors to the GitHub. +// This library is free but I need your support to sustain development and maintenance. +// If you work for a company, please consider financial support, e.g: https://www.patreon.com/imgui /* @@ -12,18 +17,21 @@ - PROGRAMMER GUIDE (read me!) - API BREAKING CHANGES (read me when you update!) - FREQUENTLY ASKED QUESTIONS (FAQ), TIPS + - How can I help? - How do I update to a newer version of ImGui? - - Can I have multiple widgets with the same label? Can I have widget without a label? (Yes) - - Why is my text output blurry? - - How can I load a different font than the default? + - What is ImTextureID and how do I display an image? + - I integrated ImGui in my engine and the text or lines are blurry.. + - I integrated ImGui in my engine and some elements are clipping or disappearing when I move windows around.. + - How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on the purpose of labels/IDs. + - How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application? + - How can I load a different font than the default? - How can I load multiple fonts? - - How can I display and input Chinese, Japanese, Korean characters? + - How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic? + - How can I use the drawing facilities without an ImGui window? (using ImDrawList API) - ISSUES & TODO-LIST - CODE - - SAMPLE CODE - - FONT DATA - + MISSION STATEMENT ================= @@ -47,14 +55,14 @@ ============== - double-click title bar to collapse window - - click upper right corner to close a window, available when 'bool* p_opened' is passed to ImGui::Begin() + - click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin() - click and drag on lower right corner to resize window - click and drag on any empty space to move window - double-click/double-tap on lower right corner grip to auto-fit to content - TAB/SHIFT+TAB to cycle through keyboard editable fields - use mouse wheel to scroll - use CTRL+mouse wheel to zoom window contents (if IO.FontAllowScaling is true) - - CTRL+Click on a slider to input value as text + - CTRL+Click on a slider or drag box to input value as text - text editor: - Hold SHIFT or use mouse to select text. - CTRL+Left/Right to word jump @@ -71,19 +79,23 @@ - read the FAQ below this section! - your code creates the UI, if your code doesn't run the UI is gone! == very dynamic UI, no construction/destructions steps, less data retention on your side, no state duplication, less sync, less bugs. - - call and read ImGui::ShowTestWindow() for sample code demonstrating most features. - - see examples/ folder for standalone sample applications. e.g. examples/opengl_example/ + - call and read ImGui::ShowTestWindow() for demo code demonstrating most features. + - see examples/ folder for standalone sample applications. Prefer reading examples/opengl_example/ first as it is the simplest. + you may be able to grab and copy a ready made imgui_impl_*** file from the examples/. - customization: PushStyleColor()/PushStyleVar() or the style editor to tweak the look of the interface (e.g. if you want a more compact UI or a different color scheme). - getting started: - - initialisation: call ImGui::GetIO() to retrieve the ImGuiIO structure and fill the 'Settings' data. - - every frame: - 1/ in your mainloop or right after you got your keyboard/mouse info, call ImGui::GetIO() and fill the 'Input' data, then call ImGui::NewFrame(). - 2/ use any ImGui function you want between NewFrame() and Render() - 3/ ImGui::Render() to render all the accumulated command-lists. it will call your RenderDrawListFn handler that you set in the IO structure. - - all rendering information are stored into command-lists until ImGui::Render() is called. - - ImGui never touches or know about your GPU state. the only function that knows about GPU is the RenderDrawListFn handler that you must provide. - - effectively it means you can create widgets at any time in your code, regardless of "update" vs "render" considerations. + - init: call ImGui::GetIO() to retrieve the ImGuiIO structure and fill the fields marked 'Settings'. + - init: call io.Fonts->GetTexDataAsRGBA32(...) and load the font texture pixels into graphics memory. + - every frame: + 1/ in your mainloop or right after you got your keyboard/mouse info, call ImGui::GetIO() and fill the fields marked 'Input' + 2/ call ImGui::NewFrame() as early as you can! + 3/ use any ImGui function you want between NewFrame() and Render() + 4/ call ImGui::Render() as late as you can to end the frame and finalize render data. it will call your RenderDrawListFn handler that you set in the IO structure. + (if you don't need to render, you still need to call Render() and ignore the callback, or call EndFrame() instead. if you call neither some aspects of windows focusing/moving will appear broken.) + - all rendering information are stored into command-lists until ImGui::Render() is called. + - ImGui never touches or know about your GPU state. the only function that knows about GPU is the RenderDrawListFn handler that you provide. + - effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" phases of your own application. - refer to the examples applications in the examples/ folder for instruction on how to setup your code. - a typical application skeleton may be: @@ -91,60 +103,122 @@ ImGuiIO& io = ImGui::GetIO(); io.DisplaySize.x = 1920.0f; io.DisplaySize.y = 1280.0f; - io.DeltaTime = 1.0f/60.0f; io.IniFilename = "imgui.ini"; + io.RenderDrawListsFn = my_render_function; // Setup a render function, or set to NULL and call GetDrawData() after Render() to access the render data. // TODO: Fill others settings of the io structure - // Load texture + // Load texture atlas + // There is a default font so you don't need to care about choosing a font yet unsigned char* pixels; - int width, height, bytes_per_pixels; - io.Fonts->GetTexDataAsRGBA32(pixels, &width, &height, &bytes_per_pixels); - // TODO: copy texture to graphics memory. - // TODO: store your texture pointer/identifier in 'io.Fonts->TexID' + int width, height; + io.Fonts->GetTexDataAsRGBA32(pixels, &width, &height); + // TODO: At this points you've got a texture pointed to by 'pixels' and you need to upload that your your graphic system + // TODO: Store your texture pointer/identifier (whatever your engine uses) in 'io.Fonts->TexID' // Application main loop while (true) { - // 1) get low-level input - // e.g. on Win32, GetKeyboardState(), or poll your events, etc. - - // 2) TODO: fill all fields of IO structure and call NewFrame + // 1) get low-level inputs (e.g. on Win32, GetKeyboardState(), or poll your events, etc.) + // TODO: fill all fields of IO structure and call NewFrame ImGuiIO& io = ImGui::GetIO(); + io.DeltaTime = 1.0f/60.0f; io.MousePos = mouse_pos; io.MouseDown[0] = mouse_button_0; + io.MouseDown[1] = mouse_button_1; io.KeysDown[i] = ... + + // 2) call NewFrame(), after this point you can use ImGui::* functions anytime ImGui::NewFrame(); - // 3) most of your application code here - you can use any of ImGui::* functions at any point in the frame + // 3) most of your application code here ImGui::Begin("My window"); ImGui::Text("Hello, world."); ImGui::End(); - GameUpdate(); - GameRender(); + MyGameUpdate(); // may use ImGui functions + MyGameRender(); // may use ImGui functions // 4) render & swap video buffers ImGui::Render(); - // swap video buffer, etc. + SwapBuffers(); } - - after calling ImGui::NewFrame() you can read back 'io.WantCaptureMouse' and 'io.WantCaptureKeyboard' to tell if ImGui - wants to use your inputs. if it does you can discard/hide the inputs from the rest of your application. + - You can read back 'io.WantCaptureMouse', 'io.WantCaptureKeybord' etc. flags from the IO structure to tell how ImGui intends to use your + inputs and to know if you should share them or hide them from the rest of your application. Read the FAQ below for more information. + API BREAKING CHANGES ==================== Occasionally introducing changes that are breaking the API. The breakage are generally minor and easy to fix. Here is a change-log of API breaking changes, if you are using one of the functions listed, expect to have to fix some code. - - - 2015/05/03 (1.39) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same). + Also read releases logs https://github.com/ocornut/imgui/releases for more details. + + - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore. + If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you. + However if your TitleBg/TitleBgActive alpha was <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar. + This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color. + ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) + { + float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; + return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); + } + If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color. + - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext(). + - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection. + - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen). + - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDraw::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer. + - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref github issue #337). + - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337) + - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete). + - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert. + - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you. + - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis. + - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete. + - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position. + GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side. + GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out! + - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize + - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project. + - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason + - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure. + you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text. + - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost. + this necessary change will break your rendering function! the fix should be very easy. sorry for that :( + - if you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest. + - the signature of the io.RenderDrawListsFn handler has changed! + ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count) + became: + ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data). + argument 'cmd_lists' -> 'draw_data->CmdLists' + argument 'cmd_lists_count' -> 'draw_data->CmdListsCount' + ImDrawList 'commands' -> 'CmdBuffer' + ImDrawList 'vtx_buffer' -> 'VtxBuffer' + ImDrawList n/a -> 'IdxBuffer' (new) + ImDrawCmd 'vtx_count' -> 'ElemCount' + ImDrawCmd 'clip_rect' -> 'ClipRect' + ImDrawCmd 'user_callback' -> 'UserCallback' + ImDrawCmd 'texture_id' -> 'TextureId' + - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer. + - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering! + - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade! + - 2015/07/10 (1.43) - changed SameLine() parameters from int to float. + - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete). + - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount. + - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence + - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely be used. Sorry! + - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete). + - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete). + - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons. + - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened. + - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same). - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function (will obsolete). - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive. - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead. - - 2015/03/17 (1.36) - renamed GetItemRectMin()/GetItemRectMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function (will obsolete). + - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function (will obsolete). - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function (will obsolete). - - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth + - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing) - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function (will obsolete). - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once. - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now. @@ -166,7 +240,7 @@ // io.Fonts->TexID = (your_texture_identifier); you now have much more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. - it is now recommended your sample the font texture with bilinear interpolation. + it is now recommended that you sample the font texture with bilinear interpolation. (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID. (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix) (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets @@ -186,56 +260,88 @@ FREQUENTLY ASKED QUESTIONS (FAQ), TIPS ====================================== + Q: How can I help? + A: - If you are experienced enough with ImGui and with C/C++, look at the todo list and see how you want/can help! + - Become a Patron/donate. Convince your company to become a Patron or provide serious funding for development time. + Q: How do I update to a newer version of ImGui? A: Overwrite the following files: imgui.cpp imgui.h + imgui_demo.cpp + imgui_draw.cpp + imgui_internal.h stb_rect_pack.h stb_textedit.h stb_truetype.h + Don't overwrite imconfig.h if you have made modification to your copy. Check the "API BREAKING CHANGES" sections for a list of occasional API breaking changes. If you have a problem with a function, search for its name in the code, there will likely be a comment about it. Please report any issue to the GitHub page! + + Q: What is ImTextureID and how do I display an image? + A: ImTextureID is a void* used to pass renderer-agnostic texture references around until it hits your render function. + ImGui knows nothing about what those bits represent, it just passes them around. It is up to you to decide what you want the void* to carry! + It could be an identifier to your OpenGL texture (cast GLuint to void*), a pointer to your custom engine material (cast MyMaterial* to void*), etc. + At the end of the chain, your renderer takes this void* to cast it back into whatever it needs to select a current texture to render. + Refer to examples applications, where each renderer (in a imgui_impl_xxxx.cpp file) is treating ImTextureID as a different thing. + (c++ tip: OpenGL uses integers to identify textures. You can safely store an integer into a void*, just cast it to void*, don't take it's address!) + To display a custom image/texture within an ImGui window, you may use ImGui::Image(), ImGui::ImageButton(), ImDrawList::AddImage() functions. + ImGui will generate the geometry and draw calls using the ImTextureID that you passed and which your renderer can use. + It is your responsibility to get textures uploaded to your GPU. + + Q: I integrated ImGui in my engine and the text or lines are blurry.. + A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f). + Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension. + + Q: I integrated ImGui in my engine and some elements are clipping or disappearing when I move windows around.. + A: Most likely you are mishandling the clipping rectangles in your render function. Rectangles provided by ImGui are defined as (x1,y1,x2,y2) and NOT as (x1,y1,width,height). + Q: Can I have multiple widgets with the same label? Can I have widget without a label? (Yes) A: Yes. A primer on the use of labels/IDs in ImGui.. - + - Elements that are not clickable, such as Text() items don't need an ID. - Interactive widgets require state to be carried over multiple frames (most typically ImGui often needs to remember what is the "active" widget). to do so they need an unique ID. unique ID are typically derived from a string label, an integer index or a pointer. - + Button("OK"); // Label = "OK", ID = hash of "OK" Button("Cancel"); // Label = "Cancel", ID = hash of "Cancel" - ID are uniquely scoped within windows, tree nodes, etc. so no conflict can happen if you have two buttons called "OK" in two different windows or in two different locations of a tree. - - if you have a same ID twice in the same location, you'll have a conflict: + - If you have a same ID twice in the same location, you'll have a conflict: Button("OK"); Button("OK"); // ID collision! Both buttons will be treated as the same. Fear not! this is easy to solve and there are many ways to solve it! - - when passing a label you can optionally specify extra unique ID information within string itself. This helps solving the simpler collision cases. + - When passing a label you can optionally specify extra unique ID information within string itself. This helps solving the simpler collision cases. use "##" to pass a complement to the ID that won't be visible to the end-user: - Button("Play##0"); // Label = "Play", ID = hash of "Play##0" - Button("Play##1"); // Label = "Play", ID = hash of "Play##1" (different from above) + Button("Play"); // Label = "Play", ID = hash of "Play" + Button("Play##foo1"); // Label = "Play", ID = hash of "Play##foo1" (different from above) + Button("Play##foo2"); // Label = "Play", ID = hash of "Play##foo2" (different from above) - - so if you want to hide the label but need an ID: + - If you want to completely hide the label, but still need an ID: - Checkbox("##On", &b); // Label = "", ID = hash of "##On" + Checkbox("##On", &b); // Label = "", ID = hash of "##On" (no label!) - - occasionally (rarely) you might want change a label while preserving a constant ID. This allows you to animate labels. - use "###" to pass a label that isn't part of ID: + - Occasionally/rarely you might want change a label while preserving a constant ID. This allows you to animate labels. + For example you may want to include varying information in a window title bar (and windows are uniquely identified by their ID.. obviously) + Use "###" to pass a label that isn't part of ID: Button("Hello###ID"; // Label = "Hello", ID = hash of "ID" Button("World###ID"; // Label = "World", ID = hash of "ID" (same as above) - - use PushID() / PopID() to create scopes and avoid ID conflicts within the same Window. - this is the most convenient way of distinguish ID if you are iterating and creating many UI elements. - you can push a pointer, a string or an integer value. remember that ID are formed from the addition of everything in the ID stack! + sprintf(buf, "My game (%f FPS)###MyGame"); + Begin(buf); // Variable label, ID = hash of "MyGame" + + - Use PushID() / PopID() to create scopes and avoid ID conflicts within the same Window. + This is the most convenient way of distinguishing ID if you are iterating and creating many UI elements. + You can push a pointer, a string or an integer value. Remember that ID are formed from the concatenation of everything in the ID stack! for (int i = 0; i < 100; i++) { @@ -260,7 +366,7 @@ PopID(); } - - more example showing that you can stack multiple prefixes into the ID stack: + - More example showing that you can stack multiple prefixes into the ID stack: Button("Click"); // Label = "Click", ID = hash of "Click" PushID("node"); @@ -270,7 +376,7 @@ PopID(); PopID(); - - tree nodes implicitly creates a scope for you by calling PushID(). + - Tree nodes implicitly creates a scope for you by calling PushID(). Button("Click"); // Label = "Click", ID = hash of "Click" if (TreeNode("node")) @@ -279,105 +385,190 @@ TreePop(); } - - when working with trees, ID are used to preserve the opened/closed state of each tree node. - depending on your use cases you may want to use strings, indices or pointers as ID. + - When working with trees, ID are used to preserve the open/close state of each tree node. + Depending on your use cases you may want to use strings, indices or pointers as ID. e.g. when displaying a single object that may change over time (1-1 relationship), using a static string as ID will preserve your node open/closed state when the targeted object change. e.g. when displaying a list of objects, using indices or pointers as ID will preserve the node open/closed state differently. experiment and see what makes more sense! - Q: Why is my text output blurry? - A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f) + Q: How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application? + A: You can read the 'io.WantCaptureXXX' flags in the ImGuiIO structure. Preferably read them after calling ImGui::NewFrame() to avoid those flags lagging by one frame. + When 'io.WantCaptureMouse' or 'io.WantCaptureKeyboard' flags are set you may want to discard/hide the inputs from the rest of your application. + When 'io.WantInputsCharacters' is set to may want to notify your OS to popup an on-screen keyboard, if available. + ImGui is tracking dragging and widget activity that may occur outside the boundary of a window, so 'io.WantCaptureMouse' is a more accurate and complete than testing for ImGui::IsMouseHoveringAnyWindow(). Q: How can I load a different font than the default? (default is an embedded version of ProggyClean.ttf, rendered at size 13) A: Use the font atlas to load the TTF file you want: - io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); - io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() + ImGuiIO& io = ImGui::GetIO(); + io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); + io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() Q: How can I load multiple fonts? A: Use the font atlas to pack them into a single texture: + (Read extra_fonts/README.txt and the code in ImFontAtlas for more details.) - ImFont* font0 = io.Fonts->AddFontDefault(); - ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); - ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels); - io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() - // the first loaded font gets used by default - // use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime + ImGuiIO& io = ImGui::GetIO(); + ImFont* font0 = io.Fonts->AddFontDefault(); + ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); + ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels); + io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() + // the first loaded font gets used by default + // use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime - Q: How can I render and input Chinese, Japanese, Korean characters? - A: When loading a font, pass custom Unicode ranges to specify the glyphs to load. ImGui will support UTF-8 encoding across the board. - Character input depends on you passing the right character code to io.AddInputCharacter(). The example applications do that. + // Options + ImFontConfig config; + config.OversampleH = 3; + config.OversampleV = 1; + config.GlyphExtraSpacing.x = 1.0f; + io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, &config); - io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, io.Fonts->GetGlyphRangesJapanese()); // Load Japanese characters - io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() - io.ImeWindowHandle = MY_HWND; // To input using Microsoft IME, give ImGui the hwnd of your application + // Combine multiple fonts into one + ImWchar ranges[] = { 0xf000, 0xf3ff, 0 }; + ImFontConfig config; + config.MergeMode = true; + io.Fonts->AddFontDefault(); + io.Fonts->LoadFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); + io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); + + Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic? + A: When loading a font, pass custom Unicode ranges to specify the glyphs to load. + All your strings needs to use UTF-8 encoding. Specifying literal in your source code using a local code page (such as CP-923 for Japanese or CP-1251 for Cyrillic) will not work. + In C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax. Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8. + You can also try to remap your local codepage characters to their Unicode codepoint using font->AddRemapChar(), but international users may have problems reading/editing your source code. + + io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); // Load Japanese characters + io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() + io.ImeWindowHandle = MY_HWND; // To input using Microsoft IME, give ImGui the hwnd of your application + + As for text input, depends on you passing the right character code to io.AddInputCharacter(). The example applications do that. + + Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API) + A: The easiest way is to create a dummy window. Call Begin() with NoTitleBar|NoResize|NoMove|NoScrollbar|NoSavedSettings|NoInputs flag, zero background alpha, + then retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like. - tip: the construct 'IMGUI_ONCE_UPON_A_FRAME { ... }' will run the block of code only once a frame. You can use it to quickly add custom UI in the middle of a deep nested inner loop in your code. - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug" - - tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window. + - tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window. this is also useful to set yourself in the context of another window (to get/set other settings) - tip: you can call Render() multiple times (e.g for VR renders). - - tip: call and read the ShowTestWindow() code for more example of how to use ImGui! + - tip: call and read the ShowTestWindow() code in imgui_demo.cpp for more example of how to use ImGui! ISSUES & TODO-LIST ================== + Issue numbers (#) refer to github issues listed at https://github.com/ocornut/imgui/issues + The list below consist mostly of notes of things to do before they are requested/discussed by users (at that point it usually happens on the github) - - misc: merge or clarify ImVec4 vs ImRect? - - window: add horizontal scroll - - window: fix resize grip rendering scaling along with Rounding style setting - - window: autofit feedback loop when user relies on any dynamic layout (window width multiplier, column). maybe just clearly drop manual autofit? - - window: add a way for very transient windows (non-saved, temporary overlay over hundreds of objects) to "clean" up from the global window list. + - doc: add a proper documentation+regression testing system (#435) + - window: add a way for very transient windows (non-saved, temporary overlay over hundreds of objects) to "clean" up from the global window list. perhaps a lightweight explicit cleanup pass. + - window: calling SetNextWindowSize() every frame with <= 0 doesn't do anything, may be useful to allow (particularly when used for a single axis). + - window: auto-fit feedback loop when user relies on any dynamic layout (window width multiplier, column) appears weird to end-user. clarify. - window: allow resizing of child windows (possibly given min/max for each axis?) - window: background options for child windows, border option (disable rounding) + - window: add a way to clear an existing window instead of appending (e.g. for tooltip override using a consistent api rather than the deferred tooltip) - window: resizing from any sides? + mouse cursor directives for app. +!- window: begin with *p_open == false should return false. + - window: get size/pos helpers given names (see discussion in #249) + - window: a collapsed window can be stuck behind the main menu bar? + - window: when window is small, prioritize resize button over close button. + - window: detect extra End() call that pop the "Debug" window out and assert at call site instead of later. + - window/tooltip: allow to set the width of a tooltip to allow TextWrapped() etc. while keeping the height automatic. + - window: increase minimum size of a window with menus or fix the menu rendering so that it doesn't look odd. + - draw-list: maintaining bounding box per command would allow to merge draw command when clipping isn't relied on (typical non-scrolling window or non-overflowing column would merge with previous command). +!- scrolling: allow immediately effective change of scroll if we haven't appended items yet + - splitter/separator: formalize the splitter idiom into an official api (we want to handle n-way split) (#319) - widgets: display mode: widget-label, label-widget (aligned on column or using fixed size), label-newline-tab-widget etc. - widgets: clean up widgets internal toward exposing everything. - - main: considering adding EndFrame()/Init(). some constructs are awkward in the implementation because of the lack of them. + - widgets: add disabled and read-only modes (#211) + - main: considering adding an Init() function? some constructs are awkward in the implementation because of the lack of them. +!- main: make it so that a frame with no window registered won't refocus every window on subsequent frames (~bump LastFrameActive of all windows). - main: IsItemHovered() make it more consistent for various type of widgets, widgets with multiple components, etc. also effectively IsHovered() region sometimes differs from hot region, e.g tree nodes - main: IsItemHovered() info stored in a stack? so that 'if TreeNode() { Text; TreePop; } if IsHovered' return the hover state of the TreeNode? - - input text: add ImGuiInputTextFlags_EnterToApply? (off github issue #218) -!- input number: large int not reliably supported because of int<>float conversions. + - input text: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now. + - input text: reorganize event handling, allow CharFilter to modify buffers, allow multiple events? (#541) + - input text: flag to disable live update of the user buffer (also applies to float/int text input) + - input text: resize behavior - field could stretch when being edited? hover tooltip shows more text? + - input text: add ImGuiInputTextFlags_EnterToApply? (off #218) + - input text multi-line: don't directly call AddText() which does an unnecessary vertex reserve for character count prior to clipping. and/or more line-based clipping to AddText(). and/or reorganize TextUnformatted/RenderText for more efficiency for large text (e.g TextUnformatted could clip and log separately, etc). + - input text multi-line: way to dynamically grow the buffer without forcing the user to initially allocate for worse case (follow up on #200) + - input text multi-line: line numbers? status bar? (follow up on #200) + - input text: allow centering/positioning text so that ctrl+clicking Drag or Slider keeps the textual value at the same pixel position. - input number: optional range min/max for Input*() functions - input number: holding [-]/[+] buttons could increase the step speed non-linearly (or user-controlled) - input number: use mouse wheel to step up/down - - input number: non-decimal input. + - input number: applying arithmetics ops (+,-,*,/) messes up with text edit undo stack. + - button: provide a button that looks framed. - text: proper alignment options - - layout: horizontal layout helper (github issue #97) + - image/image button: misalignment on padded/bordered button? + - image/image button: parameters are confusing, image() has tint_col,border_col whereas imagebutton() has bg_col/tint_col. Even thou they are different parameters ordering could be more consistent. can we fix that? + - layout: horizontal layout helper (#97) + - layout: horizontal flow until no space left (#404) - layout: more generic alignment state (left/right/centered) for single items? - layout: clean up the InputFloatN/SliderFloatN/ColorEdit4 layout code. item width should include frame padding. - - columns: separator function or parameter that works within the column (currently Separator() bypass all columns) (github issue #125) - - columns: declare column set (each column: fixed size, %, fill, distribute default size among fills) (github issue #125) - - columns: columns header to act as button (~sort op) and allow resize/reorder (github issue #125) - - columns: user specify columns size (github issue #125) - - popup: border options. richer api like BeginChild() perhaps? (github issue #197) - - combo: sparse combo boxes (via function call?) - - combo: turn child handling code into pop up helper + - layout: BeginGroup() needs a border option. + - columns: declare column set (each column: fixed size, %, fill, distribute default size among fills) (#513, #125) + - columns: add a conditional parameter to SetColumnOffset() (#513, #125) + - columns: separator function or parameter that works within the column (currently Separator() bypass all columns) (#125) + - columns: columns header to act as button (~sort op) and allow resize/reorder (#513, #125) + - columns: user specify columns size (#513, #125) + - columns: flag to add horizontal separator above/below? + - columns/layout: setup minimum line height (equivalent of automatically calling AlignFirstTextHeightToWidgets) + - combo: sparse combo boxes (via function call?) / iterators - combo: contents should extends to fit label if combo widget is small - - combo/listbox: keyboard control. need inputtext like non-active focus + key handling. considering keybord for custom listbox (see github pr #203) + - combo/listbox: keyboard control. need InputText-like non-active focus + key handling. considering keyboard for custom listbox (pr #203) - listbox: multiple selection - listbox: user may want to initial scroll to focus on the one selected value? - ! menubar, menus (github issue #126) - - tabs - - gauge: various forms of gauge/loading bars widgets - - color: better color editor. + - listbox: keyboard navigation. + - listbox: scrolling should track modified selection. +!- popups/menus: clarify usage of popups id, how MenuItem/Selectable closing parent popups affects the ID, etc. this is quite fishy needs improvement! (#331, #402) + - popups: add variant using global identifier similar to Begin/End (#402) + - popups: border options. richer api like BeginChild() perhaps? (#197) + - tooltip: tooltip that doesn't fit in entire screen seems to lose their "last prefered button" and may teleport when moving mouse + - menus: local shortcuts, global shortcuts (#456, #126) + - menus: icons + - menus: menubars: some sort of priority / effect of main menu-bar on desktop size? + - menus: calling BeginMenu() twice with a same name doesn't seem to append nicely + - statusbar: add a per-window status bar helper similar to what menubar does. + - tabs (#261, #351) + - separator: separator on the initial position of a window is not visible (cursorpos.y <= clippos.y) +!- color: the color helpers/typing is a mess and needs sorting out. + - color: add a better color picker (#346) + - node/graph editor (#306) + - pie menus patterns (#434) + - drag'n drop, dragging helpers (carry dragging info, visualize drag source before clicking, drop target, etc.) (#143, #479) + - plot: PlotLines() should use the polygon-stroke facilities (currently issues with averaging normals) - plot: make it easier for user to draw extra stuff into the graph (e.g: draw basis, highlight certain points, 2d plots, multiple plots) - plot: "smooth" automatic scale over time, user give an input 0.0(full user scale) 1.0(full derived from value) - plot: add a helper e.g. Plot(char* label, float value, float time_span=2.0f) that stores values and Plot them for you - probably another function name. and/or automatically allow to plot ANY displayed value (more reliance on stable ID) - - file selection widget -> build the tool in our codebase to improve model-dialog idioms - slider: allow using the [-]/[+] buttons used by InputFloat()/InputInt() - slider: initial absolute click is imprecise. change to relative movement slider (same as scrollbar). - slider: add dragging-based widgets to edit values with mouse (on 2 axises), saving screen real-estate. - - text edit: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now. - - text edit: centered text for slider as input text so it matches typical positioning. - - text edit: flag to disable live update of the user buffer. - - text edit: field resize behavior - field could stretch when being edited? hover tooltip shows more text? - - text edit: add multi-line text edit - - tree: add treenode/treepush int variants? because (void*) cast from int warns on some platforms/settings + - slider: tint background based on value (e.g. v_min -> v_max, or use 0.0f either side of the sign) + - slider & drag: int data passing through a float + - drag float: up/down axis + - drag float: added leeway on edge (e.g. a few invisible steps past the clamp limits) + - tree node / optimization: avoid formatting when clipped. + - tree node: tree-node/header right-most side doesn't take account of horizontal scrolling. + - tree node: add treenode/treepush int variants? not there because (void*) cast from int warns on some platforms/settings? + - tree node: try to apply scrolling at time of TreePop() if node was just opened and end of node is past scrolling limits? + - tree node / selectable render mismatch which is visible if you use them both next to each other (e.g. cf. property viewer) + - tree node: tweak color scheme to distinguish headers from selected tree node (#581) + - textwrapped: figure out better way to use TextWrapped() in an always auto-resize context (tooltip, etc.) (#249) - settings: write more decent code to allow saving/loading new fields - settings: api for per-tool simple persistent data (bool,int,float,columns sizes,etc.) in .ini file - ! style: store rounded corners in texture to use 1 quad per corner (filled and wireframe). so rounding have minor cost. - - style: checkbox: padding for "active" color should be a multiplier of the - - style: colorbox not always square? + - style: add window shadows. + - style/optimization: store rounded corners in texture to use 1 quad per corner (filled and wireframe) to lower the cost of rounding. + - style: color-box not always square? + - style: a concept of "compact style" that the end-user can easily rely on (e.g. PushStyleCompact()?) that maps to other settings? avoid implementing duplicate helpers such as SmallCheckbox(), etc. + - style: try to make PushStyleVar() more robust to incorrect parameters (to be more friendly to edit & continues situation). + - style/opt: PopStyleVar could be optimized by having GetStyleVar returns the type, using a table mapping stylevar enum to data type. + - style: global scale setting. + - style: WindowPadding needs to be EVEN needs the 0.5 multiplier probably have a subtle effect on clip rectangle - text: simple markup language for color change? + - font: dynamic font atlas to avoid baking huge ranges into bitmap and make scaling easier. + - font: small opt: for monospace font (like the defalt one) we can trim IndexXAdvance as long as trailing value is == FallbackXAdvance + - font: add support for kerning, probably optional. perhaps default to (32..128)^2 matrix ~ 36KB then hash fallback. + - font: add a simpler CalcTextSizeA() api? current one ok but not welcome if user needs to call it directly (without going through ImGui::CalcTextSize) + - font: fix AddRemapChar() to work before font has been built. - log: LogButtons() options for specifying depth and/or hiding depth slider - log: have more control over the log scope (e.g. stop logging when leaving current tree node scope) - log: be able to log anything (e.g. right-click on a window/tree-node, shows context menu? log into tty/file/clipboard) @@ -385,17 +576,25 @@ - filters: set a current filter that tree node can automatically query to hide themselves - filters: handle wildcards (with implicit leading/trailing *), regexps - shortcuts: add a shortcut api, e.g. parse "&Save" and/or "Save (CTRL+S)", pass in to widgets or provide simple ways to use (button=activate, input=focus) - ! keyboard: tooltip & combo boxes are messing up / not honoring keyboard tabbing - - keyboard: full keyboard navigation and focus. - - input: rework IO to be able to pass actual events to fix temporal aliasing issues. +!- keyboard: tooltip & combo boxes are messing up / not honoring keyboard tabbing + - keyboard: full keyboard navigation and focus. (#323) + - focus: preserve ActiveId/focus stack state, e.g. when opening a menu and close it, previously selected InputText() focus gets restored (#622) + - focus: SetKeyboardFocusHere() on with >= 0 offset could be done on same frame (else latch and modulate on beginning of next frame) + - input: rework IO system to be able to pass actual ordered/timestamped events. (~#335, #71) + - input: allow to decide and pass explicit double-clicks (e.g. for windows by the CS_DBLCLKS style). - input: support track pad style scrolling & slider edit. - - portability: big-endian test/support (github issue #81) - - misc: mark printf compiler attributes on relevant functions - misc: provide a way to compile out the entire implementation while providing a dummy API (e.g. #define IMGUI_DUMMY_IMPL) - misc: double-clicking on title bar to minimize isn't consistent, perhaps move to single-click on left-most collapse icon? - - style editor: have a more global HSV setter (e.g. alter hue on all elements). consider replacing active/hovered by offset in HSV space? + - misc: provide HoveredTime and ActivatedTime to ease the creation of animations. + - style editor: have a more global HSV setter (e.g. alter hue on all elements). consider replacing active/hovered by offset in HSV space? (#438) - style editor: color child window height expressed in multiple of line height. - - optimization/render: use indexed rendering to reduce vertex data cost (e.g. for remote/networked imgui) + - remote: make a system like RemoteImGui first-class citizen/project (#75) + - drawlist: move Font, FontSize, FontTexUvWhitePixel inside ImDrawList and make it self-contained (apart from drawing settings?) + - drawlist: end-user probably can't call Clear() directly because we expect a texture to be pushed in the stack. + - examples: directx9: save/restore device state more thoroughly. + - examples: window minimize, maximize (#583) + - optimization: add a flag to disable most of rendering, for the case where the user expect to skip it (#335) + - optimization: use another hash function than crc32, e.g. FNV1a - optimization/render: merge command-lists with same clip-rect into one even if they aren't sequential? (as long as in-between clip rectangle don't overlap)? - optimization: turn some the various stack vectors into statically-sized arrays - optimization: better clipping for multi-component widgets @@ -406,10 +605,15 @@ #endif #include "imgui.h" +#define IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_PLACEMENT_NEW +#include "imgui_internal.h" + #include // toupper, isprint #include // sqrtf, fabsf, fmodf, powf, cosf, sinf, floorf, ceilf -#include // vsnprintf, sscanf -#include // new (ptr) +#include // NULL, malloc, free, qsort, atoi +#include // vsnprintf, sscanf, printf +#include // INT_MIN, INT_MAX #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier #include // intptr_t #else @@ -417,6 +621,7 @@ #endif #ifdef _MSC_VER +#pragma warning (disable: 4127) // condition expression is constant #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen #endif @@ -428,134 +633,90 @@ #pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. #pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it. -#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // -#pragma clang diagnostic ignored "-Wmissing-noreturn" // warning : function xx could be declared with attribute 'noreturn' warning // GetDefaultFontData() asserts which some implementation makes it never return. -#endif -#ifdef __GNUC__ +#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // +#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' // +#elif defined(__GNUC__) #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used -#endif - -//------------------------------------------------------------------------- -// STB libraries implementation -//------------------------------------------------------------------------- - -struct ImGuiTextEditState; - -//#define IMGUI_STB_NAMESPACE ImStb -//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION -//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION - -#ifdef IMGUI_STB_NAMESPACE -namespace IMGUI_STB_NAMESPACE -{ -#endif - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wmissing-prototypes" -#endif - -#define STBRP_ASSERT(x) IM_ASSERT(x) -#ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION -#define STBRP_STATIC -#define STB_RECT_PACK_IMPLEMENTATION -#endif -#include "stb_rect_pack.h" - -#define STBTT_malloc(x,u) ((void)(u), ImGui::MemAlloc(x)) -#define STBTT_free(x,u) ((void)(u), ImGui::MemFree(x)) -#define STBTT_assert(x) IM_ASSERT(x) -#ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION -#define STBTT_STATIC -#define STB_TRUETYPE_IMPLEMENTATION -#endif -#include "stb_truetype.h" - -#undef STB_TEXTEDIT_STRING -#undef STB_TEXTEDIT_CHARTYPE -#define STB_TEXTEDIT_STRING ImGuiTextEditState -#define STB_TEXTEDIT_CHARTYPE ImWchar -#include "stb_textedit.h" - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - -#ifdef IMGUI_STB_NAMESPACE -} // namespace ImStb -using namespace IMGUI_STB_NAMESPACE; +#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size +#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*' +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value #endif //------------------------------------------------------------------------- // Forward Declarations //------------------------------------------------------------------------- -struct ImRect; -struct ImGuiColMod; -struct ImGuiStyleMod; -struct ImGuiDrawContext; -struct ImGuiTextEditState; -struct ImGuiIniData; -struct ImGuiState; -struct ImGuiWindow; -typedef int ImGuiButtonFlags; // enum ImGuiButtonFlags_ +static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end = NULL); -static bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, bool allow_key_modifiers, ImGuiButtonFlags flags = 0); -static void LogText(const ImVec2& ref_pos, const char* text, const char* text_end = NULL); +static void PushMultiItemsWidths(int components, float w_full = 0.0f); +static float GetDraggedColumnOffset(int column_index); -static void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true); -static void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width); -static void RenderTextClipped(ImVec2 pos, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& pos_max, const ImVec2* clip_max = NULL, ImGuiAlign align = ImGuiAlign_Default); -static void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f); -static void RenderCollapseTriangle(ImVec2 p_min, bool opened, float scale = 1.0f, bool shadow = false); -static void RenderCheckMark(ImVec2 pos, ImU32 col); +static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true); -static void SetFont(ImFont* font); -static bool ItemAdd(const ImRect& bb, const ImGuiID* id); -static void ItemSize(ImVec2 size, float text_offset_y = 0.0f); -static void ItemSize(const ImRect& bb, float text_offset_y = 0.0f); -static void PushColumnClipRect(int column_index = -1); -static bool IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged); +static void SetCurrentFont(ImFont* font); +static void SetCurrentWindow(ImGuiWindow* window); +static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y); +static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond); +static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond cond); +static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond cond); +static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs); +static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags); +static inline bool IsWindowContentHoverable(ImGuiWindow* window); +static void ClearSetNextWindowData(); +static void CheckStacksSize(ImGuiWindow* window, bool write); +static void Scrollbar(ImGuiWindow* window, bool horizontal); -static bool IsMouseHoveringRect(const ImRect& bb); -static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true); +static void AddDrawListToRenderList(ImVector& out_render_list, ImDrawList* draw_list); +static void AddWindowToRenderList(ImVector& out_render_list, ImGuiWindow* window); +static void AddWindowToSortedBuffer(ImVector& out_sorted_windows, ImGuiWindow* window); -static void Scrollbar(ImGuiWindow* window); -static bool CloseWindowButton(bool* p_opened = NULL); -static void FocusWindow(ImGuiWindow* window); -static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs); +static ImGuiIniData* FindWindowSettings(const char* name); +static ImGuiIniData* AddWindowSettings(const char* name); +static void LoadSettings(); +static void SaveSettings(); +static void MarkSettingsDirty(); -// Helpers: String -static int ImStricmp(const char* str1, const char* str2); -static int ImStrnicmp(const char* str1, const char* str2, int count); -static char* ImStrdup(const char *str); -static size_t ImStrlenW(const ImWchar* str); -static const char* ImStristr(const char* haystack, const char* needle, const char* needle_end); -static size_t ImFormatString(char* buf, size_t buf_size, const char* fmt, ...); -static size_t ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args); +static void PushColumnClipRect(int column_index = -1); +static ImRect GetVisibleRect(); -// Helpers: Misc -static ImU32 ImHash(const void* data, size_t data_size, ImU32 seed); -static bool ImLoadFileToMemory(const char* filename, const char* file_open_mode, void** out_file_data, size_t* out_file_size, size_t padding_bytes = 0); -static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } -static inline bool ImCharIsSpace(int c) { return c == ' ' || c == '\t' || c == 0x3000; } +static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags); +static void CloseInactivePopups(); +static void ClosePopupToLevel(int remaining); +static void ClosePopup(ImGuiID id); +static bool IsPopupOpen(ImGuiID id); +static ImGuiWindow* GetFrontMostModalRootWindow(); +static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& rect_to_avoid); -// Helpers: UTF-8 <> wchar -static int ImTextCharToUtf8(char* buf, size_t buf_size, unsigned int in_char); // return output UTF-8 bytes count -static ptrdiff_t ImTextStrToUtf8(char* buf, size_t buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count -static int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end); // return input UTF-8 bytes count -static ptrdiff_t ImTextStrFromUtf8(ImWchar* buf, size_t buf_size, const char* in_text, const char* in_text_end, const char** in_remaining = NULL); // return input UTF-8 bytes count -static int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end); // return number of UTF-8 code-points (NOT bytes count) -static int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end); // return number of bytes to express string as UTF-8 code-points +static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data); +static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end); +static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false); + +static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size); +static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size); +static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2); +static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format); //----------------------------------------------------------------------------- // Platform dependent default implementations //----------------------------------------------------------------------------- -static const char* GetClipboardTextFn_DefaultImpl(); -static void SetClipboardTextFn_DefaultImpl(const char* text); -static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y); +static const char* GetClipboardTextFn_DefaultImpl(); +static void SetClipboardTextFn_DefaultImpl(const char* text); +static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y); + +//----------------------------------------------------------------------------- +// Context +//----------------------------------------------------------------------------- + +// Default context, default font atlas. +// New contexts always point by default to this font atlas. It can be changed by reassigning the GetIO().Fonts variable. +static ImGuiContext GImDefaultContext; +static ImFontAtlas GImDefaultFontAtlas; + +// Current context pointer. Implicitely used by all ImGui functions. Always assumed to be != NULL. Change to a different context by calling ImGui::SetCurrentContext() +// ImGui is currently not thread-safe because of this variable. If you want thread-safety to allow N threads to access N different contexts, you might work around it by (A) having two instances of the ImGui code under different namespaces or (B) change this variable to be TLS. Further development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586 +ImGuiContext* GImGui = &GImDefaultContext; //----------------------------------------------------------------------------- // User facing structures @@ -568,32 +729,39 @@ ImGuiStyle::ImGuiStyle() WindowMinSize = ImVec2(32,32); // Minimum window size WindowRounding = 9.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows WindowTitleAlign = ImGuiAlign_Left; // Alignment for title bar text - ChildWindowRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows + ChildWindowRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets) FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets). ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! - WindowFillAlphaDefault = 0.70f; // Default alpha of window background, if not specified in ImGui::Begin() - IndentSpacing = 22.0f; // Horizontal spacing when e.g. entering a tree node + IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns - ScrollbarWidth = 16.0f; // Width of the vertical scrollbar - ScrollbarRounding = 0.0f; // Radius of grab corners rounding for scrollbar + ScrollbarSize = 16.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar + ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar + GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. DisplayWindowPadding = ImVec2(22,22); // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows. DisplaySafeAreaPadding = ImVec2(4,4); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. + AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU. + AntiAliasedShapes = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) + CurveTessellationTol = 1.25f; // Tessellation tolerance. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. Colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); - Colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + Colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f); + Colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.70f); Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + Colors[ImGuiCol_PopupBg] = ImVec4(0.05f, 0.05f, 0.10f, 0.90f); Colors[ImGuiCol_Border] = ImVec4(0.70f, 0.70f, 0.70f, 0.65f); - Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.60f); + Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); Colors[ImGuiCol_FrameBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.30f); // Background of checkbox, radio button, plot, slider, text input Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.90f, 0.80f, 0.80f, 0.40f); Colors[ImGuiCol_FrameBgActive] = ImVec4(0.90f, 0.65f, 0.65f, 0.45f); - Colors[ImGuiCol_TitleBg] = ImVec4(0.50f, 0.50f, 1.00f, 0.45f); + Colors[ImGuiCol_TitleBg] = ImVec4(0.27f, 0.27f, 0.54f, 0.83f); Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f); - Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.40f, 0.40f, 0.80f, 0.15f); + Colors[ImGuiCol_TitleBgActive] = ImVec4(0.32f, 0.32f, 0.63f, 0.87f); + Colors[ImGuiCol_MenuBarBg] = ImVec4(0.40f, 0.40f, 0.55f, 0.80f); + Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.20f, 0.25f, 0.30f, 0.60f); Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f); Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f); Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 0.40f); @@ -621,13 +789,9 @@ ImGuiStyle::ImGuiStyle() Colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f); - Colors[ImGuiCol_TooltipBg] = ImVec4(0.05f, 0.05f, 0.10f, 0.90f); + Colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); } -// Statically allocated font atlas. This is merely a maneuver to keep ImFontAtlas definition at the bottom of the .h file (otherwise it'd be inside ImGuiIO) -// Also we wouldn't be able to new() one at this point, before users may define IO.MemAllocFn. -static ImFontAtlas GDefaultFontAtlas; - ImGuiIO::ImGuiIO() { // Most fields are initialized with zero @@ -638,13 +802,22 @@ ImGuiIO::ImGuiIO() IniSavingRate = 5.0f; IniFilename = "imgui.ini"; LogFilename = "imgui_log.txt"; - Fonts = &GDefaultFontAtlas; + Fonts = &GImDefaultFontAtlas; FontGlobalScale = 1.0f; + DisplayFramebufferScale = ImVec2(1.0f, 1.0f); MousePos = ImVec2(-1,-1); MousePosPrev = ImVec2(-1,-1); MouseDoubleClickTime = 0.30f; MouseDoubleClickMaxDist = 6.0f; MouseDragThreshold = 6.0f; + for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) + MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f; + for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) + KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f; + for (int i = 0; i < ImGuiKey_COUNT; i++) + KeyMap[i] = -1; + KeyRepeatDelay = 0.250f; + KeyRepeatRate = 0.050f; UserData = NULL; // User functions @@ -654,6 +827,14 @@ ImGuiIO::ImGuiIO() GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations SetClipboardTextFn = SetClipboardTextFn_DefaultImpl; ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl; + + // Set OS X style defaults based on __APPLE__ compile time flag +#ifdef __APPLE__ + WordMovementUsesAltKey = true; // OS X style: Text editing cursor movement using Alt instead of Ctrl + ShortcutsUseSuperKey = true; // OS X style: Shortcuts using Cmd/Super instead of Ctrl + DoubleClickSelectsWord = true; // OS X style: Double click selects by word instead of selecting whole text + MultiSelectUsesSuperKey = true; // OS X style: Multi-selection in lists uses Cmd/Super instead of Ctrl +#endif } // Pass in translated ASCII characters for text input. @@ -661,103 +842,87 @@ ImGuiIO::ImGuiIO() // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message void ImGuiIO::AddInputCharacter(ImWchar c) { - const size_t n = ImStrlenW(InputCharacters); - if (n + 1 < sizeof(InputCharacters) / sizeof(InputCharacters[0])) + const int n = ImStrlenW(InputCharacters); + if (n + 1 < IM_ARRAYSIZE(InputCharacters)) { InputCharacters[n] = c; - InputCharacters[n+1] = 0; + InputCharacters[n+1] = '\0'; } } +void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars) +{ + // We can't pass more wchars than ImGuiIO::InputCharacters[] can hold so don't convert more + const int wchars_buf_len = sizeof(ImGuiIO::InputCharacters) / sizeof(ImWchar); + ImWchar wchars[wchars_buf_len]; + ImTextStrFromUtf8(wchars, wchars_buf_len, utf8_chars, NULL); + for (int i = 0; i < wchars_buf_len && wchars[i] != 0; i++) + AddInputCharacter(wchars[i]); +} + //----------------------------------------------------------------------------- -// Helpers +// HELPERS //----------------------------------------------------------------------------- -#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) - -#undef PI -const float PI = 3.14159265358979323846f; - -#ifdef INT_MAX -#define IM_INT_MIN INT_MIN -#define IM_INT_MAX INT_MAX -#else -#define IM_INT_MIN (-2147483647-1) -#define IM_INT_MAX (2147483647) -#endif +#define IM_F32_TO_INT8(_VAL) ((int)((_VAL) * 255.0f + 0.5f)) // Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n. -#ifdef _MSC_VER -#define STR_NEWLINE "\r\n" +#ifdef _WIN32 +#define IM_NEWLINE "\r\n" #else -#define STR_NEWLINE "\n" +#define IM_NEWLINE "\n" #endif -// Math bits -// We are keeping those static in the .cpp file so as not to leak them outside, in the case the user has implicit cast operators between ImVec2 and its own types. -static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x*rhs, lhs.y*rhs); } -//static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x/rhs, lhs.y/rhs); } -static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x+rhs.x, lhs.y+rhs.y); } -static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x-rhs.x, lhs.y-rhs.y); } -static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2 rhs) { return ImVec2(lhs.x*rhs.x, lhs.y*rhs.y); } -static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2 rhs) { return ImVec2(lhs.x/rhs.x, lhs.y/rhs.y); } -static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } -static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } -static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } -//static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } -static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x-rhs.x, lhs.y-rhs.y, lhs.z-rhs.z, lhs.w-lhs.w); } +bool ImIsPointInTriangle(const ImVec2& p, const ImVec2& a, const ImVec2& b, const ImVec2& c) +{ + bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f; + bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f; + bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f; + return ((b1 == b2) && (b2 == b3)); +} -static inline int ImMin(int lhs, int rhs) { return lhs < rhs ? lhs : rhs; } -static inline int ImMax(int lhs, int rhs) { return lhs >= rhs ? lhs : rhs; } -static inline float ImMin(float lhs, float rhs) { return lhs < rhs ? lhs : rhs; } -static inline float ImMax(float lhs, float rhs) { return lhs >= rhs ? lhs : rhs; } -static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMin(lhs.x,rhs.x), ImMin(lhs.y,rhs.y)); } -static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMax(lhs.x,rhs.x), ImMax(lhs.y,rhs.y)); } -static inline int ImClamp(int v, int mn, int mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } -static inline float ImClamp(float v, float mn, float mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } -static inline ImVec2 ImClamp(const ImVec2& f, const ImVec2& mn, ImVec2 mx) { return ImVec2(ImClamp(f.x,mn.x,mx.x), ImClamp(f.y,mn.y,mx.y)); } -static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; } -static inline float ImLerp(float a, float b, float t) { return a + (b - a) * t; } -static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t) { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); } -static inline float ImLengthSqr(const ImVec2& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y; } -static inline float ImLengthSqr(const ImVec4& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y + lhs.z*lhs.z + lhs.w*lhs.w; } - -static int ImStricmp(const char* str1, const char* str2) +int ImStricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } -static int ImStrnicmp(const char* str1, const char* str2, int count) +int ImStrnicmp(const char* str1, const char* str2, int count) { int d = 0; while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; } return d; } -static char* ImStrdup(const char *str) +char* ImStrdup(const char *str) { - char *buff = (char*)ImGui::MemAlloc(strlen(str) + 1); - IM_ASSERT(buff); - strcpy(buff, str); - return buff; + size_t len = strlen(str) + 1; + void* buff = ImGui::MemAlloc(len); + return (char*)memcpy(buff, (const void*)str, len); } -static size_t ImStrlenW(const ImWchar* str) +int ImStrlenW(const ImWchar* str) { - size_t n = 0; + int n = 0; while (*str++) n++; return n; } -static const char* ImStristr(const char* haystack, const char* needle, const char* needle_end) +const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line +{ + while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n') + buf_mid_line--; + return buf_mid_line; +} + +const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end) { if (!needle_end) needle_end = needle + strlen(needle); const char un0 = (char)toupper(*needle); - while (*haystack) + while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end)) { if (toupper(*haystack) == un0) { @@ -773,32 +938,49 @@ static const char* ImStristr(const char* haystack, const char* needle, const cha return NULL; } -// Pass data_size==0 for zero-terminated string -// Try to replace with FNV1a hash? -static ImU32 ImHash(const void* data, size_t data_size, ImU32 seed = 0) -{ +int ImFormatString(char* buf, int buf_size, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + int w = vsnprintf(buf, buf_size, fmt, args); + va_end(args); + buf[buf_size-1] = 0; + return (w == -1) ? buf_size : w; +} + +int ImFormatStringV(char* buf, int buf_size, const char* fmt, va_list args) +{ + int w = vsnprintf(buf, buf_size, fmt, args); + buf[buf_size-1] = 0; + return (w == -1) ? buf_size : w; +} + +// Pass data_size==0 for zero-terminated strings +// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements. +ImU32 ImHash(const void* data, int data_size, ImU32 seed) +{ static ImU32 crc32_lut[256] = { 0 }; if (!crc32_lut[1]) { const ImU32 polynomial = 0xEDB88320; - for (ImU32 i = 0; i < 256; i++) - { - ImU32 crc = i; - for (ImU32 j = 0; j < 8; j++) - crc = (crc >> 1) ^ (ImU32(-int(crc & 1)) & polynomial); - crc32_lut[i] = crc; + for (ImU32 i = 0; i < 256; i++) + { + ImU32 crc = i; + for (ImU32 j = 0; j < 8; j++) + crc = (crc >> 1) ^ (ImU32(-int(crc & 1)) & polynomial); + crc32_lut[i] = crc; } } seed = ~seed; - ImU32 crc = seed; + ImU32 crc = seed; const unsigned char* current = (const unsigned char*)data; if (data_size > 0) { // Known size - while (data_size--) - crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++]; + while (data_size--) + crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++]; } else { @@ -807,7 +989,7 @@ static ImU32 ImHash(const void* data, size_t data_size, ImU32 seed = 0) { // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed. // Because this syntax is rarely used we are optimizing for the common case. - // - If we reach ### in the string we discard the hash so far and reset to the seed. + // - If we reach ### in the string we discard the hash so far and reset to the seed. // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller. if (c == '#' && current[0] == '#' && current[1] == '#') crc = seed; @@ -815,32 +997,198 @@ static ImU32 ImHash(const void* data, size_t data_size, ImU32 seed = 0) crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c]; } } - return ~crc; -} - -static size_t ImFormatString(char* buf, size_t buf_size, const char* fmt, ...) -{ - va_list args; - va_start(args, fmt); - int w = vsnprintf(buf, buf_size, fmt, args); - va_end(args); - buf[buf_size-1] = 0; - return (w == -1) ? buf_size : (size_t)w; + return ~crc; } -static size_t ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args) +//----------------------------------------------------------------------------- +// ImText* helpers +//----------------------------------------------------------------------------- + +// Convert UTF-8 to 32-bits character, process single character input. +// Based on stb_from_utf8() from github.com/nothings/stb/ +// We handle UTF-8 decoding error by skipping forward. +int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end) { - int w = vsnprintf(buf, buf_size, fmt, args); - buf[buf_size-1] = 0; - return (w == -1) ? buf_size : (size_t)w; + unsigned int c = (unsigned int)-1; + const unsigned char* str = (const unsigned char*)in_text; + if (!(*str & 0x80)) + { + c = (unsigned int)(*str++); + *out_char = c; + return 1; + } + if ((*str & 0xe0) == 0xc0) + { + *out_char = 0xFFFD; // will be invalid but not end of string + if (in_text_end && in_text_end - (const char*)str < 2) return 1; + if (*str < 0xc2) return 2; + c = (unsigned int)((*str++ & 0x1f) << 6); + if ((*str & 0xc0) != 0x80) return 2; + c += (*str++ & 0x3f); + *out_char = c; + return 2; + } + if ((*str & 0xf0) == 0xe0) + { + *out_char = 0xFFFD; // will be invalid but not end of string + if (in_text_end && in_text_end - (const char*)str < 3) return 1; + if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3; + if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below + c = (unsigned int)((*str++ & 0x0f) << 12); + if ((*str & 0xc0) != 0x80) return 3; + c += (unsigned int)((*str++ & 0x3f) << 6); + if ((*str & 0xc0) != 0x80) return 3; + c += (*str++ & 0x3f); + *out_char = c; + return 3; + } + if ((*str & 0xf8) == 0xf0) + { + *out_char = 0xFFFD; // will be invalid but not end of string + if (in_text_end && in_text_end - (const char*)str < 4) return 1; + if (*str > 0xf4) return 4; + if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4; + if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below + c = (unsigned int)((*str++ & 0x07) << 18); + if ((*str & 0xc0) != 0x80) return 4; + c += (unsigned int)((*str++ & 0x3f) << 12); + if ((*str & 0xc0) != 0x80) return 4; + c += (unsigned int)((*str++ & 0x3f) << 6); + if ((*str & 0xc0) != 0x80) return 4; + c += (*str++ & 0x3f); + // utf-8 encodings of values used in surrogate pairs are invalid + if ((c & 0xFFFFF800) == 0xD800) return 4; + *out_char = c; + return 4; + } + *out_char = 0; + return 0; +} + +int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining) +{ + ImWchar* buf_out = buf; + ImWchar* buf_end = buf + buf_size; + while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c; + in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); + if (c == 0) + break; + if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes + *buf_out++ = (ImWchar)c; + } + *buf_out = 0; + if (in_text_remaining) + *in_text_remaining = in_text; + return (int)(buf_out - buf); +} + +int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end) +{ + int char_count = 0; + while ((!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c; + in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); + if (c == 0) + break; + if (c < 0x10000) + char_count++; + } + return char_count; +} + +// Based on stb_to_utf8() from github.com/nothings/stb/ +static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c) +{ + if (c < 0x80) + { + buf[0] = (char)c; + return 1; + } + if (c < 0x800) + { + if (buf_size < 2) return 0; + buf[0] = (char)(0xc0 + (c >> 6)); + buf[1] = (char)(0x80 + (c & 0x3f)); + return 2; + } + if (c >= 0xdc00 && c < 0xe000) + { + return 0; + } + if (c >= 0xd800 && c < 0xdc00) + { + if (buf_size < 4) return 0; + buf[0] = (char)(0xf0 + (c >> 18)); + buf[1] = (char)(0x80 + ((c >> 12) & 0x3f)); + buf[2] = (char)(0x80 + ((c >> 6) & 0x3f)); + buf[3] = (char)(0x80 + ((c ) & 0x3f)); + return 4; + } + //else if (c < 0x10000) + { + if (buf_size < 3) return 0; + buf[0] = (char)(0xe0 + (c >> 12)); + buf[1] = (char)(0x80 + ((c>> 6) & 0x3f)); + buf[2] = (char)(0x80 + ((c ) & 0x3f)); + return 3; + } +} + +static inline int ImTextCountUtf8BytesFromChar(unsigned int c) +{ + if (c < 0x80) return 1; + if (c < 0x800) return 2; + if (c >= 0xdc00 && c < 0xe000) return 0; + if (c >= 0xd800 && c < 0xdc00) return 4; + return 3; +} + +int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end) +{ + char* buf_out = buf; + const char* buf_end = buf + buf_size; + while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c = (unsigned int)(*in_text++); + if (c < 0x80) + *buf_out++ = (char)c; + else + buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c); + } + *buf_out = 0; + return (int)(buf_out - buf); +} + +int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end) +{ + int bytes_count = 0; + while ((!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c = (unsigned int)(*in_text++); + if (c < 0x80) + bytes_count++; + else + bytes_count += ImTextCountUtf8BytesFromChar(c); + } + return bytes_count; +} + +ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in) +{ + float s = 1.0f/255.0f; + return ImVec4((in & 0xFF) * s, ((in >> 8) & 0xFF) * s, ((in >> 16) & 0xFF) * s, (in >> 24) * s); } ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in) { - ImU32 out = ((ImU32)(ImSaturate(in.x)*255.f)); - out |= ((ImU32)(ImSaturate(in.y)*255.f) << 8); - out |= ((ImU32)(ImSaturate(in.z)*255.f) << 16); - out |= ((ImU32)(ImSaturate(in.w)*255.f) << 24); + ImU32 out; + out = ((ImU32)IM_F32_TO_INT8(ImSaturate(in.x))); + out |= ((ImU32)IM_F32_TO_INT8(ImSaturate(in.y))) << 8; + out |= ((ImU32)IM_F32_TO_INT8(ImSaturate(in.z))) << 16; + out |= ((ImU32)IM_F32_TO_INT8(ImSaturate(in.w))) << 24; return out; } @@ -869,7 +1217,7 @@ void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593 // also http://en.wikipedia.org/wiki/HSL_and_HSV void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b) -{ +{ if (s == 0.0f) { // gray @@ -897,485 +1245,48 @@ void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& // Load file content into memory // Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree() -static bool ImLoadFileToMemory(const char* filename, const char* file_open_mode, void** out_file_data, size_t* out_file_size, size_t padding_bytes) +void* ImLoadFileToMemory(const char* filename, const char* file_open_mode, int* out_file_size, int padding_bytes) { - IM_ASSERT(filename && file_open_mode && out_file_data && out_file_size); - *out_file_data = NULL; - *out_file_size = 0; + IM_ASSERT(filename && file_open_mode); + if (out_file_size) + *out_file_size = 0; FILE* f; if ((f = fopen(filename, file_open_mode)) == NULL) - return false; + return NULL; long file_size_signed; if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET)) { fclose(f); - return false; + return NULL; } - size_t file_size = (size_t)file_size_signed; + int file_size = (int)file_size_signed; void* file_data = ImGui::MemAlloc(file_size + padding_bytes); if (file_data == NULL) { fclose(f); - return false; + return NULL; } - if (fread(file_data, 1, file_size, f) != file_size) + if (fread(file_data, 1, (size_t)file_size, f) != (size_t)file_size) { fclose(f); ImGui::MemFree(file_data); - return false; + return NULL; } if (padding_bytes > 0) memset((void *)(((char*)file_data) + file_size), 0, padding_bytes); fclose(f); - *out_file_data = file_data; - *out_file_size = file_size; + if (out_file_size) + *out_file_size = file_size; - return true; + return file_data; } //----------------------------------------------------------------------------- - -enum ImGuiButtonFlags_ -{ - ImGuiButtonFlags_Repeat = (1 << 0), - ImGuiButtonFlags_PressedOnClick = (1 << 1), - ImGuiButtonFlags_FlattenChilds = (1 << 2) -}; - -struct ImGuiColMod // Color modifier, backup of modified data so we can restore it -{ - ImGuiCol Col; - ImVec4 PreviousValue; -}; - -struct ImGuiStyleMod // Style modifier, backup of modified data so we can restore it -{ - ImGuiStyleVar Var; - ImVec2 PreviousValue; -}; - -struct ImRect // 2D axis aligned bounding-box -{ - ImVec2 Min; - ImVec2 Max; - - ImRect() { Min = ImVec2(FLT_MAX,FLT_MAX); Max = ImVec2(-FLT_MAX,-FLT_MAX); } - ImRect(const ImVec2& min, const ImVec2& max) { Min = min; Max = max; } - ImRect(const ImVec4& v) { Min.x = v.x; Min.y = v.y; Max.x = v.z; Max.y = v.w; } - ImRect(float x1, float y1, float x2, float y2) { Min.x = x1; Min.y = y1; Max.x = x2; Max.y = y2; } - - ImVec2 GetCenter() const { return Min + (Max-Min)*0.5f; } - ImVec2 GetSize() const { return Max-Min; } - float GetWidth() const { return (Max-Min).x; } - float GetHeight() const { return (Max-Min).y; } - ImVec2 GetTL() const { return Min; } - ImVec2 GetTR() const { return ImVec2(Max.x,Min.y); } - ImVec2 GetBL() const { return ImVec2(Min.x,Max.y); } - ImVec2 GetBR() const { return Max; } - bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; } - bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x < Max.x && r.Max.y < Max.y; } - bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; } - void Add(const ImVec2& rhs) { Min.x = ImMin(Min.x, rhs.x); Min.y = ImMin(Min.y, rhs.y); Max.x = ImMax(Max.x, rhs.x); Max.y = ImMax(Max.x, rhs.x); } - void Add(const ImRect& rhs) { Min.x = ImMin(Min.x, rhs.Min.x); Min.y = ImMin(Min.y, rhs.Min.y); Max.x = ImMax(Max.x, rhs.Max.x); Max.y = ImMax(Max.y, rhs.Max.y); } - void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; } - void Expand(const ImVec2& amount) { Min -= amount; Max += amount; } - void Reduce(const ImVec2& amount) { Min += amount; Max -= amount; } - void Clip(const ImRect& clip) { Min.x = ImMax(Min.x, clip.Min.x); Min.y = ImMax(Min.y, clip.Min.y); Max.x = ImMin(Max.x, clip.Max.x); Max.y = ImMin(Max.y, clip.Max.y); } - ImVec2 GetClosestPoint(ImVec2 p, bool on_edge) const - { - if (!on_edge && Contains(p)) - return p; - if (p.x > Max.x) p.x = Max.x; - else if (p.x < Min.x) p.x = Min.x; - if (p.y > Max.y) p.y = Max.y; - else if (p.y < Min.y) p.y = Min.y; - return p; - } -}; -typedef ImRect ImGuiAabb; // FIXME-OBSOLETE - -struct ImGuiGroupData -{ - ImVec2 BackupCursorPos; - ImVec2 BackupCursorMaxPos; - float BackupColumnsStartX; - float BackupCurrentLineHeight; - float BackupCurrentLineTextBaseOffset; - float BackupLogLinePosY; -}; - -// Temporary per-window data, reset at the beginning of the frame -struct ImGuiDrawContext -{ - ImVec2 CursorPos; - ImVec2 CursorPosPrevLine; - ImVec2 CursorStartPos; - ImVec2 CursorMaxPos; // Implicitly calculate the size of our contents, always extending. Saved into window->SizeContents at the end of the frame - float CurrentLineHeight; - float CurrentLineTextBaseOffset; - float PrevLineHeight; - float PrevLineTextBaseOffset; - float LogLinePosY; - int TreeDepth; - ImGuiID LastItemID; - ImRect LastItemRect; - bool LastItemHoveredAndUsable; - bool LastItemHoveredRect; - ImVector ChildWindows; - ImVector AllowKeyboardFocus; - ImVector ItemWidth; // 0.0: default, >0.0: width in pixels, <0.0: align xx pixels to the right of window - ImVector TextWrapPos; - ImVector GroupStack; - ImGuiColorEditMode ColorEditMode; - ImGuiStorage* StateStorage; - int StackSizesBackup[5]; // store size of various stacks for asserting - - float ColumnsStartX; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.) - float ColumnsOffsetX; // Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree->Column->Tree. Need revamp columns API. - int ColumnsCurrent; - int ColumnsCount; - ImVec2 ColumnsStartPos; - float ColumnsCellMinY; - float ColumnsCellMaxY; - bool ColumnsShowBorders; - ImGuiID ColumnsSetID; - ImVector ColumnsOffsetsT; // Columns offset normalized 0.0 (far left) -> 1.0 (far right) - - ImGuiDrawContext() - { - CursorPos = CursorPosPrevLine = CursorStartPos = CursorMaxPos = ImVec2(0.0f, 0.0f); - CurrentLineHeight = PrevLineHeight = 0.0f; - CurrentLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f; - LogLinePosY = -1.0f; - TreeDepth = 0; - LastItemID = 0; - LastItemRect = ImRect(0.0f,0.0f,0.0f,0.0f); - LastItemHoveredAndUsable = LastItemHoveredRect = false; - ColorEditMode = ImGuiColorEditMode_RGB; - StateStorage = NULL; - memset(StackSizesBackup, 0, sizeof(StackSizesBackup)); - - ColumnsStartX = 0.0f; - ColumnsOffsetX = 0.0f; - ColumnsCurrent = 0; - ColumnsCount = 1; - ColumnsStartPos = ImVec2(0.0f, 0.0f); - ColumnsCellMinY = ColumnsCellMaxY = 0.0f; - ColumnsShowBorders = true; - ColumnsSetID = 0; - } -}; - -// Internal state of the currently focused/edited text input box -struct ImGuiTextEditState -{ - ImGuiID Id; // widget id owning the text state - ImWchar Text[1024]; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer. - char InitialText[1024*3+1]; // backup of end-user buffer at the time of focus (in UTF-8, unaltered) - size_t CurLenA, CurLenW; // we need to maintain our buffer length in both UTF-8 and wchar format. - size_t BufSizeA; // end-user buffer size, <= 1024 (or increase above) - float Width; // widget width - float ScrollX; - STB_TexteditState StbState; - float CursorAnim; - ImVec2 InputCursorScreenPos; // Cursor position in screen space to be used by IME callback. - bool SelectedAllMouseLock; - ImFont* Font; - float FontSize; - - ImGuiTextEditState() { memset(this, 0, sizeof(*this)); } - - void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking - bool CursorIsVisible() const { return CursorAnim <= 0.0f || fmodf(CursorAnim, 1.20f) <= 0.80f; } // Blinking - bool HasSelection() const { return StbState.select_start != StbState.select_end; } - void SelectAll() { StbState.select_start = 0; StbState.select_end = (int)ImStrlenW(Text); StbState.cursor = StbState.select_end; StbState.has_preferred_x = false; } - - void OnKeyPressed(int key); - void UpdateScrollOffset(); - ImVec2 CalcDisplayOffsetFromCharIdx(int i) const; - - // Static functions because they are used to render non-focused instances of a text input box - static const char* GetTextPointerClippedA(ImFont* font, float font_size, const char* text, float width, ImVec2* out_text_size = NULL); - static const ImWchar* GetTextPointerClippedW(ImFont* font, float font_size, const ImWchar* text, float width, ImVec2* out_text_size = NULL); - static void RenderTextScrolledClipped(ImFont* font, float font_size, const char* text, ImVec2 pos_base, float width, float scroll_x); -}; - -// Data saved in imgui.ini file -struct ImGuiIniData -{ - char* Name; - ImGuiID ID; - ImVec2 Pos; - ImVec2 Size; - bool Collapsed; - - ImGuiIniData() { memset(this, 0, sizeof(*this)); } - ~ImGuiIniData() { if (Name) { ImGui::MemFree(Name); Name = NULL; } } -}; - -struct ImGuiMouseCursorData -{ - ImGuiMouseCursor Type; - ImVec2 Offset; - ImVec2 Size; - ImVec2 TexUvMin[2]; - ImVec2 TexUvMax[2]; -}; - -// Main state for ImGui -struct ImGuiState -{ - bool Initialized; - ImGuiIO IO; - ImGuiStyle Style; - ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back() - float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize() - float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Size of characters. - ImVec2 FontTexUvWhitePixel; // (Shortcut) == Font->TexUvForWhite - - float Time; - int FrameCount; - int FrameCountRendered; - ImVector Windows; - ImVector WindowsSortBuffer; - ImGuiWindow* CurrentWindow; // Being drawn into - ImVector CurrentWindowStack; - int CurrentPopupStackSize; - ImGuiWindow* FocusedWindow; // Will catch keyboard inputs - ImGuiWindow* HoveredWindow; // Will catch mouse inputs - ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only) - ImGuiID HoveredId; // Hovered widget - ImGuiID ActiveId; // Active widget - ImGuiID ActiveIdPreviousFrame; - bool ActiveIdIsAlive; - bool ActiveIdIsJustActivated; // Set when - bool ActiveIdIsFocusedOnly; // Set only by active widget. Denote focus but no active interaction. - ImGuiWindow* MovedWindow; // Track the child window we clicked on to move a window. Only valid if ActiveID is the "#MOVE" identifier of a window. - float SettingsDirtyTimer; - ImVector Settings; - int DisableHideTextAfterDoubleHash; - ImVector ColorModifiers; - ImVector StyleModifiers; - ImVector FontStack; - - ImVec2 SetNextWindowPosVal; - ImGuiSetCond SetNextWindowPosCond; - ImVec2 SetNextWindowSizeVal; - ImGuiSetCond SetNextWindowSizeCond; - bool SetNextWindowCollapsedVal; - ImGuiSetCond SetNextWindowCollapsedCond; - bool SetNextWindowFocus; - bool SetNextTreeNodeOpenedVal; - ImGuiSetCond SetNextTreeNodeOpenedCond; - - // Render - ImVector RenderDrawLists[3]; - - // Mouse cursor - ImGuiMouseCursor MouseCursor; - ImDrawList MouseCursorDrawList; // Optional software render of mouse cursors, if io.MouseDrawCursor is set - ImGuiMouseCursorData MouseCursorData[ImGuiMouseCursor_Count_]; - - // Widget state - ImGuiTextEditState InputTextState; - ImGuiID ScalarAsInputTextId; // Temporary text input when CTRL+clicking on a slider, etc. - ImGuiStorage ColorEditModeStorage; // for user selection - ImGuiID ActiveComboID; - ImVec2 ActiveClickDeltaToCenter; - float DragCurrentValue; // current dragged value, always float, not rounded by end-user precision settings - ImVec2 DragLastMouseDelta; - float DragSpeedDefaultRatio; // if speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio - float DragSpeedScaleSlow; - float DragSpeedScaleFast; - float ScrollbarClickDeltaToGrabCenter; // distance between mouse and center of grab box, normalized in parent space - char Tooltip[1024]; - char* PrivateClipboard; // if no custom clipboard handler is defined - - // Logging - bool LogEnabled; - FILE* LogFile; - ImGuiTextBuffer* LogClipboard; // pointer so our GImGui static constructor doesn't call heap allocators. - int LogStartDepth; - int LogAutoExpandMaxDepth; - - // Misc - float FramerateSecPerFrame[120]; // calculate estimate of framerate for user - int FramerateSecPerFrameIdx; - float FramerateSecPerFrameAccum; - char TempBuffer[1024*3+1]; // temporary text buffer - - ImGuiState() - { - Initialized = false; - Font = NULL; - FontBaseSize = FontSize = 0.0f; - FontTexUvWhitePixel = ImVec2(0.0f, 0.0f); - - Time = 0.0f; - FrameCount = 0; - FrameCountRendered = -1; - CurrentWindow = NULL; - CurrentPopupStackSize = 0; - FocusedWindow = NULL; - HoveredWindow = NULL; - HoveredRootWindow = NULL; - HoveredId = 0; - ActiveId = 0; - ActiveIdPreviousFrame = 0; - ActiveIdIsAlive = false; - ActiveIdIsJustActivated = false; - ActiveIdIsFocusedOnly = false; - MovedWindow = NULL; - SettingsDirtyTimer = 0.0f; - DisableHideTextAfterDoubleHash = 0; - - SetNextWindowPosVal = ImVec2(0.0f, 0.0f); - SetNextWindowPosCond = 0; - SetNextWindowSizeVal = ImVec2(0.0f, 0.0f); - SetNextWindowSizeCond = 0; - SetNextWindowCollapsedVal = false; - SetNextWindowCollapsedCond = 0; - SetNextWindowFocus = false; - SetNextTreeNodeOpenedVal = false; - SetNextTreeNodeOpenedCond = 0; - - ScalarAsInputTextId = 0; - ActiveComboID = 0; - ActiveClickDeltaToCenter = ImVec2(0.0f, 0.0f); - DragCurrentValue = 0.0f; - DragLastMouseDelta = ImVec2(0.0f, 0.0f); - DragSpeedDefaultRatio = 0.01f; - DragSpeedScaleSlow = 0.01f; - DragSpeedScaleFast = 10.0f; - ScrollbarClickDeltaToGrabCenter = 0.0f; - memset(Tooltip, 0, sizeof(Tooltip)); - PrivateClipboard = NULL; - - MouseCursor = ImGuiMouseCursor_Arrow; - - LogEnabled = false; - LogFile = NULL; - LogClipboard = NULL; - LogStartDepth = 0; - LogAutoExpandMaxDepth = 2; - - memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame)); - FramerateSecPerFrameIdx = 0; - FramerateSecPerFrameAccum = 0.0f; - } -}; - -static ImGuiState GImDefaultState; // Internal state storage -static ImGuiState* GImGui = &GImDefaultState; // We access everything through this pointer. NB: this pointer is always assumed to be != NULL - -struct ImGuiWindow -{ - char* Name; - ImGuiID ID; - ImGuiWindowFlags Flags; - ImVec2 PosFloat; - ImVec2 Pos; // Position rounded-up to nearest pixel - ImVec2 Size; // Current size (==SizeFull or collapsed title bar size) - ImVec2 SizeFull; // Size when non collapsed - ImVec2 SizeContents; // Size of contents (== extents reach of the drawing cursor) from previous frame - ImGuiID MoveID; // == window->GetID("#MOVE") - float ScrollY; - float NextScrollY; - bool ScrollbarY; - bool Active; // Set to true on Begin() - bool WasActive; - bool Accessed; // Set to true when any widget access the current window - bool Collapsed; // Set when collapsing window to become only title-bar - bool SkipItems; // == Visible && !Collapsed - int BeginCount; // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs) - int AutoFitFrames; - bool AutoFitOnlyGrows; - int AutoPosLastDirection; - int HiddenFrames; - int SetWindowPosAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowPos() call will succeed with this particular flag. - int SetWindowSizeAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowSize() call will succeed with this particular flag. - int SetWindowCollapsedAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowCollapsed() call will succeed with this particular flag. - - ImGuiDrawContext DC; // Temporary per-window data, reset at the beginning of the frame - ImVector IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack - ImVector ClipRectStack; // Scissoring / clipping rectangle. x1, y1, x2, y2. - ImRect ClippedRect; // = ClipRectStack.front() after setup in Begin() - int LastFrameDrawn; - float ItemWidthDefault; - ImGuiStorage StateStorage; - float FontWindowScale; // Scale multiplier per-window - ImDrawList* DrawList; - ImGuiWindow* RootWindow; - - // Focus - int FocusIdxAllCounter; // Start at -1 and increase as assigned via FocusItemRegister() - int FocusIdxTabCounter; // (same, but only count widgets which you can Tab through) - int FocusIdxAllRequestCurrent; // Item being requested for focus - int FocusIdxTabRequestCurrent; // Tab-able item being requested for focus - int FocusIdxAllRequestNext; // Item being requested for focus, for next update (relies on layout to be stable between the frame pressing TAB and the next frame) - int FocusIdxTabRequestNext; // " - -public: - ImGuiWindow(const char* name); - ~ImGuiWindow(); - - ImGuiID GetID(const char* str, const char* str_end = NULL); - ImGuiID GetID(const void* ptr); - - bool FocusItemRegister(bool is_active, bool tab_stop = true); // Return true if focus is requested - void FocusItemUnregister(); - - ImRect Rect() const { return ImRect(Pos, Pos+Size); } - float CalcFontSize() const { return GImGui->FontBaseSize * FontWindowScale; } - float TitleBarHeight() const { return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0 : CalcFontSize() + GImGui->Style.FramePadding.y * 2.0f; } - ImRect TitleBarRect() const { return ImRect(Pos, Pos + ImVec2(SizeFull.x, TitleBarHeight())); } - ImVec2 WindowPadding() const { return ((Flags & ImGuiWindowFlags_ChildWindow) && !(Flags & ImGuiWindowFlags_ShowBorders) && !(Flags & ImGuiWindowFlags_ComboBox)) ? ImVec2(0,0) : GImGui->Style.WindowPadding; } - ImU32 Color(ImGuiCol idx, float a=1.f) const { ImVec4 c = GImGui->Style.Colors[idx]; c.w *= GImGui->Style.Alpha * a; return ImGui::ColorConvertFloat4ToU32(c); } - ImU32 Color(const ImVec4& col) const { ImVec4 c = col; c.w *= GImGui->Style.Alpha; return ImGui::ColorConvertFloat4ToU32(c); } -}; - -static inline ImGuiWindow* GetCurrentWindow() -{ - // If this ever crash it probably means that ImGui::NewFrame() hasn't been called. We should always have a CurrentWindow in the stack (there is an implicit "Debug" window) - ImGuiState& g = *GImGui; - g.CurrentWindow->Accessed = true; - return g.CurrentWindow; -} - -static inline void SetCurrentWindow(ImGuiWindow* window) -{ - ImGuiState& g = *GImGui; - g.CurrentWindow = window; - if (window) - g.FontSize = window->CalcFontSize(); -} - -static inline ImGuiWindow* GetParentWindow() -{ - ImGuiState& g = *GImGui; - IM_ASSERT(g.CurrentWindowStack.size() >= 2); - return g.CurrentWindowStack[g.CurrentWindowStack.size() - 2]; -} - -static void SetActiveId(ImGuiID id) -{ - ImGuiState& g = *GImGui; - g.ActiveId = id; - g.ActiveIdIsFocusedOnly = false; - g.ActiveIdIsJustActivated = true; -} - -static void RegisterAliveId(ImGuiID id) -{ - ImGuiState& g = *GImGui; - if (g.ActiveId == id) - g.ActiveIdIsAlive = true; -} - +// ImGuiStorage //----------------------------------------------------------------------------- // Helper: Key->value storage @@ -1415,6 +1326,11 @@ int ImGuiStorage::GetInt(ImU32 key, int default_val) const return it->val_i; } +bool ImGuiStorage::GetBool(ImU32 key, bool default_val) const +{ + return GetInt(key, default_val ? 1 : 0) != 0; +} + float ImGuiStorage::GetFloat(ImU32 key, float default_val) const { ImVector::iterator it = LowerBound(const_cast&>(Data), key); @@ -1440,6 +1356,11 @@ int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val) return &it->val_i; } +bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val) +{ + return (bool*)GetIntRef(key, default_val ? 1 : 0); +} + float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val) { ImVector::iterator it = LowerBound(Data, key); @@ -1456,8 +1377,7 @@ void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val) return &it->val_p; } -// FIXME-OPT: Wasting CPU because all SetInt() are preceeded by GetInt() calls so we should have the result from lower_bound already in place. -// However we only use SetInt() on explicit user action (so that's maximum once a frame) so the optimisation isn't much needed. +// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame) void ImGuiStorage::SetInt(ImU32 key, int val) { ImVector::iterator it = LowerBound(Data, key); @@ -1469,6 +1389,11 @@ void ImGuiStorage::SetInt(ImU32 key, int val) it->val_i = val; } +void ImGuiStorage::SetBool(ImU32 key, bool val) +{ + SetInt(key, val ? 1 : 0); +} + void ImGuiStorage::SetFloat(ImU32 key, float val) { ImVector::iterator it = LowerBound(Data, key); @@ -1493,10 +1418,12 @@ void ImGuiStorage::SetVoidPtr(ImU32 key, void* val) void ImGuiStorage::SetAllInt(int v) { - for (size_t i = 0; i < Data.size(); i++) + for (int i = 0; i < Data.Size; i++) Data[i].val_i = v; } +//----------------------------------------------------------------------------- +// ImGuiTextFilter //----------------------------------------------------------------------------- // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" @@ -1514,14 +1441,16 @@ ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) } } -void ImGuiTextFilter::Draw(const char* label, float width) +bool ImGuiTextFilter::Draw(const char* label, float width) { - if (width > 0.0f) + if (width != 0.0f) ImGui::PushItemWidth(width); - ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf)); - if (width > 0.0f) + bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf)); + if (width != 0.0f) ImGui::PopItemWidth(); - Build(); + if (value_changed) + Build(); + return value_changed; } void ImGuiTextFilter::TextRange::split(char separator, ImVector& out) @@ -1549,7 +1478,7 @@ void ImGuiTextFilter::Build() input_range.split(',', Filters); CountGrep = 0; - for (size_t i = 0; i != Filters.size(); i++) + for (int i = 0; i != Filters.Size; i++) { Filters[i].trim_blanks(); if (Filters[i].empty()) @@ -1559,15 +1488,15 @@ void ImGuiTextFilter::Build() } } -bool ImGuiTextFilter::PassFilter(const char* val) const +bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const { if (Filters.empty()) return true; - if (val == NULL) - val = ""; + if (text == NULL) + text = ""; - for (size_t i = 0; i != Filters.size(); i++) + for (int i = 0; i != Filters.Size; i++) { const TextRange& f = Filters[i]; if (f.empty()) @@ -1575,13 +1504,13 @@ bool ImGuiTextFilter::PassFilter(const char* val) const if (f.front() == '-') { // Subtract - if (ImStristr(val, f.begin()+1, f.end()) != NULL) + if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL) return false; } else { // Grep - if (ImStristr(val, f.begin(), f.end()) != NULL) + if (ImStristr(text, text_end, f.begin(), f.end()) != NULL) return true; } } @@ -1593,9 +1522,11 @@ bool ImGuiTextFilter::PassFilter(const char* val) const return false; } +//----------------------------------------------------------------------------- +// ImGuiTextBuffer //----------------------------------------------------------------------------- -// On some platform vsnprintf() takes va_list by reference and modifies it. +// On some platform vsnprintf() takes va_list by reference and modifies it. // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it. #ifndef va_copy #define va_copy(dest, src) (dest = src) @@ -1611,16 +1542,16 @@ void ImGuiTextBuffer::appendv(const char* fmt, va_list args) if (len <= 0) return; - const size_t write_off = Buf.size(); - const size_t needed_sz = write_off + (size_t)len; - if (write_off + (size_t)len >= Buf.capacity()) + const int write_off = Buf.Size; + const int needed_sz = write_off + len; + if (write_off + len >= Buf.Capacity) { - const size_t double_capacity = Buf.capacity() * 2; + int double_capacity = Buf.Capacity * 2; Buf.reserve(needed_sz > double_capacity ? needed_sz : double_capacity); } Buf.resize(needed_sz); - ImFormatStringV(&Buf[write_off] - 1, (size_t)len+1, fmt, args_copy); + ImFormatStringV(&Buf[write_off] - 1, len+1, fmt, args_copy); } void ImGuiTextBuffer::append(const char* fmt, ...) @@ -1631,44 +1562,181 @@ void ImGuiTextBuffer::append(const char* fmt, ...) va_end(args); } +//----------------------------------------------------------------------------- +// ImGuiSimpleColumns +//----------------------------------------------------------------------------- + +ImGuiSimpleColumns::ImGuiSimpleColumns() +{ + Count = 0; + Spacing = Width = NextWidth = 0.0f; + memset(Pos, 0, sizeof(Pos)); + memset(NextWidths, 0, sizeof(NextWidths)); +} + +void ImGuiSimpleColumns::Update(int count, float spacing, bool clear) +{ + IM_ASSERT(Count <= IM_ARRAYSIZE(Pos)); + Count = count; + Width = NextWidth = 0.0f; + Spacing = spacing; + if (clear) memset(NextWidths, 0, sizeof(NextWidths)); + for (int i = 0; i < Count; i++) + { + if (i > 0 && NextWidths[i] > 0.0f) + Width += Spacing; + Pos[i] = (float)(int)Width; + Width += NextWidths[i]; + NextWidths[i] = 0.0f; + } +} + +float ImGuiSimpleColumns::DeclColumns(float w0, float w1, float w2) // not using va_arg because they promote float to double +{ + NextWidth = 0.0f; + NextWidths[0] = ImMax(NextWidths[0], w0); + NextWidths[1] = ImMax(NextWidths[1], w1); + NextWidths[2] = ImMax(NextWidths[2], w2); + for (int i = 0; i < 3; i++) + NextWidth += NextWidths[i] + ((i > 0 && NextWidths[i] > 0.0f) ? Spacing : 0.0f); + return ImMax(Width, NextWidth); +} + +float ImGuiSimpleColumns::CalcExtraSpace(float avail_w) +{ + return ImMax(0.0f, avail_w - Width); +} + +//----------------------------------------------------------------------------- +// ImGuiListClipper +//----------------------------------------------------------------------------- + +static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height) +{ + // Setting those fields so that SetScrollHere() can properly function after the end of our clipper usage. + // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list. + ImGui::SetCursorPosY(pos_y); + ImGuiWindow* window = ImGui::GetCurrentWindow(); + window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; + window->DC.PrevLineHeight = (line_height - GImGui->Style.ItemSpacing.y); +} + +// Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1 +// Use case B: Begin() called from constructor with items_height>0 +// FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style. +void ImGuiListClipper::Begin(int count, float items_height) +{ + StartPosY = ImGui::GetCursorPosY(); + ItemsHeight = items_height; + ItemsCount = count; + StepNo = 0; + DisplayEnd = DisplayStart = -1; + if (ItemsHeight > 0.0f) + { + ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display + if (DisplayStart > 0) + SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor + StepNo = 2; + } +} + +void ImGuiListClipper::End() +{ + if (ItemsCount < 0) + return; + // In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user. + if (ItemsCount < INT_MAX) + SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor + ItemsCount = -1; + StepNo = 3; +} + +bool ImGuiListClipper::Step() +{ + if (ItemsCount == 0 || ImGui::GetCurrentWindowRead()->SkipItems) + { + ItemsCount = -1; + return false; + } + if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height. + { + DisplayStart = 0; + DisplayEnd = 1; + StartPosY = ImGui::GetCursorPosY(); + StepNo = 1; + return true; + } + if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. + { + if (ItemsCount == 1) { ItemsCount = -1; return false; } + float items_height = ImGui::GetCursorPosY() - StartPosY; + IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically + ImGui::SetCursorPosY(StartPosY); // Rewind cursor so we can Begin() again, this time with a known height. + Begin(ItemsCount, items_height); + StepNo = 3; + return true; + } + if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3. + { + IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0); + StepNo = 3; + return true; + } + if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. + End(); + return false; +} + +//----------------------------------------------------------------------------- +// ImGuiWindow //----------------------------------------------------------------------------- ImGuiWindow::ImGuiWindow(const char* name) { Name = ImStrdup(name); - ID = ImHash(name, 0); + ID = ImHash(name, 0); IDStack.push_back(ID); MoveID = GetID("#MOVE"); Flags = 0; + IndexWithinParent = 0; PosFloat = Pos = ImVec2(0.0f, 0.0f); Size = SizeFull = ImVec2(0.0f, 0.0f); - SizeContents = ImVec2(0.0f, 0.0f); - ScrollY = 0.0f; - NextScrollY = 0.0f; - ScrollbarY = false; + SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f); + WindowPadding = ImVec2(0.0f, 0.0f); + Scroll = ImVec2(0.0f, 0.0f); + ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); + ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f); + ScrollbarX = ScrollbarY = false; + ScrollbarSizes = ImVec2(0.0f, 0.0f); + BorderSize = 0.0f; Active = WasActive = false; Accessed = false; Collapsed = false; SkipItems = false; BeginCount = 0; - AutoFitFrames = -1; + PopupID = 0; + AutoFitFramesX = AutoFitFramesY = -1; AutoFitOnlyGrows = false; AutoPosLastDirection = -1; HiddenFrames = 0; SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiSetCond_Always | ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing; + SetWindowPosCenterWanted = false; - LastFrameDrawn = -1; + LastFrameActive = -1; ItemWidthDefault = 0.0f; FontWindowScale = 1.0f; DrawList = (ImDrawList*)ImGui::MemAlloc(sizeof(ImDrawList)); - new(DrawList) ImDrawList(); + IM_PLACEMENT_NEW(DrawList) ImDrawList(); + DrawList->_OwnerName = Name; RootWindow = NULL; + RootNonPopupWindow = NULL; + ParentWindow = NULL; FocusIdxAllCounter = FocusIdxTabCounter = -1; - FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = IM_INT_MAX; - FocusIdxAllRequestNext = FocusIdxTabRequestNext = IM_INT_MAX; + FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX; + FocusIdxAllRequestNext = FocusIdxTabRequestNext = INT_MAX; } ImGuiWindow::~ImGuiWindow() @@ -1683,208 +1751,228 @@ ImGuiWindow::~ImGuiWindow() ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end) { ImGuiID seed = IDStack.back(); - const ImGuiID id = ImHash(str, str_end ? str_end - str : 0, seed); - RegisterAliveId(id); + ImGuiID id = ImHash(str, str_end ? (int)(str_end - str) : 0, seed); + ImGui::KeepAliveID(id); return id; } ImGuiID ImGuiWindow::GetID(const void* ptr) { ImGuiID seed = IDStack.back(); - const ImGuiID id = ImHash(&ptr, sizeof(void*), seed); - RegisterAliveId(id); + ImGuiID id = ImHash(&ptr, sizeof(void*), seed); + ImGui::KeepAliveID(id); return id; } -bool ImGuiWindow::FocusItemRegister(bool is_active, bool tab_stop) -{ - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); +//----------------------------------------------------------------------------- +// Internal API exposed in imgui_internal.h +//----------------------------------------------------------------------------- - const bool allow_keyboard_focus = window->DC.AllowKeyboardFocus.back(); - FocusIdxAllCounter++; +static void SetCurrentWindow(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + g.CurrentWindow = window; + if (window) + g.FontSize = window->CalcFontSize(); +} + +ImGuiWindow* ImGui::GetParentWindow() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.CurrentWindowStack.Size >= 2); + return g.CurrentWindowStack[(unsigned int)g.CurrentWindowStack.Size - 2]; +} + +void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window = NULL) +{ + ImGuiContext& g = *GImGui; + g.ActiveId = id; + g.ActiveIdAllowOverlap = false; + g.ActiveIdIsJustActivated = true; + g.ActiveIdWindow = window; +} + +void ImGui::SetHoveredID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + g.HoveredId = id; + g.HoveredIdAllowOverlap = false; +} + +void ImGui::KeepAliveID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + if (g.ActiveId == id) + g.ActiveIdIsAlive = true; +} + +// Advance cursor given item size for layout. +void ImGui::ItemSize(const ImVec2& size, float text_offset_y) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + // Always align ourselves on pixel boundaries + ImGuiContext& g = *GImGui; + const float line_height = ImMax(window->DC.CurrentLineHeight, size.y); + const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y); + window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y); + window->DC.CursorPos = ImVec2((float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX), (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y)); + window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x); + window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); + + //window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, 0xFF0000FF, 4); // Debug + + window->DC.PrevLineHeight = line_height; + window->DC.PrevLineTextBaseOffset = text_base_offset; + window->DC.CurrentLineHeight = window->DC.CurrentLineTextBaseOffset = 0.0f; +} + +void ImGui::ItemSize(const ImRect& bb, float text_offset_y) +{ + ItemSize(bb.GetSize(), text_offset_y); +} + +// Declare item bounding box for clipping and interaction. +// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface +// declares their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd(). +bool ImGui::ItemAdd(const ImRect& bb, const ImGuiID* id) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.LastItemID = id ? *id : 0; + window->DC.LastItemRect = bb; + window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = false; + if (IsClippedEx(bb, id, false)) + return false; + + // This is a sensible default, but widgets are free to override it after calling ItemAdd() + ImGuiContext& g = *GImGui; + if (IsMouseHoveringRect(bb.Min, bb.Max)) + { + // Matching the behavior of IsHovered() but allow if ActiveId==window->MoveID (we clicked on the window background) + // So that clicking on items with no active id such as Text() still returns true with IsItemHovered() + window->DC.LastItemHoveredRect = true; + if (g.HoveredRootWindow == window->RootWindow) + if (g.ActiveId == 0 || (id && g.ActiveId == *id) || g.ActiveIdAllowOverlap || (g.ActiveId == window->MoveID)) + if (IsWindowContentHoverable(window)) + window->DC.LastItemHoveredAndUsable = true; + } + + return true; +} + +bool ImGui::IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindowRead(); + + if (!bb.Overlaps(window->ClipRect)) + if (!id || *id != GImGui->ActiveId) + if (clip_even_when_logged || !g.LogEnabled) + return true; + return false; +} + +// NB: This is an internal helper. The user-facing IsItemHovered() is using data emitted from ItemAdd(), with a slightly different logic. +bool ImGui::IsHovered(const ImRect& bb, ImGuiID id, bool flatten_childs) +{ + ImGuiContext& g = *GImGui; + if (g.HoveredId == 0 || g.HoveredId == id || g.HoveredIdAllowOverlap) + { + ImGuiWindow* window = GetCurrentWindowRead(); + if (g.HoveredWindow == window || (flatten_childs && g.HoveredRootWindow == window->RootWindow)) + if ((g.ActiveId == 0 || g.ActiveId == id || g.ActiveIdAllowOverlap) && IsMouseHoveringRect(bb.Min, bb.Max)) + if (IsWindowContentHoverable(g.HoveredRootWindow)) + return true; + } + return false; +} + +bool ImGui::FocusableItemRegister(ImGuiWindow* window, bool is_active, bool tab_stop) +{ + ImGuiContext& g = *GImGui; + + const bool allow_keyboard_focus = window->DC.AllowKeyboardFocus; + window->FocusIdxAllCounter++; if (allow_keyboard_focus) - FocusIdxTabCounter++; + window->FocusIdxTabCounter++; // Process keyboard input at this point: TAB, Shift-TAB switch focus // We can always TAB out of a widget that doesn't allow tabbing in. - if (tab_stop && FocusIdxAllRequestNext == IM_INT_MAX && FocusIdxTabRequestNext == IM_INT_MAX && is_active && IsKeyPressedMap(ImGuiKey_Tab)) + if (tab_stop && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && is_active && IsKeyPressedMap(ImGuiKey_Tab)) { // Modulo on index will be applied at the end of frame once we've got the total counter of items. - FocusIdxTabRequestNext = FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1); + window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1); } - if (FocusIdxAllCounter == FocusIdxAllRequestCurrent) + if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent) return true; if (allow_keyboard_focus) - if (FocusIdxTabCounter == FocusIdxTabRequestCurrent) + if (window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent) return true; return false; } -void ImGuiWindow::FocusItemUnregister() +void ImGui::FocusableItemUnregister(ImGuiWindow* window) { - FocusIdxAllCounter--; - FocusIdxTabCounter--; + window->FocusIdxAllCounter--; + window->FocusIdxTabCounter--; } -static inline void AddDrawListToRenderList(ImVector& out_render_list, ImDrawList* draw_list) +ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_x, float default_y) { - if (!draw_list->commands.empty() && !draw_list->vtx_buffer.empty()) - { - if (draw_list->commands.back().vtx_count == 0) - draw_list->commands.pop_back(); - out_render_list.push_back(draw_list); - GImGui->IO.MetricsRenderVertices += (int)draw_list->vtx_buffer.size(); - } + ImGuiContext& g = *GImGui; + ImVec2 content_max; + if (size.x < 0.0f || size.y < 0.0f) + content_max = g.CurrentWindow->Pos + GetContentRegionMax(); + if (size.x <= 0.0f) + size.x = (size.x == 0.0f) ? default_x : ImMax(content_max.x - g.CurrentWindow->DC.CursorPos.x, 4.0f) + size.x; + if (size.y <= 0.0f) + size.y = (size.y == 0.0f) ? default_y : ImMax(content_max.y - g.CurrentWindow->DC.CursorPos.y, 4.0f) + size.y; + return size; } -static void AddWindowToRenderList(ImVector& out_render_list, ImGuiWindow* window) +float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) { - AddDrawListToRenderList(out_render_list, window->DrawList); - for (size_t i = 0; i < window->DC.ChildWindows.size(); i++) - { - ImGuiWindow* child = window->DC.ChildWindows[i]; - if (child->Active) // clipped children may have been marked not active - AddWindowToRenderList(out_render_list, child); - } + if (wrap_pos_x < 0.0f) + return 0.0f; + + ImGuiWindow* window = GetCurrentWindowRead(); + if (wrap_pos_x == 0.0f) + wrap_pos_x = GetContentRegionMax().x + window->Pos.x; + else if (wrap_pos_x > 0.0f) + wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space + + const float wrap_width = wrap_pos_x > 0.0f ? ImMax(wrap_pos_x - pos.x, 0.00001f) : 0.0f; + return wrap_width; } //----------------------------------------------------------------------------- void* ImGui::MemAlloc(size_t sz) { + GImGui->IO.MetricsAllocs++; return GImGui->IO.MemAllocFn(sz); } void ImGui::MemFree(void* ptr) { + if (ptr) GImGui->IO.MetricsAllocs--; return GImGui->IO.MemFreeFn(ptr); } - -static ImGuiIniData* FindWindowSettings(const char* name) + +const char* ImGui::GetClipboardText() { - ImGuiState& g = *GImGui; - ImGuiID id = ImHash(name, 0); - for (size_t i = 0; i != g.Settings.size(); i++) - { - ImGuiIniData* ini = g.Settings[i]; - if (ini->ID == id) - return ini; - } - return NULL; + return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn() : ""; } -static ImGuiIniData* AddWindowSettings(const char* name) +void ImGui::SetClipboardText(const char* text) { - ImGuiIniData* ini = (ImGuiIniData*)ImGui::MemAlloc(sizeof(ImGuiIniData)); - new(ini) ImGuiIniData(); - ini->Name = ImStrdup(name); - ini->ID = ImHash(name, 0); - ini->Collapsed = false; - ini->Pos = ImVec2(FLT_MAX,FLT_MAX); - ini->Size = ImVec2(0,0); - GImGui->Settings.push_back(ini); - return ini; -} - -// Zero-tolerance, poor-man .ini parsing -// FIXME: Write something less rubbish -static void LoadSettings() -{ - ImGuiState& g = *GImGui; - const char* filename = g.IO.IniFilename; - if (!filename) - return; - - char* file_data; - size_t file_size; - if (!ImLoadFileToMemory(filename, "rb", (void**)&file_data, &file_size, 1)) - return; - - ImGuiIniData* settings = NULL; - const char* buf_end = file_data + file_size; - for (const char* line_start = file_data; line_start < buf_end; ) - { - const char* line_end = line_start; - while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') - line_end++; - - if (line_start[0] == '[' && line_end > line_start && line_end[-1] == ']') - { - char name[64]; - ImFormatString(name, IM_ARRAYSIZE(name), "%.*s", line_end-line_start-2, line_start+1); - settings = FindWindowSettings(name); - if (!settings) - settings = AddWindowSettings(name); - } - else if (settings) - { - float x, y; - int i; - if (sscanf(line_start, "Pos=%f,%f", &x, &y) == 2) - settings->Pos = ImVec2(x, y); - else if (sscanf(line_start, "Size=%f,%f", &x, &y) == 2) - settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize); - else if (sscanf(line_start, "Collapsed=%d", &i) == 1) - settings->Collapsed = (i != 0); - } - - line_start = line_end+1; - } - - ImGui::MemFree(file_data); -} - -static void SaveSettings() -{ - ImGuiState& g = *GImGui; - const char* filename = g.IO.IniFilename; - if (!filename) - return; - - // Gather data from windows that were active during this session - for (size_t i = 0; i != g.Windows.size(); i++) - { - ImGuiWindow* window = g.Windows[i]; - if (window->Flags & ImGuiWindowFlags_NoSavedSettings) - continue; - ImGuiIniData* settings = FindWindowSettings(window->Name); - settings->Pos = window->Pos; - settings->Size = window->SizeFull; - settings->Collapsed = window->Collapsed; - } - - // Write .ini file - // If a window wasn't opened in this session we preserve its settings - FILE* f = fopen(filename, "wt"); - if (!f) - return; - for (size_t i = 0; i != g.Settings.size(); i++) - { - const ImGuiIniData* settings = g.Settings[i]; - if (settings->Pos.x == FLT_MAX) - continue; - const char* name = settings->Name; - if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() - name = p; - fprintf(f, "[%s]\n", name); - fprintf(f, "Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y); - fprintf(f, "Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y); - fprintf(f, "Collapsed=%d\n", settings->Collapsed); - fprintf(f, "\n"); - } - - fclose(f); -} - -static void MarkSettingsDirty() -{ - ImGuiState& g = *GImGui; - if (g.SettingsDirtyTimer <= 0.0f) - g.SettingsDirtyTimer = g.IO.IniSavingRate; + if (GImGui->IO.SetClipboardTextFn) + GImGui->IO.SetClipboardTextFn(text); } const char* ImGui::GetVersion() @@ -1894,22 +1982,33 @@ const char* ImGui::GetVersion() // Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself // Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module -void* ImGui::GetInternalState() +ImGuiContext* ImGui::GetCurrentContext() { return GImGui; } -size_t ImGui::GetInternalStateSize() +void ImGui::SetCurrentContext(ImGuiContext* ctx) { - return sizeof(ImGuiState); + GImGui = ctx; } -void ImGui::SetInternalState(void* state, bool construct) +ImGuiContext* ImGui::CreateContext(void* (*malloc_fn)(size_t), void (*free_fn)(void*)) { - if (construct) - new (state) ImGuiState(); - - GImGui = (ImGuiState*)state; + if (!malloc_fn) malloc_fn = malloc; + ImGuiContext* ctx = (ImGuiContext*)malloc_fn(sizeof(ImGuiContext)); + IM_PLACEMENT_NEW(ctx) ImGuiContext(); + ctx->IO.MemAllocFn = malloc_fn; + ctx->IO.MemFreeFn = free_fn ? free_fn : free; + return ctx; +} + +void ImGui::DestroyContext(ImGuiContext* ctx) +{ + void (*free_fn)(void*) = ctx->IO.MemFreeFn; + ctx->~ImGuiContext(); + free_fn(ctx); + if (GImGui == ctx) + GImGui = NULL; } ImGuiIO& ImGui::GetIO() @@ -1922,33 +2021,58 @@ ImGuiStyle& ImGui::GetStyle() return GImGui->Style; } +// Same value as passed to your RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame() +ImDrawData* ImGui::GetDrawData() +{ + return GImGui->RenderDrawData.Valid ? &GImGui->RenderDrawData : NULL; +} + +float ImGui::GetTime() +{ + return GImGui->Time; +} + +int ImGui::GetFrameCount() +{ + return GImGui->FrameCount; +} + void ImGui::NewFrame() { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; // Check user data - IM_ASSERT(g.IO.DeltaTime > 0.0f); + IM_ASSERT(g.IO.DeltaTime >= 0.0f); // Need a positive DeltaTime (zero is tolerated but will cause some timing issues) IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f); - IM_ASSERT(g.IO.RenderDrawListsFn != NULL); // Must be implemented - IM_ASSERT(g.IO.Fonts->Fonts.size() > 0); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? + IM_ASSERT(g.IO.Fonts->Fonts.Size > 0); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? + IM_ASSERT(g.Style.CurveTessellationTol > 0.0f); // Invalid style setting if (!g.Initialized) { // Initialize on first frame g.LogClipboard = (ImGuiTextBuffer*)ImGui::MemAlloc(sizeof(ImGuiTextBuffer)); - new(g.LogClipboard) ImGuiTextBuffer(); + IM_PLACEMENT_NEW(g.LogClipboard) ImGuiTextBuffer(); IM_ASSERT(g.Settings.empty()); LoadSettings(); g.Initialized = true; } - SetFont(g.IO.Fonts->Fonts[0]); + SetCurrentFont(g.IO.Fonts->Fonts[0]); g.Time += g.IO.DeltaTime; g.FrameCount += 1; g.Tooltip[0] = '\0'; + g.OverlayDrawList.Clear(); + g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID); + g.OverlayDrawList.PushClipRectFullScreen(); + g.OverlayDrawList.AddDrawCmd(); + + // Mark rendering data as invalid to prevent user who may have a handle on it to use it + g.RenderDrawData.Valid = false; + g.RenderDrawData.CmdLists = NULL; + g.RenderDrawData.CmdListsCount = g.RenderDrawData.TotalVtxCount = g.RenderDrawData.TotalIdxCount = 0; // Update inputs state if (g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0) @@ -1958,10 +2082,12 @@ void ImGui::NewFrame() else g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev; g.IO.MousePosPrev = g.IO.MousePos; - for (size_t i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) + for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) { - g.IO.MouseDownTime[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownTime[i] < 0.0f ? 0.0f : g.IO.MouseDownTime[i] + g.IO.DeltaTime) : -1.0f; - g.IO.MouseClicked[i] = (g.IO.MouseDownTime[i] == 0.0f); + g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f; + g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f; + g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i]; + g.IO.MouseDownDuration[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownDuration[i] < 0.0f ? 0.0f : g.IO.MouseDownDuration[i] + g.IO.DeltaTime) : -1.0f; g.IO.MouseDoubleClicked[i] = false; if (g.IO.MouseClicked[i]) { @@ -1983,8 +2109,9 @@ void ImGui::NewFrame() g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i])); } } - for (size_t i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++) - g.IO.KeysDownTime[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownTime[i] < 0.0f ? 0.0f : g.IO.KeysDownTime[i] + g.IO.DeltaTime) : -1.0f; + memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration)); + for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++) + g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f; // Calculate frame-rate for the user, as a purely luxurious feature g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx]; @@ -1993,14 +2120,43 @@ void ImGui::NewFrame() g.IO.Framerate = 1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame)); // Clear reference to active widget if the widget isn't alive anymore + g.HoveredIdPreviousFrame = g.HoveredId; g.HoveredId = 0; + g.HoveredIdAllowOverlap = false; if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0) - SetActiveId(0); + SetActiveID(0); g.ActiveIdPreviousFrame = g.ActiveId; g.ActiveIdIsAlive = false; g.ActiveIdIsJustActivated = false; - if (!g.ActiveId) + + // Handle user moving window (at the beginning of the frame to avoid input lag or sheering). Only valid for root windows. + if (g.MovedWindowMoveId && g.MovedWindowMoveId == g.ActiveId) + { + KeepAliveID(g.MovedWindowMoveId); + IM_ASSERT(g.MovedWindow && g.MovedWindow->RootWindow); + IM_ASSERT(g.MovedWindow->RootWindow->MoveID == g.MovedWindowMoveId); + if (g.IO.MouseDown[0]) + { + if (!(g.MovedWindow->Flags & ImGuiWindowFlags_NoMove)) + { + g.MovedWindow->PosFloat += g.IO.MouseDelta; + if (!(g.MovedWindow->Flags & ImGuiWindowFlags_NoSavedSettings)) + MarkSettingsDirty(); + } + FocusWindow(g.MovedWindow); + } + else + { + SetActiveID(0); + g.MovedWindow = NULL; + g.MovedWindowMoveId = 0; + } + } + else + { g.MovedWindow = NULL; + g.MovedWindowMoveId = 0; + } // Delay saving settings so we don't spam disk too much if (g.SettingsDirtyTimer > 0.0f) @@ -2011,34 +2167,56 @@ void ImGui::NewFrame() } // Find the window we are hovering. Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow - g.HoveredWindow = FindHoveredWindow(g.IO.MousePos, false); + g.HoveredWindow = g.MovedWindow ? g.MovedWindow : FindHoveredWindow(g.IO.MousePos, false); if (g.HoveredWindow && (g.HoveredWindow->Flags & ImGuiWindowFlags_ChildWindow)) g.HoveredRootWindow = g.HoveredWindow->RootWindow; else - g.HoveredRootWindow = FindHoveredWindow(g.IO.MousePos, true); + g.HoveredRootWindow = g.MovedWindow ? g.MovedWindow->RootWindow : FindHoveredWindow(g.IO.MousePos, true); + + if (ImGuiWindow* modal_window = GetFrontMostModalRootWindow()) + { + g.ModalWindowDarkeningRatio = ImMin(g.ModalWindowDarkeningRatio + g.IO.DeltaTime * 6.0f, 1.0f); + ImGuiWindow* window = g.HoveredRootWindow; + while (window && window != modal_window) + window = window->ParentWindow; + if (!window) + g.HoveredRootWindow = g.HoveredWindow = NULL; + } + else + { + g.ModalWindowDarkeningRatio = 0.0f; + } // Are we using inputs? Tell user so they can capture/discard the inputs away from the rest of their application. - // When clicking outside of a window we assume the click is owned by the application and won't request capture. + // When clicking outside of a window we assume the click is owned by the application and won't request capture. We need to track click ownership. int mouse_earliest_button_down = -1; + bool mouse_any_down = false; for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) { if (g.IO.MouseClicked[i]) - g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL); + g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty()); + mouse_any_down |= g.IO.MouseDown[i]; if (g.IO.MouseDown[i]) if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[mouse_earliest_button_down] > g.IO.MouseClickedTime[i]) mouse_earliest_button_down = i; } - bool mouse_owned_by_application = mouse_earliest_button_down != -1 && !g.IO.MouseDownOwned[mouse_earliest_button_down]; - g.IO.WantCaptureMouse = (!mouse_owned_by_application && g.HoveredWindow != NULL) || (g.ActiveId != 0); - g.IO.WantCaptureKeyboard = (g.ActiveId != 0); + bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down]; + if (g.CaptureMouseNextFrame != -1) + g.IO.WantCaptureMouse = (g.CaptureMouseNextFrame != 0); + else + g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (g.ActiveId != 0) || (!g.OpenPopupStack.empty()); + g.IO.WantCaptureKeyboard = (g.CaptureKeyboardNextFrame != -1) ? (g.CaptureKeyboardNextFrame != 0) : (g.ActiveId != 0); + g.IO.WantTextInput = (g.ActiveId != 0 && g.InputTextState.Id == g.ActiveId); g.MouseCursor = ImGuiMouseCursor_Arrow; + g.CaptureMouseNextFrame = g.CaptureKeyboardNextFrame = -1; + g.OsImePosRequest = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default // If mouse was first clicked outside of ImGui bounds we also cancel out hovering. - if (mouse_owned_by_application) + if (!mouse_avail_to_imgui) g.HoveredWindow = g.HoveredRootWindow = NULL; // Scale & Scrolling - if (g.HoveredWindow && g.IO.MouseWheel != 0.0f) + if (g.HoveredWindow && g.IO.MouseWheel != 0.0f && !g.HoveredWindow->Collapsed) { ImGuiWindow* window = g.HoveredWindow; if (g.IO.KeyCtrl) @@ -2063,7 +2241,7 @@ void ImGui::NewFrame() if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse)) { const int scroll_lines = (window->Flags & ImGuiWindowFlags_ComboBox) ? 3 : 5; - window->NextScrollY -= g.IO.MouseWheel * window->CalcFontSize() * scroll_lines; + SetWindowScrollY(window, window->Scroll.y - g.IO.MouseWheel * window->CalcFontSize() * scroll_lines); } } } @@ -2071,12 +2249,10 @@ void ImGui::NewFrame() // Pressing TAB activate widget focus // NB: Don't discard FocusedWindow if it isn't active, so that a window that go on/off programatically won't lose its keyboard focus. if (g.ActiveId == 0 && g.FocusedWindow != NULL && g.FocusedWindow->Active && IsKeyPressedMap(ImGuiKey_Tab, false)) - { g.FocusedWindow->FocusIdxTabRequestNext = 0; - } // Mark all windows as not visible - for (size_t i = 0; i != g.Windows.size(); i++) + for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; window->WasActive = window->Active; @@ -2087,6 +2263,8 @@ void ImGui::NewFrame() // No window should be open at the beginning of the frame. // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear. g.CurrentWindowStack.resize(0); + g.CurrentPopupStack.resize(0); + CloseInactivePopups(); // Create implicit window - we will only render it if the user has added something to it. ImGui::SetNextWindowSize(ImVec2(400,400), ImGuiSetCond_FirstUseEver); @@ -2096,13 +2274,19 @@ void ImGui::NewFrame() // NB: behavior of ImGui after Shutdown() is not tested/guaranteed at the moment. This function is merely here to free heap allocations. void ImGui::Shutdown() { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; + + // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame) + if (g.IO.Fonts) // Testing for NULL to allow user to NULLify in case of running Shutdown() on multiple contexts. Bit hacky. + g.IO.Fonts->Clear(); + + // Cleanup of other data are conditional on actually having used ImGui. if (!g.Initialized) return; SaveSettings(); - for (size_t i = 0; i < g.Windows.size(); i++) + for (int i = 0; i < g.Windows.Size; i++) { g.Windows[i]->~ImGuiWindow(); ImGui::MemFree(g.Windows[i]); @@ -2113,24 +2297,26 @@ void ImGui::Shutdown() g.FocusedWindow = NULL; g.HoveredWindow = NULL; g.HoveredRootWindow = NULL; - for (size_t i = 0; i < g.Settings.size(); i++) - { - g.Settings[i]->~ImGuiIniData(); - ImGui::MemFree(g.Settings[i]); - } + for (int i = 0; i < g.Settings.Size; i++) + ImGui::MemFree(g.Settings[i].Name); g.Settings.clear(); g.ColorModifiers.clear(); g.StyleModifiers.clear(); g.FontStack.clear(); - for (size_t i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) + g.OpenPopupStack.clear(); + g.CurrentPopupStack.clear(); + for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) g.RenderDrawLists[i].clear(); - g.MouseCursorDrawList.ClearFreeMemory(); + g.OverlayDrawList.ClearFreeMemory(); g.ColorEditModeStorage.Clear(); if (g.PrivateClipboard) { ImGui::MemFree(g.PrivateClipboard); g.PrivateClipboard = NULL; } + g.InputTextState.Text.clear(); + g.InputTextState.InitialText.clear(); + g.InputTextState.TempTextBuffer.clear(); if (g.LogFile && g.LogFile != stdout) { @@ -2143,12 +2329,131 @@ void ImGui::Shutdown() ImGui::MemFree(g.LogClipboard); } - if (g.IO.Fonts) // Testing for NULL to allow user to NULLify in case of running Shutdown() on multiple contexts. Bit hacky. - g.IO.Fonts->Clear(); - g.Initialized = false; } +static ImGuiIniData* FindWindowSettings(const char* name) +{ + ImGuiContext& g = *GImGui; + ImGuiID id = ImHash(name, 0); + for (int i = 0; i != g.Settings.Size; i++) + { + ImGuiIniData* ini = &g.Settings[i]; + if (ini->ID == id) + return ini; + } + return NULL; +} + +static ImGuiIniData* AddWindowSettings(const char* name) +{ + GImGui->Settings.resize(GImGui->Settings.Size + 1); + ImGuiIniData* ini = &GImGui->Settings.back(); + ini->Name = ImStrdup(name); + ini->ID = ImHash(name, 0); + ini->Collapsed = false; + ini->Pos = ImVec2(FLT_MAX,FLT_MAX); + ini->Size = ImVec2(0,0); + return ini; +} + +// Zero-tolerance, poor-man .ini parsing +// FIXME: Write something less rubbish +static void LoadSettings() +{ + ImGuiContext& g = *GImGui; + const char* filename = g.IO.IniFilename; + if (!filename) + return; + + int file_size; + char* file_data = (char*)ImLoadFileToMemory(filename, "rb", &file_size, 1); + if (!file_data) + return; + + ImGuiIniData* settings = NULL; + const char* buf_end = file_data + file_size; + for (const char* line_start = file_data; line_start < buf_end; ) + { + const char* line_end = line_start; + while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') + line_end++; + + if (line_start[0] == '[' && line_end > line_start && line_end[-1] == ']') + { + char name[64]; + ImFormatString(name, IM_ARRAYSIZE(name), "%.*s", (int)(line_end-line_start-2), line_start+1); + settings = FindWindowSettings(name); + if (!settings) + settings = AddWindowSettings(name); + } + else if (settings) + { + float x, y; + int i; + if (sscanf(line_start, "Pos=%f,%f", &x, &y) == 2) + settings->Pos = ImVec2(x, y); + else if (sscanf(line_start, "Size=%f,%f", &x, &y) == 2) + settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize); + else if (sscanf(line_start, "Collapsed=%d", &i) == 1) + settings->Collapsed = (i != 0); + } + + line_start = line_end+1; + } + + ImGui::MemFree(file_data); +} + +static void SaveSettings() +{ + ImGuiContext& g = *GImGui; + const char* filename = g.IO.IniFilename; + if (!filename) + return; + + // Gather data from windows that were active during this session + for (int i = 0; i != g.Windows.Size; i++) + { + ImGuiWindow* window = g.Windows[i]; + if (window->Flags & ImGuiWindowFlags_NoSavedSettings) + continue; + ImGuiIniData* settings = FindWindowSettings(window->Name); + settings->Pos = window->Pos; + settings->Size = window->SizeFull; + settings->Collapsed = window->Collapsed; + } + + // Write .ini file + // If a window wasn't opened in this session we preserve its settings + FILE* f = fopen(filename, "wt"); + if (!f) + return; + for (int i = 0; i != g.Settings.Size; i++) + { + const ImGuiIniData* settings = &g.Settings[i]; + if (settings->Pos.x == FLT_MAX) + continue; + const char* name = settings->Name; + if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() + name = p; + fprintf(f, "[%s]\n", name); + fprintf(f, "Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y); + fprintf(f, "Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y); + fprintf(f, "Collapsed=%d\n", settings->Collapsed); + fprintf(f, "\n"); + } + + fclose(f); +} + +static void MarkSettingsDirty() +{ + ImGuiContext& g = *GImGui; + if (g.SettingsDirtyTimer <= 0.0f) + g.SettingsDirtyTimer = g.IO.IniSavingRate; +} + // FIXME: Add a more explicit sort order in the window structure. static int ChildWindowComparer(const void* lhs, const void* rhs) { @@ -2160,7 +2465,7 @@ static int ChildWindowComparer(const void* lhs, const void* rhs) return d; if (int d = (a->Flags & ImGuiWindowFlags_ComboBox) - (b->Flags & ImGuiWindowFlags_ComboBox)) return d; - return 0; + return (a->IndexWithinParent - b->IndexWithinParent); } static void AddWindowToSortedBuffer(ImVector& out_sorted_windows, ImGuiWindow* window) @@ -2168,10 +2473,10 @@ static void AddWindowToSortedBuffer(ImVector& out_sorted_windows, out_sorted_windows.push_back(window); if (window->Active) { - const size_t count = window->DC.ChildWindows.size(); + int count = window->DC.ChildWindows.Size; if (count > 1) - qsort(window->DC.ChildWindows.begin(), count, sizeof(ImGuiWindow*), ChildWindowComparer); - for (size_t i = 0; i < count; i++) + qsort(window->DC.ChildWindows.begin(), (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer); + for (int i = 0; i < count; i++) { ImGuiWindow* child = window->DC.ChildWindows[i]; if (child->Active) @@ -2180,107 +2485,158 @@ static void AddWindowToSortedBuffer(ImVector& out_sorted_windows, } } -static void PushClipRect(const ImVec4& clip_rect, bool clipped = true) +static void AddDrawListToRenderList(ImVector& out_render_list, ImDrawList* draw_list) { - ImGuiWindow* window = GetCurrentWindow(); + if (draw_list->CmdBuffer.empty()) + return; - ImVec4 cr = clip_rect; - if (clipped && !window->ClipRectStack.empty()) + // Remove trailing command if unused + ImDrawCmd& last_cmd = draw_list->CmdBuffer.back(); + if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL) { - // Clip with existing clip rect - const ImVec4 cur_cr = window->ClipRectStack.back(); - cr = ImVec4(ImMax(cr.x, cur_cr.x), ImMax(cr.y, cur_cr.y), ImMin(cr.z, cur_cr.z), ImMin(cr.w, cur_cr.w)); + draw_list->CmdBuffer.pop_back(); + if (draw_list->CmdBuffer.empty()) + return; } - cr.z = ImMax(cr.x, cr.z); - cr.w = ImMax(cr.y, cr.w); - IM_ASSERT(cr.x <= cr.z && cr.y <= cr.w); - window->ClipRectStack.push_back(cr); - window->DrawList->PushClipRect(cr); + // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. + IM_ASSERT(draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size); + IM_ASSERT(draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size); + IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size); + + // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = 2 bytes = 64K vertices) + // If this assert triggers because you are drawing lots of stuff manually, A) workaround by calling BeginChild()/EndChild() to put your draw commands in multiple draw lists, B) #define ImDrawIdx to a 'unsigned int' in imconfig.h and render accordingly. + IM_ASSERT((int64_t)draw_list->_VtxCurrentIdx <= ((int64_t)1L << (sizeof(ImDrawIdx)*8))); // Too many vertices in same ImDrawList. See comment above. + + out_render_list.push_back(draw_list); + GImGui->IO.MetricsRenderVertices += draw_list->VtxBuffer.Size; + GImGui->IO.MetricsRenderIndices += draw_list->IdxBuffer.Size; } -static void PopClipRect() +static void AddWindowToRenderList(ImVector& out_render_list, ImGuiWindow* window) +{ + AddDrawListToRenderList(out_render_list, window->DrawList); + for (int i = 0; i < window->DC.ChildWindows.Size; i++) + { + ImGuiWindow* child = window->DC.ChildWindows[i]; + if (!child->Active) // clipped children may have been marked not active + continue; + if ((child->Flags & ImGuiWindowFlags_Popup) && child->HiddenFrames > 0) + continue; + AddWindowToRenderList(out_render_list, child); + } +} + +// When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result. +void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) { ImGuiWindow* window = GetCurrentWindow(); - window->ClipRectStack.pop_back(); - window->DrawList->PopClipRect(); + window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect); + window->ClipRect = window->DrawList->_ClipRectStack.back(); } -void ImGui::Render() +void ImGui::PopClipRect() { - ImGuiState& g = *GImGui; - IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() + ImGuiWindow* window = GetCurrentWindow(); + window->DrawList->PopClipRect(); + window->ClipRect = window->DrawList->_ClipRectStack.back(); +} - const bool first_render_of_the_frame = (g.FrameCountRendered != g.FrameCount); - g.FrameCountRendered = g.FrameCount; - - if (first_render_of_the_frame) +// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal. +void ImGui::EndFrame() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() + IM_ASSERT(g.FrameCountEnded != g.FrameCount); // ImGui::EndFrame() called multiple times, or forgot to call ImGui::NewFrame() again + + // Render tooltip + if (g.Tooltip[0]) { - // Hide implicit "Debug" window if it hasn't been used - IM_ASSERT(g.CurrentWindowStack.size() == 1); // Mismatched Begin/End - if (g.CurrentWindow && !g.CurrentWindow->Accessed) - g.CurrentWindow->Active = false; - ImGui::End(); + ImGui::BeginTooltip(); + ImGui::TextUnformatted(g.Tooltip); + ImGui::EndTooltip(); + } - // Click to focus window and start moving (after we're done with all our widgets) - if (g.ActiveId == 0 && g.HoveredId == 0 && g.IO.MouseClicked[0]) + // Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME) + if (g.IO.ImeSetInputScreenPosFn && ImLengthSqr(g.OsImePosRequest - g.OsImePosSet) > 0.0001f) + { + g.IO.ImeSetInputScreenPosFn((int)g.OsImePosRequest.x, (int)g.OsImePosRequest.y); + g.OsImePosSet = g.OsImePosRequest; + } + + // Hide implicit "Debug" window if it hasn't been used + IM_ASSERT(g.CurrentWindowStack.Size == 1); // Mismatched Begin()/End() calls + if (g.CurrentWindow && !g.CurrentWindow->Accessed) + g.CurrentWindow->Active = false; + ImGui::End(); + + // Click to focus window and start moving (after we're done with all our widgets) + if (g.ActiveId == 0 && g.HoveredId == 0 && g.IO.MouseClicked[0]) + { + if (!(g.FocusedWindow && !g.FocusedWindow->WasActive && g.FocusedWindow->Active)) // Unless we just made a popup appear { if (g.HoveredRootWindow != NULL) { - IM_ASSERT(g.MovedWindow == NULL); - g.MovedWindow = g.HoveredWindow; - SetActiveId(g.HoveredRootWindow->MoveID); + FocusWindow(g.HoveredWindow); + if (!(g.HoveredWindow->Flags & ImGuiWindowFlags_NoMove)) + { + g.MovedWindow = g.HoveredWindow; + g.MovedWindowMoveId = g.HoveredRootWindow->MoveID; + SetActiveID(g.MovedWindowMoveId, g.HoveredRootWindow); + } } - else if (g.FocusedWindow != NULL) + else if (g.FocusedWindow != NULL && GetFrontMostModalRootWindow() == NULL) { // Clicking on void disable focus FocusWindow(NULL); } } - - // Sort the window list so that all child windows are after their parent - // We cannot do that on FocusWindow() because childs may not exist yet - g.WindowsSortBuffer.resize(0); - g.WindowsSortBuffer.reserve(g.Windows.size()); - for (size_t i = 0; i != g.Windows.size(); i++) - { - ImGuiWindow* window = g.Windows[i]; - if (window->Flags & ImGuiWindowFlags_ChildWindow) // if a child is active its parent will add it - if (window->Active) - continue; - AddWindowToSortedBuffer(g.WindowsSortBuffer, window); - } - IM_ASSERT(g.Windows.size() == g.WindowsSortBuffer.size()); // we done something wrong - g.Windows.swap(g.WindowsSortBuffer); - - // Clear Input data for next frame - g.IO.MouseWheel = 0.0f; - memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters)); } + // Sort the window list so that all child windows are after their parent + // We cannot do that on FocusWindow() because childs may not exist yet + g.WindowsSortBuffer.resize(0); + g.WindowsSortBuffer.reserve(g.Windows.Size); + for (int i = 0; i != g.Windows.Size; i++) + { + ImGuiWindow* window = g.Windows[i]; + if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it + continue; + AddWindowToSortedBuffer(g.WindowsSortBuffer, window); + } + IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); // we done something wrong + g.Windows.swap(g.WindowsSortBuffer); + + // Clear Input data for next frame + g.IO.MouseWheel = 0.0f; + memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters)); + + g.FrameCountEnded = g.FrameCount; +} + +void ImGui::Render() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() + + if (g.FrameCountEnded != g.FrameCount) + ImGui::EndFrame(); + g.FrameCountRendered = g.FrameCount; + // Skip render altogether if alpha is 0.0 - // Note that vertex buffers have been created, so it is best practice that you don't create windows in the first place, or respond to Begin() returning false + // Note that vertex buffers have been created and are wasted, so it is best practice that you don't create windows in the first place, or consistently respond to Begin() returning false. if (g.Style.Alpha > 0.0f) { - // Render tooltip - if (g.Tooltip[0]) - { - ImGui::BeginTooltip(); - ImGui::TextUnformatted(g.Tooltip); - ImGui::EndTooltip(); - } - // Gather windows to render - g.IO.MetricsRenderVertices = 0; - g.IO.MetricsActiveWindows = 0; - for (size_t i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) + g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsActiveWindows = 0; + for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) g.RenderDrawLists[i].resize(0); - for (size_t i = 0; i != g.Windows.size(); i++) + for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; if (window->Active && window->HiddenFrames <= 0 && (window->Flags & (ImGuiWindowFlags_ChildWindow)) == 0) { - // FIXME: Generalize this with a proper layering system so we can stack. + // FIXME: Generalize this with a proper layering system so e.g. user can draw in specific layers, below text, .. g.IO.MetricsActiveWindows++; if (window->Flags & ImGuiWindowFlags_Popup) AddWindowToRenderList(g.RenderDrawLists[1], window); @@ -2292,68 +2648,65 @@ void ImGui::Render() } // Flatten layers - size_t n = g.RenderDrawLists[0].size(); - size_t flattened_size = n; - for (size_t i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) - flattened_size += g.RenderDrawLists[i].size(); + int n = g.RenderDrawLists[0].Size; + int flattened_size = n; + for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) + flattened_size += g.RenderDrawLists[i].Size; g.RenderDrawLists[0].resize(flattened_size); - for (size_t i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) + for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) { ImVector& layer = g.RenderDrawLists[i]; - if (!layer.empty()) - { - memcpy(&g.RenderDrawLists[0][n], &layer[0], layer.size() * sizeof(ImDrawList*)); - n += layer.size(); - } + if (layer.empty()) + continue; + memcpy(&g.RenderDrawLists[0][n], &layer[0], layer.Size * sizeof(ImDrawList*)); + n += layer.Size; } + // Draw software mouse cursor if requested if (g.IO.MouseDrawCursor) { const ImGuiMouseCursorData& cursor_data = g.MouseCursorData[g.MouseCursor]; - const ImVec2 pos = g.IO.MousePos - cursor_data.Offset; + const ImVec2 pos = g.IO.MousePos - cursor_data.HotOffset; const ImVec2 size = cursor_data.Size; const ImTextureID tex_id = g.IO.Fonts->TexID; - g.MouseCursorDrawList.Clear(); - g.MouseCursorDrawList.PushTextureID(tex_id); - g.MouseCursorDrawList.AddImage(tex_id, pos+ImVec2(1,0), pos+ImVec2(1,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], 0x30000000); // Shadow - g.MouseCursorDrawList.AddImage(tex_id, pos+ImVec2(2,0), pos+ImVec2(2,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], 0x30000000); // Shadow - g.MouseCursorDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], 0xFF000000); // Black border - g.MouseCursorDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[0], cursor_data.TexUvMax[0], 0xFFFFFFFF); // White fill - g.MouseCursorDrawList.PopTextureID(); - AddDrawListToRenderList(g.RenderDrawLists[0], &g.MouseCursorDrawList); + g.OverlayDrawList.PushTextureID(tex_id); + g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(1,0), pos+ImVec2(1,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], 0x30000000); // Shadow + g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(2,0), pos+ImVec2(2,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], 0x30000000); // Shadow + g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], 0xFF000000); // Black border + g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[0], cursor_data.TexUvMax[0], 0xFFFFFFFF); // White fill + g.OverlayDrawList.PopTextureID(); } + if (!g.OverlayDrawList.VtxBuffer.empty()) + AddDrawListToRenderList(g.RenderDrawLists[0], &g.OverlayDrawList); - // Render - if (!g.RenderDrawLists[0].empty()) - g.IO.RenderDrawListsFn(&g.RenderDrawLists[0][0], (int)g.RenderDrawLists[0].size()); + // Setup draw data + g.RenderDrawData.Valid = true; + g.RenderDrawData.CmdLists = (g.RenderDrawLists[0].Size > 0) ? &g.RenderDrawLists[0][0] : NULL; + g.RenderDrawData.CmdListsCount = g.RenderDrawLists[0].Size; + g.RenderDrawData.TotalVtxCount = g.IO.MetricsRenderVertices; + g.RenderDrawData.TotalIdxCount = g.IO.MetricsRenderIndices; + + // Render. If user hasn't set a callback then they may retrieve the draw data via GetDrawData() + if (g.RenderDrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL) + g.IO.RenderDrawListsFn(&g.RenderDrawData); } } -// Find the optional ## from which we stop displaying text. -static const char* FindTextDisplayEnd(const char* text, const char* text_end = NULL) +const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end) { const char* text_display_end = text; if (!text_end) text_end = (const char*)-1; - ImGuiState& g = *GImGui; - if (g.DisableHideTextAfterDoubleHash > 0) - { - while (text_display_end < text_end && *text_display_end != '\0') - text_display_end++; - } - else - { - while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#')) - text_display_end++; - } + while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#')) + text_display_end++; return text_display_end; } // Pass text data straight to log (without being displayed) void ImGui::LogText(const char* fmt, ...) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; if (!g.LogEnabled) return; @@ -2372,13 +2725,13 @@ void ImGui::LogText(const char* fmt, ...) // Internal version that takes a position to decide on newline placement and pad items according to their depth. // We split text into individual lines to add current tree level padding -static void LogText(const ImVec2& ref_pos, const char* text, const char* text_end) +static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); + ImGuiContext& g = *GImGui; + ImGuiWindow* window = ImGui::GetCurrentWindowRead(); if (!text_end) - text_end = FindTextDisplayEnd(text, text_end); + text_end = ImGui::FindRenderedTextEnd(text, text_end); const bool log_new_line = ref_pos.y > window->DC.LogLinePosY+1; window->DC.LogLinePosY = ref_pos.y; @@ -2410,7 +2763,7 @@ static void LogText(const ImVec2& ref_pos, const char* text, const char* text_en { const int char_count = (int)(line_end - text_remaining); if (log_new_line || !is_first_line) - ImGui::LogText(STR_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, text_remaining); + ImGui::LogText(IM_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, text_remaining); else ImGui::LogText(" %.*s", char_count, text_remaining); } @@ -2421,33 +2774,18 @@ static void LogText(const ImVec2& ref_pos, const char* text, const char* text_en } } -static float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) -{ - if (wrap_pos_x < 0.0f) - return 0.0f; - - ImGuiWindow* window = GetCurrentWindow(); - if (wrap_pos_x == 0.0f) - wrap_pos_x = ImGui::GetContentRegionMax().x; - if (wrap_pos_x > 0.0f) - wrap_pos_x += window->Pos.x; // wrap_pos_x is provided is window local space - - const float wrap_width = wrap_pos_x > 0.0f ? ImMax(wrap_pos_x - pos.x, 0.00001f) : 0.0f; - return wrap_width; -} - // Internal ImGui functions to render text // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText() -static void RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash) +void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); // Hide anything after a '##' string const char* text_display_end; if (hide_text_after_hash) { - text_display_end = FindTextDisplayEnd(text, text_end); + text_display_end = FindRenderedTextEnd(text, text_end); } else { @@ -2459,18 +2797,15 @@ static void RenderText(ImVec2 pos, const char* text, const char* text_end, bool const int text_len = (int)(text_display_end - text); if (text_len > 0) { - // Render - window->DrawList->AddText(g.Font, g.FontSize, pos, window->Color(ImGuiCol_Text), text, text_display_end); - - // Log as text + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end); if (g.LogEnabled) - LogText(pos, text, text_display_end); + LogRenderedText(pos, text, text_display_end); } } -static void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width) +void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (!text_end) @@ -2479,56 +2814,68 @@ static void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end const int text_len = (int)(text_end - text); if (text_len > 0) { - window->DrawList->AddText(g.Font, g.FontSize, pos, window->Color(ImGuiCol_Text), text, text_end, wrap_width); + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width); if (g.LogEnabled) - LogText(pos, text, text_end); + LogRenderedText(pos, text, text_end); } } -static void RenderTextClipped(ImVec2 pos, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& pos_max, const ImVec2* clip_max, ImGuiAlign align) +// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges) +void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, ImGuiAlign align, const ImVec2* clip_min, const ImVec2* clip_max) { // Hide anything after a '##' string - const char* text_display_end = FindTextDisplayEnd(text, text_end); + const char* text_display_end = FindRenderedTextEnd(text, text_end); const int text_len = (int)(text_display_end - text); if (text_len == 0) return; - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); // Perform CPU side clipping for single clipped element to avoid using scissor state - const ImVec2 text_size = text_size_if_known ? *text_size_if_known : ImGui::CalcTextSize(text, text_display_end, false, 0.0f); + ImVec2 pos = pos_min; + const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f); + if (!clip_max) clip_max = &pos_max; - const bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y); + bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y); + if (!clip_min) clip_min = &pos_min; else need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y); // Align if (align & ImGuiAlign_Center) pos.x = ImMax(pos.x, (pos.x + pos_max.x - text_size.x) * 0.5f); else if (align & ImGuiAlign_Right) pos.x = ImMax(pos.x, pos_max.x - text_size.x); + if (align & ImGuiAlign_VCenter) pos.y = ImMax(pos.y, (pos.y + pos_max.y - text_size.y) * 0.5f); // Render - window->DrawList->AddText(g.Font, g.FontSize, pos, window->Color(ImGuiCol_Text), text, text_display_end, 0.0f, need_clipping ? clip_max : NULL); + if (need_clipping) + { + ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y); + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect); + } + else + { + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL); + } if (g.LogEnabled) - LogText(pos, text, text_display_end); + LogRenderedText(pos, text, text_display_end); } // Render a rectangle shaped with optional rounding and borders -static void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding) +void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding) { ImGuiWindow* window = GetCurrentWindow(); window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding); if (border && (window->Flags & ImGuiWindowFlags_ShowBorders)) { - // FIXME: This is the best I've found that works on multiple renderer/back ends. Bit dodgy. - window->DrawList->AddRect(p_min+ImVec2(1.5f,1.5f), p_max+ImVec2(1,1), window->Color(ImGuiCol_BorderShadow), rounding); - window->DrawList->AddRect(p_min+ImVec2(0.5f,0.5f), p_max+ImVec2(0,0), window->Color(ImGuiCol_Border), rounding); + window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding); + window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding); } } // Render a triangle to denote expanded/collapsed state -static void RenderCollapseTriangle(ImVec2 p_min, bool opened, float scale, bool shadow) +void ImGui::RenderCollapseTriangle(ImVec2 p_min, bool is_open, float scale, bool shadow) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); const float h = g.FontSize * 1.00f; @@ -2536,7 +2883,7 @@ static void RenderCollapseTriangle(ImVec2 p_min, bool opened, float scale, bool ImVec2 center = p_min + ImVec2(h*0.50f, h*0.50f*scale); ImVec2 a, b, c; - if (opened) + if (is_open) { center.y -= r*0.25f; a = center + ImVec2(0,1)*r; @@ -2549,72 +2896,74 @@ static void RenderCollapseTriangle(ImVec2 p_min, bool opened, float scale, bool b = center + ImVec2(-0.500f,0.866f)*r; c = center + ImVec2(-0.500f,-0.866f)*r; } - + if (shadow && (window->Flags & ImGuiWindowFlags_ShowBorders) != 0) - window->DrawList->AddTriangleFilled(a+ImVec2(2,2), b+ImVec2(2,2), c+ImVec2(2,2), window->Color(ImGuiCol_BorderShadow)); - window->DrawList->AddTriangleFilled(a, b, c, window->Color(ImGuiCol_Text)); + window->DrawList->AddTriangleFilled(a+ImVec2(2,2), b+ImVec2(2,2), c+ImVec2(2,2), GetColorU32(ImGuiCol_BorderShadow)); + window->DrawList->AddTriangleFilled(a, b, c, GetColorU32(ImGuiCol_Text)); } -static void RenderCheckMark(ImVec2 pos, ImU32 col) +void ImGui::RenderBullet(ImVec2 pos) { - ImGuiState& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + window->DrawList->AddCircleFilled(pos, GImGui->FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8); +} + +void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col) +{ + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); ImVec2 a, b, c; float start_x = (float)(int)(g.FontSize * 0.307f + 0.5f); float rem_third = (float)(int)((g.FontSize - start_x) / 3.0f); - a.x = pos.x + start_x; + a.x = pos.x + 0.5f + start_x; b.x = a.x + rem_third; c.x = a.x + rem_third * 3.0f; - b.y = pos.y + (float)(int)(g.Font->BaseLine * (g.FontSize / g.Font->FontSize) + 0.5f) + (float)(int)(g.Font->DisplayOffset.y); + b.y = pos.y - 1.0f + (float)(int)(g.Font->Ascent * (g.FontSize / g.Font->FontSize) + 0.5f) + (float)(int)(g.Font->DisplayOffset.y); a.y = b.y - rem_third; c.y = b.y - rem_third * 2.0f; - window->DrawList->AddLine(a, b, col); - window->DrawList->AddLine(b, c, col); + window->DrawList->PathLineTo(a); + window->DrawList->PathLineTo(b); + window->DrawList->PathLineTo(c); + window->DrawList->PathStroke(col, false); } // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker. // CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize) ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; const char* text_display_end; if (hide_text_after_double_hash) - text_display_end = FindTextDisplayEnd(text, text_end); // Hide anything after a '##' string + text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string else text_display_end = text_end; ImFont* font = g.Font; const float font_size = g.FontSize; + if (text == text_display_end) + return ImVec2(0.0f, font_size); ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL); // Cancel out character spacing for the last character of a line (it is baked into glyph->XAdvance field) - const float font_scale = font_size / font->FontSize; + const float font_scale = font_size / font->FontSize; const float character_spacing_x = 1.0f * font_scale; if (text_size.x > 0.0f) text_size.x -= character_spacing_x; + text_size.x = (float)(int)(text_size.x + 0.95f); return text_size; } -// Helper to calculate coarse clipping of large list of evenly sized items. -// If you are displaying thousands of items and you have a random access to the list, you can perform clipping yourself to save on CPU. -// { -// float item_height = ImGui::GetTextLineHeightWithSpacing(); -// int display_start, display_end; -// ImGui::CalcListClipping(count, item_height, &display_start, &display_end); // calculate how many to clip/display -// ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (display_start) * item_height); // advance cursor -// for (int i = display_start; i < display_end; i++) // display only visible items -// // TODO: display visible item -// ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (count - display_end) * item_height); // advance cursor -// } +// Helper to calculate coarse clipping of large list of evenly sized items. +// NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern. +// NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindowRead(); if (g.LogEnabled) { // If logging is active, do not perform any clipping @@ -2622,35 +2971,38 @@ void ImGui::CalcListClipping(int items_count, float items_height, int* out_items *out_items_display_end = items_count; return; } + if (window->SkipItems) + { + *out_items_display_start = *out_items_display_end = 0; + return; + } const ImVec2 pos = window->DC.CursorPos; - const ImVec4 clip_rect = window->ClipRectStack.back(); - const float clip_y1 = clip_rect.y; - const float clip_y2 = clip_rect.w; - - int start = (int)((clip_y1 - pos.y) / items_height); - int end = (int)((clip_y2 - pos.y) / items_height); + int start = (int)((window->ClipRect.Min.y - pos.y) / items_height); + int end = (int)((window->ClipRect.Max.y - pos.y) / items_height); start = ImClamp(start, 0, items_count); end = ImClamp(end + 1, start, items_count); - *out_items_display_start = start; *out_items_display_end = end; } // Find window given position, search front-to-back +// FIXME: Note that we have a lag here because WindowRectClipped is updated in Begin() so windows moved by user via SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is called, aka before the next Begin(). Moving window thankfully isn't affected. static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs) { - ImGuiState& g = *GImGui; - for (int i = (int)g.Windows.size()-1; i >= 0; i--) + ImGuiContext& g = *GImGui; + for (int i = g.Windows.Size-1; i >= 0; i--) { - ImGuiWindow* window = g.Windows[(size_t)i]; + ImGuiWindow* window = g.Windows[i]; if (!window->Active) continue; + if (window->Flags & ImGuiWindowFlags_NoInputs) + continue; if (excluding_childs && (window->Flags & ImGuiWindowFlags_ChildWindow) != 0) continue; // Using the clipped AABB so a child window will typically be clipped by its parent. - ImRect bb(window->ClippedRect.Min - g.Style.TouchExtraPadding, window->ClippedRect.Max + g.Style.TouchExtraPadding); + ImRect bb(window->WindowRectClipped.Min - g.Style.TouchExtraPadding, window->WindowRectClipped.Max + g.Style.TouchExtraPadding); if (bb.Contains(pos)) return window; } @@ -2660,39 +3012,30 @@ static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs) // Test if mouse cursor is hovering given rectangle // NB- Rectangle is clipped by our current clip setting // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding) -static bool IsMouseHoveringRect(const ImRect& rect) +bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindowRead(); // Clip - ImRect rect_clipped = rect; - if (!window->ClipRectStack.empty()) - { - const ImVec4 clip_rect = window->ClipRectStack.back(); - rect_clipped.Clip(ImRect(ImVec2(clip_rect.x, clip_rect.y), ImVec2(clip_rect.z, clip_rect.w))); - } + ImRect rect_clipped(r_min, r_max); + if (clip) + rect_clipped.Clip(window->ClipRect); // Expand for touch input const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding); return rect_for_touch.Contains(g.IO.MousePos); } -bool ImGui::IsMouseHoveringRect(const ImVec2& rect_min, const ImVec2& rect_max) -{ - return IsMouseHoveringRect(ImRect(rect_min, rect_max)); -} - bool ImGui::IsMouseHoveringWindow() { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - return g.HoveredWindow == window; + ImGuiContext& g = *GImGui; + return g.HoveredWindow == g.CurrentWindow; } bool ImGui::IsMouseHoveringAnyWindow() { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; return g.HoveredWindow != NULL; } @@ -2703,72 +3046,96 @@ bool ImGui::IsPosHoveringAnyWindow(const ImVec2& pos) static bool IsKeyPressedMap(ImGuiKey key, bool repeat) { - ImGuiState& g = *GImGui; - const int key_index = g.IO.KeyMap[key]; + const int key_index = GImGui->IO.KeyMap[key]; return ImGui::IsKeyPressed(key_index, repeat); } +int ImGui::GetKeyIndex(ImGuiKey key) +{ + IM_ASSERT(key >= 0 && key < ImGuiKey_COUNT); + return GImGui->IO.KeyMap[key]; +} + bool ImGui::IsKeyDown(int key_index) { - ImGuiState& g = *GImGui; - IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown)); - return g.IO.KeysDown[key_index]; + if (key_index < 0) return false; + IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown)); + return GImGui->IO.KeysDown[key_index]; } bool ImGui::IsKeyPressed(int key_index, bool repeat) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; + if (key_index < 0) return false; IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown)); - const float t = g.IO.KeysDownTime[key_index]; + const float t = g.IO.KeysDownDuration[key_index]; if (t == 0.0f) return true; - // FIXME: Repeat rate should be provided elsewhere? - const float KEY_REPEAT_DELAY = 0.250f; - const float KEY_REPEAT_RATE = 0.020f; - if (repeat && t > KEY_REPEAT_DELAY) - if ((fmodf(t - KEY_REPEAT_DELAY, KEY_REPEAT_RATE) > KEY_REPEAT_RATE*0.5f) != (fmodf(t - KEY_REPEAT_DELAY - g.IO.DeltaTime, KEY_REPEAT_RATE) > KEY_REPEAT_RATE*0.5f)) + if (repeat && t > g.IO.KeyRepeatDelay) + { + float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate; + if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f)) return true; + } + return false; +} +bool ImGui::IsKeyReleased(int key_index) +{ + ImGuiContext& g = *GImGui; + if (key_index < 0) return false; + IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown)); + if (g.IO.KeysDownDurationPrev[key_index] >= 0.0f && !g.IO.KeysDown[key_index]) + return true; return false; } bool ImGui::IsMouseDown(int button) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseDown[button]; } bool ImGui::IsMouseClicked(int button, bool repeat) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); - const float t = g.IO.MouseDownTime[button]; + const float t = g.IO.MouseDownDuration[button]; if (t == 0.0f) return true; - // FIXME: Repeat rate should be provided elsewhere? - const float MOUSE_REPEAT_DELAY = 0.250f; - const float MOUSE_REPEAT_RATE = 0.020f; - if (repeat && t > MOUSE_REPEAT_DELAY) - if ((fmodf(t - MOUSE_REPEAT_DELAY, MOUSE_REPEAT_RATE) > MOUSE_REPEAT_RATE*0.5f) != (fmodf(t - MOUSE_REPEAT_DELAY - g.IO.DeltaTime, MOUSE_REPEAT_RATE) > MOUSE_REPEAT_RATE*0.5f)) + if (repeat && t > g.IO.KeyRepeatDelay) + { + float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate; + if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f)) return true; + } return false; } +bool ImGui::IsMouseReleased(int button) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + return g.IO.MouseReleased[button]; +} + bool ImGui::IsMouseDoubleClicked(int button) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseDoubleClicked[button]; } bool ImGui::IsMouseDragging(int button, float lock_threshold) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + if (!g.IO.MouseDown[button]) + return false; if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold; @@ -2779,9 +3146,18 @@ ImVec2 ImGui::GetMousePos() return GImGui->IO.MousePos; } +// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed! +ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup() +{ + ImGuiContext& g = *GImGui; + if (g.CurrentPopupStack.Size > 0) + return g.OpenPopupStack[g.CurrentPopupStack.Size-1].MousePosOnOpen; + return g.IO.MousePos; +} + ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; @@ -2793,7 +3169,7 @@ ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold) void ImGui::ResetMouseDragDelta(int button) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr g.IO.MouseClickedPos[button] = g.IO.MousePos; @@ -2809,63 +3185,92 @@ void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type) GImGui->MouseCursor = cursor_type; } +void ImGui::CaptureKeyboardFromApp(bool capture) +{ + GImGui->CaptureKeyboardNextFrame = capture ? 1 : 0; +} + +void ImGui::CaptureMouseFromApp(bool capture) +{ + GImGui->CaptureMouseNextFrame = capture ? 1 : 0; +} + bool ImGui::IsItemHovered() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemHoveredAndUsable; } bool ImGui::IsItemHoveredRect() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemHoveredRect; } bool ImGui::IsItemActive() { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; if (g.ActiveId) { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); return g.ActiveId == window->DC.LastItemID; } return false; } +bool ImGui::IsItemClicked(int mouse_button) +{ + return IsMouseClicked(mouse_button) && IsItemHovered(); +} + +bool ImGui::IsAnyItemHovered() +{ + return GImGui->HoveredId != 0 || GImGui->HoveredIdPreviousFrame != 0; +} + bool ImGui::IsAnyItemActive() { - ImGuiState& g = *GImGui; - return g.ActiveId != 0; + return GImGui->ActiveId != 0; } bool ImGui::IsItemVisible() { - ImGuiWindow* window = GetCurrentWindow(); - ImRect r(window->ClipRectStack.back()); + ImGuiWindow* window = GetCurrentWindowRead(); + ImRect r(window->ClipRect); return r.Overlaps(window->DC.LastItemRect); } +// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority. +void ImGui::SetItemAllowOverlap() +{ + ImGuiContext& g = *GImGui; + if (g.HoveredId == g.CurrentWindow->DC.LastItemID) + g.HoveredIdAllowOverlap = true; + if (g.ActiveId == g.CurrentWindow->DC.LastItemID) + g.ActiveIdAllowOverlap = true; +} + ImVec2 ImGui::GetItemRectMin() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemRect.Min; } ImVec2 ImGui::GetItemRectMax() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemRect.Max; } ImVec2 ImGui::GetItemRectSize() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemRect.GetSize(); } ImVec2 ImGui::CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge, float outward) { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); ImRect rect = window->DC.LastItemRect; rect.Expand(outward); return rect.GetClosestPoint(pos, on_edge); @@ -2874,7 +3279,7 @@ ImVec2 ImGui::CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge, float ou // Tooltip is stored and turned into a BeginTooltip()/EndTooltip() sequence at the end of the frame. Each call override previous value. void ImGui::SetTooltipV(const char* fmt, va_list args) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImFormatStringV(g.Tooltip, IM_ARRAYSIZE(g.Tooltip), fmt, args); } @@ -2886,86 +3291,259 @@ void ImGui::SetTooltip(const char* fmt, ...) va_end(args); } -float ImGui::GetTime() +static ImRect GetVisibleRect() { - return GImGui->Time; -} - -int ImGui::GetFrameCount() -{ - return GImGui->FrameCount; -} - -static ImVec4 GetVisibleRect() -{ - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y) - return ImVec4(g.IO.DisplayVisibleMin.x, g.IO.DisplayVisibleMin.y, g.IO.DisplayVisibleMax.x, g.IO.DisplayVisibleMax.y); - return ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y); + return ImRect(g.IO.DisplayVisibleMin, g.IO.DisplayVisibleMax); + return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y); } void ImGui::BeginTooltip() { - ImGuiState& g = *GImGui; ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize; - ImGui::Begin("##Tooltip", NULL, ImVec2(0,0), g.Style.Colors[ImGuiCol_TooltipBg].w, flags); + ImGui::Begin("##Tooltip", NULL, flags); } void ImGui::EndTooltip() { - IM_ASSERT(GetCurrentWindow()->Flags & ImGuiWindowFlags_Tooltip); + IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls ImGui::End(); } -void ImGui::BeginPopup(bool* p_opened) +static bool IsPopupOpen(ImGuiID id) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - IM_ASSERT(p_opened != NULL); // Must provide a bool at the moment + ImGuiContext& g = *GImGui; + const bool is_open = g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupID == id; + return is_open; +} + +// Mark popup as open (toggle toward open state). +// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. +// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). +// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL) +void ImGui::OpenPopupEx(const char* str_id, bool reopen_existing) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiID id = window->GetID(str_id); + int current_stack_size = g.CurrentPopupStack.Size; + ImGuiPopupRef popup_ref = ImGuiPopupRef(id, window, window->GetID("##menus"), g.IO.MousePos); // Tagged as new ref because constructor sets Window to NULL (we are passing the ParentWindow info here) + if (g.OpenPopupStack.Size < current_stack_size + 1) + g.OpenPopupStack.push_back(popup_ref); + else if (reopen_existing || g.OpenPopupStack[current_stack_size].PopupID != id) + { + g.OpenPopupStack.resize(current_stack_size+1); + g.OpenPopupStack[current_stack_size] = popup_ref; + } +} + +void ImGui::OpenPopup(const char* str_id) +{ + ImGui::OpenPopupEx(str_id, false); +} + +static void CloseInactivePopups() +{ + ImGuiContext& g = *GImGui; + if (g.OpenPopupStack.empty()) + return; + + // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it. + // Don't close our own child popup windows + int n = 0; + if (g.FocusedWindow) + { + for (n = 0; n < g.OpenPopupStack.Size; n++) + { + ImGuiPopupRef& popup = g.OpenPopupStack[n]; + if (!popup.Window) + continue; + IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0); + if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow) + continue; + + bool has_focus = false; + for (int m = n; m < g.OpenPopupStack.Size && !has_focus; m++) + has_focus = (g.OpenPopupStack[m].Window && g.OpenPopupStack[m].Window->RootWindow == g.FocusedWindow->RootWindow); + if (!has_focus) + break; + } + } + if (n < g.OpenPopupStack.Size) // This test is not required but it allows to set a useful breakpoint on the line below + g.OpenPopupStack.resize(n); +} + +static ImGuiWindow* GetFrontMostModalRootWindow() +{ + ImGuiContext& g = *GImGui; + for (int n = g.OpenPopupStack.Size-1; n >= 0; n--) + if (ImGuiWindow* front_most_popup = g.OpenPopupStack.Data[n].Window) + if (front_most_popup->Flags & ImGuiWindowFlags_Modal) + return front_most_popup; + return NULL; +} + +static void ClosePopupToLevel(int remaining) +{ + ImGuiContext& g = *GImGui; + if (remaining > 0) + ImGui::FocusWindow(g.OpenPopupStack[remaining-1].Window); + else + ImGui::FocusWindow(g.OpenPopupStack[0].ParentWindow); + g.OpenPopupStack.resize(remaining); +} + +static void ClosePopup(ImGuiID id) +{ + if (!IsPopupOpen(id)) + return; + ImGuiContext& g = *GImGui; + ClosePopupToLevel(g.OpenPopupStack.Size - 1); +} + +// Close the popup we have begin-ed into. +void ImGui::CloseCurrentPopup() +{ + ImGuiContext& g = *GImGui; + int popup_idx = g.CurrentPopupStack.Size - 1; + if (popup_idx < 0 || popup_idx > g.OpenPopupStack.Size || g.CurrentPopupStack[popup_idx].PopupID != g.OpenPopupStack[popup_idx].PopupID) + return; + while (popup_idx > 0 && g.OpenPopupStack[popup_idx].Window && (g.OpenPopupStack[popup_idx].Window->Flags & ImGuiWindowFlags_ChildMenu)) + popup_idx--; + ClosePopupToLevel(popup_idx); +} + +static inline void ClearSetNextWindowData() +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowPosCond = g.SetNextWindowSizeCond = g.SetNextWindowContentSizeCond = g.SetNextWindowCollapsedCond = 0; + g.SetNextWindowSizeConstraint = g.SetNextWindowFocus = false; +} + +static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + const ImGuiID id = window->GetID(str_id); + if (!IsPopupOpen(id)) + { + ClearSetNextWindowData(); // We behave like Begin() and need to consume those values + return false; + } ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); - ImGuiWindowFlags flags = ImGuiWindowFlags_Popup|ImGuiWindowFlags_ShowBorders|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize; - float alpha = 1.0f; + ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize; - char name[20]; - ImFormatString(name, 20, "##Popup%02d", g.CurrentPopupStackSize++); - ImGui::Begin(name, p_opened, ImVec2(0.0f, 0.0f), alpha, flags); + char name[32]; + if (flags & ImGuiWindowFlags_ChildMenu) + ImFormatString(name, 20, "##menu_%d", g.CurrentPopupStack.Size); // Recycle windows based on depth + else + ImFormatString(name, 20, "##popup_%08x", id); // Not recycling, so we can close/open during the same frame + bool is_open = ImGui::Begin(name, NULL, flags); if (!(window->Flags & ImGuiWindowFlags_ShowBorders)) - GetCurrentWindow()->Flags &= ~ImGuiWindowFlags_ShowBorders; + g.CurrentWindow->Flags &= ~ImGuiWindowFlags_ShowBorders; + if (!is_open) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + ImGui::EndPopup(); + + return is_open; +} + +bool ImGui::BeginPopup(const char* str_id) +{ + if (GImGui->OpenPopupStack.Size <= GImGui->CurrentPopupStack.Size) // Early out for performance + { + ClearSetNextWindowData(); // We behave like Begin() and need to consume those values + return false; + } + return BeginPopupEx(str_id, ImGuiWindowFlags_ShowBorders); +} + +bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags extra_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + const ImGuiID id = window->GetID(name); + if (!IsPopupOpen(id)) + { + ClearSetNextWindowData(); // We behave like Begin() and need to consume those values + return false; + } + + ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_Modal|ImGuiWindowFlags_NoCollapse|ImGuiWindowFlags_NoSavedSettings; + bool is_open = ImGui::Begin(name, p_open, flags); + if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + { + ImGui::EndPopup(); + if (is_open) + ClosePopup(id); + return false; + } + + return is_open; } void ImGui::EndPopup() { - ImGuiState& g = *GImGui; - IM_ASSERT(GetCurrentWindow()->Flags & ImGuiWindowFlags_Popup); - IM_ASSERT(g.CurrentPopupStackSize > 0); - g.CurrentPopupStackSize--; + ImGuiWindow* window = GetCurrentWindow(); + IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls + IM_ASSERT(GImGui->CurrentPopupStack.Size > 0); ImGui::End(); - ImGui::PopStyleVar(); + if (!(window->Flags & ImGuiWindowFlags_Modal)) + ImGui::PopStyleVar(); +} + +// This is a helper to handle the most simple case of associating one named popup to one given widget. +// 1. If you have many possible popups (for different "instances" of a same widget, or for wholly different widgets), you may be better off handling +// this yourself so you can store data relative to the widget that opened the popup instead of choosing different popup identifiers. +// 2. If you want right-clicking on the same item to reopen the popup at new location, use the same code replacing IsItemHovered() with IsItemHoveredRect() +// and passing true to the OpenPopupEx(). +// Because: hovering an item in a window below the popup won't normally trigger is hovering behavior/coloring. The pattern of ignoring the fact that +// the item isn't interactable (because it is blocked by the active popup) may useful in some situation when e.g. large canvas as one item, content of menu +// driven by click position. +bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button) +{ + if (IsItemHovered() && IsMouseClicked(mouse_button)) + OpenPopupEx(str_id, false); + return BeginPopup(str_id); +} + +bool ImGui::BeginPopupContextWindow(bool also_over_items, const char* str_id, int mouse_button) +{ + if (!str_id) str_id = "window_context_menu"; + if (IsMouseHoveringWindow() && IsMouseClicked(mouse_button)) + if (also_over_items || !IsAnyItemHovered()) + OpenPopupEx(str_id, true); + return BeginPopup(str_id); +} + +bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button) +{ + if (!str_id) str_id = "void_context_menu"; + if (!IsMouseHoveringAnyWindow() && IsMouseClicked(mouse_button)) + OpenPopupEx(str_id, true); + return BeginPopup(str_id); } bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow; - ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow; - - const ImVec2 content_max = window->Pos + ImGui::GetContentRegionMax(); - const ImVec2 cursor_pos = window->Pos + ImGui::GetCursorPos(); - ImVec2 size = size_arg; + const ImVec2 content_avail = GetContentRegionAvail(); + ImVec2 size = ImFloor(size_arg); if (size.x <= 0.0f) { if (size.x == 0.0f) flags |= ImGuiWindowFlags_ChildWindowAutoFitX; - size.x = ImMax(content_max.x - cursor_pos.x, g.Style.WindowMinSize.x) - fabsf(size.x); + size.x = ImMax(content_avail.x, 4.0f) - fabsf(size.x); // Arbitrary minimum zero-ish child size of 4.0f (0.0f causing too much issues) } if (size.y <= 0.0f) { if (size.y == 0.0f) flags |= ImGuiWindowFlags_ChildWindowAutoFitY; - size.y = ImMax(content_max.y - cursor_pos.y, g.Style.WindowMinSize.y) - fabsf(size.y); + size.y = ImMax(content_avail.y, 4.0f) - fabsf(size.y); } if (border) flags |= ImGuiWindowFlags_ShowBorders; @@ -2974,8 +3552,7 @@ bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, char title[256]; ImFormatString(title, IM_ARRAYSIZE(title), "%s.%s", window->Name, str_id); - const float alpha = 1.0f; - bool ret = ImGui::Begin(title, NULL, size, alpha, flags); + bool ret = ImGui::Begin(title, NULL, size, -1.0f, flags); if (!(window->Flags & ImGuiWindowFlags_ShowBorders)) GetCurrentWindow()->Flags &= ~ImGuiWindowFlags_ShowBorders; @@ -2986,7 +3563,7 @@ bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, bool ImGui::BeginChild(ImGuiID id, const ImVec2& size, bool border, ImGuiWindowFlags extra_flags) { char str_id[32]; - ImFormatString(str_id, IM_ARRAYSIZE(str_id), "child_%x", id); + ImFormatString(str_id, IM_ARRAYSIZE(str_id), "child_%08x", id); bool ret = ImGui::BeginChild(str_id, size, border, extra_flags); return ret; } @@ -2995,7 +3572,7 @@ void ImGui::EndChild() { ImGuiWindow* window = GetCurrentWindow(); - IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); + IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss if ((window->Flags & ImGuiWindowFlags_ComboBox) || window->BeginCount > 1) { ImGui::End(); @@ -3003,13 +3580,12 @@ void ImGui::EndChild() else { // When using auto-filling child window, we don't provide full width/height to ItemSize so that it doesn't feed back into automatic size-fitting. - ImGuiState& g = *GImGui; - ImVec2 sz = ImGui::GetWindowSize(); - if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitX) - sz.x = ImMax(g.Style.WindowMinSize.x, sz.x - g.Style.WindowPadding.x); + ImVec2 sz = GetWindowSize(); + if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitX) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f + sz.x = ImMax(4.0f, sz.x); if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitY) - sz.y = ImMax(g.Style.WindowMinSize.y, sz.y - g.Style.WindowPadding.y); - + sz.y = ImMax(4.0f, sz.y); + ImGui::End(); window = GetCurrentWindow(); @@ -3020,66 +3596,72 @@ void ImGui::EndChild() } // Helper to create a child window / scrolling region that looks like a normal widget frame. -void ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size) +bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, style.Colors[ImGuiCol_FrameBg]); ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, style.FrameRounding); - ImGui::BeginChild(id, size); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding); + return ImGui::BeginChild(id, size, (g.CurrentWindow->Flags & ImGuiWindowFlags_ShowBorders) ? true : false, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags); } void ImGui::EndChildFrame() { ImGui::EndChild(); - ImGui::PopStyleVar(); + ImGui::PopStyleVar(2); ImGui::PopStyleColor(); } // Save and compare stack sizes on Begin()/End() to detect usage errors static void CheckStacksSize(ImGuiWindow* window, bool write) { - // NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin) - ImGuiState& g = *GImGui; + // NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin) + ImGuiContext& g = *GImGui; int* p_backup = &window->DC.StackSizesBackup[0]; - { int current = (int)window->IDStack.size(); if (write) *p_backup = current; else IM_ASSERT(*p_backup == current); p_backup++; } // User forgot PopID() - { int current = (int)window->DC.GroupStack.size(); if (write) *p_backup = current; else IM_ASSERT(*p_backup == current); p_backup++; } // User forgot EndGroup() - { int current = (int)g.ColorModifiers.size(); if (write) *p_backup = current; else IM_ASSERT(*p_backup == current); p_backup++; } // User forgot PopStyleColor() - { int current = (int)g.StyleModifiers.size(); if (write) *p_backup = current; else IM_ASSERT(*p_backup == current); p_backup++; } // User forgot PopStyleVar() - { int current = (int)g.FontStack.size(); if (write) *p_backup = current; else IM_ASSERT(*p_backup == current); p_backup++; } // User forgot PopFont() + { int current = window->IDStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushID/PopID Mismatch!"); p_backup++; } // User forgot PopID() + { int current = window->DC.GroupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // User forgot EndGroup() + { int current = g.CurrentPopupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++; }// User forgot EndPopup()/EndMenu() + { int current = g.ColorModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // User forgot PopStyleColor() + { int current = g.StyleModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // User forgot PopStyleVar() + { int current = g.FontStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushFont/PopFont Mismatch!"); p_backup++; } // User forgot PopFont() IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup)); } -static ImVec2 FindBestWindowPos(const ImVec2& mouse_pos, const ImVec2& size, int* last_dir, const ImRect& r_inner) +static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& r_inner) { const ImGuiStyle& style = GImGui->Style; - // Clamp into visible area while not overlapping the cursor - ImRect r_outer(GetVisibleRect()); - r_outer.Reduce(style.DisplaySafeAreaPadding); - ImVec2 mouse_pos_clamped = ImClamp(mouse_pos, r_outer.Min, r_outer.Max - size); + // Clamp into visible area while not overlapping the cursor. Safety padding is optional if our popup size won't fit without it. + ImVec2 safe_padding = style.DisplaySafeAreaPadding; + ImRect r_outer(GetVisibleRect()); + r_outer.Reduce(ImVec2((size.x - r_outer.GetWidth() > safe_padding.x*2) ? safe_padding.x : 0.0f, (size.y - r_outer.GetHeight() > safe_padding.y*2) ? safe_padding.y : 0.0f)); + ImVec2 base_pos_clamped = ImClamp(base_pos, r_outer.Min, r_outer.Max - size); - for (int n = (*last_dir != -1) ? -1 : 0; n < 4; n++) // Right, down, up, left. Favor last used direction. + for (int n = (*last_dir != -1) ? -1 : 0; n < 4; n++) // Last, Right, down, up, left. (Favor last used direction). { const int dir = (n == -1) ? *last_dir : n; ImRect rect(dir == 0 ? r_inner.Max.x : r_outer.Min.x, dir == 1 ? r_inner.Max.y : r_outer.Min.y, dir == 3 ? r_inner.Min.x : r_outer.Max.x, dir == 2 ? r_inner.Min.y : r_outer.Max.y); if (rect.GetWidth() < size.x || rect.GetHeight() < size.y) continue; *last_dir = dir; - return ImVec2(dir == 0 ? r_inner.Max.x : dir == 3 ? r_inner.Min.x - size.x : mouse_pos_clamped.x, dir == 1 ? r_inner.Max.y : dir == 2 ? r_inner.Min.y - size.y : mouse_pos_clamped.y); + return ImVec2(dir == 0 ? r_inner.Max.x : dir == 3 ? r_inner.Min.x - size.x : base_pos_clamped.x, dir == 1 ? r_inner.Max.y : dir == 2 ? r_inner.Min.y - size.y : base_pos_clamped.y); } - // Fallback + // Fallback, try to keep within display *last_dir = -1; - return mouse_pos + ImVec2(2,2); + ImVec2 pos = base_pos; + pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x); + pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y); + return pos; } -static ImGuiWindow* FindWindowByName(const char* name) +ImGuiWindow* ImGui::FindWindowByName(const char* name) { - // FIXME-OPT: Store sorted hashes -> pointers. - ImGuiState& g = *GImGui; + // FIXME-OPT: Store sorted hashes -> pointers so we can do a bissection in a contiguous block + ImGuiContext& g = *GImGui; ImGuiID id = ImHash(name, 0); - for (size_t i = 0; i < g.Windows.size(); i++) + for (int i = 0; i < g.Windows.Size; i++) if (g.Windows[i]->ID == id) return g.Windows[i]; return NULL; @@ -3087,11 +3669,11 @@ static ImGuiWindow* FindWindowByName(const char* name) static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; // Create window the first time ImGuiWindow* window = (ImGuiWindow*)ImGui::MemAlloc(sizeof(ImGuiWindow)); - new(window) ImGuiWindow(name); + IM_PLACEMENT_NEW(window) ImGuiWindow(name); window->Flags = flags; if (flags & ImGuiWindowFlags_NoSavedSettings) @@ -3132,39 +3714,74 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0) { - window->AutoFitFrames = 2; + window->AutoFitFramesX = window->AutoFitFramesY = 2; window->AutoFitOnlyGrows = false; } - else if (ImLengthSqr(window->Size) < 0.00001f) + else { - window->AutoFitFrames = 2; - window->AutoFitOnlyGrows = true; + if (window->Size.x <= 0.0f) + window->AutoFitFramesX = 2; + if (window->Size.y <= 0.0f) + window->AutoFitFramesY = 2; + window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0); } - g.Windows.push_back(window); + if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus) + g.Windows.insert(g.Windows.begin(), window); // Quite slow but rare and only once + else + g.Windows.push_back(window); return window; } -// Push a new ImGui window to add widgets to. -// - 'size' for a regular window denote the initial size for first-time creation (no saved data) and isn't that useful. Use SetNextWindowSize() prior to calling Begin() for more flexible window manipulation. -// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair. -// - Begin/End can be called multiple times during the frame with the same window name to append content. -// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file). -// You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file. -// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned. -// - Passing 'bool* p_opened' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed. -// - Passing non-zero 'size' is roughly equivalent to calling SetNextWindowSize(size, ImGuiSetCond_FirstUseEver) prior to calling Begin(). -bool ImGui::Begin(const char* name, bool* p_opened, ImGuiWindowFlags flags) +static void ApplySizeFullWithConstraint(ImGuiWindow* window, ImVec2 new_size) { - return ImGui::Begin(name, p_opened, ImVec2(0.f, 0.f), -1.0f, flags); + ImGuiContext& g = *GImGui; + if (g.SetNextWindowSizeConstraint) + { + // Using -1,-1 on either X/Y axis to preserve the current size. + ImRect cr = g.SetNextWindowSizeConstraintRect; + new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x; + new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y; + if (g.SetNextWindowSizeConstraintCallback) + { + ImGuiSizeConstraintCallbackData data; + data.UserData = g.SetNextWindowSizeConstraintCallbackUserData; + data.Pos = window->Pos; + data.CurrentSize = window->SizeFull; + data.DesiredSize = new_size; + g.SetNextWindowSizeConstraintCallback(&data); + new_size = data.DesiredSize; + } + } + if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize))) + new_size = ImMax(new_size, g.Style.WindowMinSize); + window->SizeFull = new_size; } -bool ImGui::Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_use, float bg_alpha, ImGuiWindowFlags flags) +// Push a new ImGui window to add widgets to. +// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair. +// - Begin/End can be called multiple times during the frame with the same window name to append content. +// - 'size_on_first_use' for a regular window denote the initial size for first-time creation (no saved data) and isn't that useful. Use SetNextWindowSize() prior to calling Begin() for more flexible window manipulation. +// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file). +// You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file. +// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned. +// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed. +// - Passing non-zero 'size' is roughly equivalent to calling SetNextWindowSize(size, ImGuiSetCond_FirstUseEver) prior to calling Begin(). +bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) { - ImGuiState& g = *GImGui; + return ImGui::Begin(name, p_open, ImVec2(0.f, 0.f), -1.0f, flags); +} + +bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha, ImGuiWindowFlags flags) +{ + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; + IM_ASSERT(name != NULL); // Window name required IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() - IM_ASSERT(name != NULL); // Must pass a name + IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet + + if (flags & ImGuiWindowFlags_NoInputs) + flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize; // Find or create bool window_is_new = false; @@ -3174,38 +3791,73 @@ bool ImGui::Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_ window = CreateNewWindow(name, size_on_first_use, flags); window_is_new = true; } - window->Flags = (ImGuiWindowFlags)flags; const int current_frame = ImGui::GetFrameCount(); - const bool window_was_visible = (window->LastFrameDrawn == current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on + const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame); + if (first_begin_of_the_frame) + window->Flags = (ImGuiWindowFlags)flags; + else + flags = window->Flags; // Add to stack ImGuiWindow* parent_window = !g.CurrentWindowStack.empty() ? g.CurrentWindowStack.back() : NULL; g.CurrentWindowStack.push_back(window); SetCurrentWindow(window); CheckStacksSize(window, true); + IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow)); + + bool window_was_active = (window->LastFrameActive == current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on + if (flags & ImGuiWindowFlags_Popup) + { + ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size]; + window_was_active &= (window->PopupID == popup_ref.PopupID); + window_was_active &= (window == popup_ref.Window); + popup_ref.Window = window; + g.CurrentPopupStack.push_back(popup_ref); + window->PopupID = popup_ref.PopupID; + } + + const bool window_appearing_after_being_hidden = (window->HiddenFrames == 1); // Process SetNextWindow***() calls - bool window_pos_set_by_api = false; + bool window_pos_set_by_api = false, window_size_set_by_api = false; if (g.SetNextWindowPosCond) { - const ImVec2 backup_cursor_pos = window->DC.CursorPos; // FIXME: not sure of the exact reason of this anymore :( need to look into that. - if (!window_was_visible) window->SetWindowPosAllowFlags |= ImGuiSetCond_Appearing; + const ImVec2 backup_cursor_pos = window->DC.CursorPos; // FIXME: not sure of the exact reason of this saving/restore anymore :( need to look into that. + if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowPosAllowFlags |= ImGuiSetCond_Appearing; window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.SetNextWindowPosCond) != 0; - ImGui::SetWindowPos(g.SetNextWindowPosVal, g.SetNextWindowPosCond); + if (window_pos_set_by_api && ImLengthSqr(g.SetNextWindowPosVal - ImVec2(-FLT_MAX,-FLT_MAX)) < 0.001f) + { + window->SetWindowPosCenterWanted = true; // May be processed on the next frame if this is our first frame and we are measuring size + window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); + } + else + { + SetWindowPos(window, g.SetNextWindowPosVal, g.SetNextWindowPosCond); + } window->DC.CursorPos = backup_cursor_pos; g.SetNextWindowPosCond = 0; } if (g.SetNextWindowSizeCond) { - if (!window_was_visible) window->SetWindowSizeAllowFlags |= ImGuiSetCond_Appearing; - ImGui::SetWindowSize(g.SetNextWindowSizeVal, g.SetNextWindowSizeCond); + if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowSizeAllowFlags |= ImGuiSetCond_Appearing; + window_size_set_by_api = (window->SetWindowSizeAllowFlags & g.SetNextWindowSizeCond) != 0; + SetWindowSize(window, g.SetNextWindowSizeVal, g.SetNextWindowSizeCond); g.SetNextWindowSizeCond = 0; } + if (g.SetNextWindowContentSizeCond) + { + window->SizeContentsExplicit = g.SetNextWindowContentSizeVal; + g.SetNextWindowContentSizeCond = 0; + } + else if (first_begin_of_the_frame) + { + window->SizeContentsExplicit = ImVec2(0.0f, 0.0f); + } if (g.SetNextWindowCollapsedCond) { - if (!window_was_visible) window->SetWindowCollapsedAllowFlags |= ImGuiSetCond_Appearing; - ImGui::SetWindowCollapsed(g.SetNextWindowCollapsedVal, g.SetNextWindowCollapsedCond); + if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowCollapsedAllowFlags |= ImGuiSetCond_Appearing; + SetWindowCollapsed(window, g.SetNextWindowCollapsedVal, g.SetNextWindowCollapsedCond); g.SetNextWindowCollapsedCond = 0; } if (g.SetNextWindowFocus) @@ -3215,57 +3867,56 @@ bool ImGui::Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_ } // Update known root window (if we are a child window, otherwise window == window->RootWindow) - size_t root_idx = g.CurrentWindowStack.size() - 1; - while (root_idx > 0) - { - if ((g.CurrentWindowStack[root_idx]->Flags & ImGuiWindowFlags_ChildWindow) == 0) + int root_idx, root_non_popup_idx; + for (root_idx = g.CurrentWindowStack.Size - 1; root_idx > 0; root_idx--) + if (!(g.CurrentWindowStack[root_idx]->Flags & ImGuiWindowFlags_ChildWindow)) break; - root_idx--; - } + for (root_non_popup_idx = root_idx; root_non_popup_idx > 0; root_non_popup_idx--) + if (!(g.CurrentWindowStack[root_non_popup_idx]->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) + break; + window->ParentWindow = parent_window; window->RootWindow = g.CurrentWindowStack[root_idx]; - - // Default alpha - if (bg_alpha < 0.0f) - bg_alpha = style.WindowFillAlphaDefault; + window->RootNonPopupWindow = g.CurrentWindowStack[root_non_popup_idx]; // This is merely for displaying the TitleBgActive color. // When reusing window again multiple times a frame, just append content (don't need to setup again) - const bool first_begin_of_the_frame = (window->LastFrameDrawn != current_frame); if (first_begin_of_the_frame) { window->Active = true; + window->IndexWithinParent = 0; window->BeginCount = 0; - window->DrawList->Clear(); - window->ClipRectStack.resize(0); - window->LastFrameDrawn = current_frame; + window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX); + window->LastFrameActive = current_frame; window->IDStack.resize(1); - // Setup texture, outer clipping rectangle + // Clear draw list, setup texture, outer clipping rectangle + window->DrawList->Clear(); window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); - if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ComboBox)) - PushClipRect(parent_window->ClipRectStack.back()); + ImRect fullscreen_rect(GetVisibleRect()); + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_ComboBox|ImGuiWindowFlags_Popup))) + PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true); else - PushClipRect(GetVisibleRect()); + PushClipRect(fullscreen_rect.Min, fullscreen_rect.Max, true); // New windows appears in front - if (!window_was_visible) + if (!window_was_active) { window->AutoPosLastDirection = -1; - if (!(flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip)) - { - FocusWindow(window); + if (!(flags & ImGuiWindowFlags_NoFocusOnAppearing)) + if (!(flags & (ImGuiWindowFlags_ChildWindow|ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup)) + FocusWindow(window); - // Popup first latch mouse position, will position itself when it appears next frame - if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api) - window->PosFloat = g.IO.MousePos; - } + // Popup first latch mouse position, will position itself when it appears next frame + if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api) + window->PosFloat = g.IO.MousePos; } // Collapse window by double-clicking on title bar // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse)) { - if (g.HoveredWindow == window && IsMouseHoveringRect(window->TitleBarRect()) && g.IO.MouseDoubleClicked[0]) + ImRect title_bar_rect = window->TitleBarRect(); + if (g.HoveredWindow == window && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0]) { window->Collapsed = !window->Collapsed; if (!(flags & ImGuiWindowFlags_NoSavedSettings)) @@ -3278,36 +3929,46 @@ bool ImGui::Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_ window->Collapsed = false; } - const bool window_appearing_after_being_hidden = (window->HiddenFrames == 1); - if (window->HiddenFrames > 0) - window->HiddenFrames--; - // SIZE - // Save contents size from last frame for auto-fitting - window->SizeContents = window_is_new ? ImVec2(0.0f, 0.0f) : window->DC.CursorMaxPos - window->Pos; - window->SizeContents.y += window->ScrollY; + // Save contents size from last frame for auto-fitting (unless explicitly specified) + window->SizeContents.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.x - window->Pos.x) + window->Scroll.x)); + window->SizeContents.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.y - window->Pos.y) + window->Scroll.y)); // Hide popup/tooltip window when first appearing while we measure size (because we recycle them) - if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0 && !window->WasActive) + if (window->HiddenFrames > 0) + window->HiddenFrames--; + if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0 && !window_was_active) { window->HiddenFrames = 1; - window->Size = window->SizeFull = window->SizeContents = ImVec2(0.f, 0.f); // TODO: We don't support SetNextWindowSize() for tooltips or popups yet + if (flags & ImGuiWindowFlags_AlwaysAutoResize) + { + if (!window_size_set_by_api) + window->Size = window->SizeFull = ImVec2(0.f, 0.f); + window->SizeContents = ImVec2(0.f, 0.f); + } } + // Lock window padding so that altering the ShowBorders flag for children doesn't have side-effects. + window->WindowPadding = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_ShowBorders | ImGuiWindowFlags_ComboBox | ImGuiWindowFlags_Popup))) ? ImVec2(0,0) : style.WindowPadding; + // Calculate auto-fit size ImVec2 size_auto_fit; if ((flags & ImGuiWindowFlags_Tooltip) != 0) { // Tooltip always resize. We keep the spacing symmetric on both axises for aesthetic purpose. - size_auto_fit = window->SizeContents + style.WindowPadding - ImVec2(0.0f, style.ItemSpacing.y); + size_auto_fit = window->SizeContents + window->WindowPadding - ImVec2(0.0f, style.ItemSpacing.y); } else { - size_auto_fit = ImClamp(window->SizeContents + style.WindowPadding, style.WindowMinSize, ImMax(style.WindowMinSize, g.IO.DisplaySize - style.WindowPadding)); - if (size_auto_fit.y < window->SizeContents.y + style.WindowPadding.y) - size_auto_fit.x += style.ScrollbarWidth; - size_auto_fit.y -= style.ItemSpacing.y; + size_auto_fit = ImClamp(window->SizeContents + window->WindowPadding, style.WindowMinSize, ImMax(style.WindowMinSize, g.IO.DisplaySize - g.Style.DisplaySafeAreaPadding)); + + // Handling case of auto fit window not fitting in screen on one axis, we are growing auto fit size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than DisplaySize-WindowPadding. + if (size_auto_fit.x < window->SizeContents.x && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)) + size_auto_fit.y += style.ScrollbarSize; + if (size_auto_fit.y < window->SizeContents.y && !(flags & ImGuiWindowFlags_NoScrollbar)) + size_auto_fit.x += style.ScrollbarSize; + size_auto_fit.y = ImMax(size_auto_fit.y - style.ItemSpacing.y, 0.0f); } // Handle automatic resize @@ -3315,80 +3976,84 @@ bool ImGui::Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_ { // We still process initial auto-fit on collapsed windows to get a window width, // But otherwise we don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed. - if (window->AutoFitFrames > 0) - window->SizeFull = window->AutoFitOnlyGrows ? ImMax(window->SizeFull, size_auto_fit) : size_auto_fit; - window->Size = window->TitleBarRect().GetSize(); + if (window->AutoFitFramesX > 0) + window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; + if (window->AutoFitFramesY > 0) + window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; } else { - if (flags & ImGuiWindowFlags_AlwaysAutoResize) + if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window_size_set_by_api) { window->SizeFull = size_auto_fit; } - else if (window->AutoFitFrames > 0) + else if ((window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) && !window_size_set_by_api) { // Auto-fit only grows during the first few frames - window->SizeFull = window->AutoFitOnlyGrows ? ImMax(window->SizeFull, size_auto_fit) : size_auto_fit; + if (window->AutoFitFramesX > 0) + window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; + if (window->AutoFitFramesY > 0) + window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; if (!(flags & ImGuiWindowFlags_NoSavedSettings)) MarkSettingsDirty(); } - window->Size = window->SizeFull; } - // Minimum window size - if (!(flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip)) - window->SizeFull = ImMax(window->SizeFull, style.WindowMinSize); - + // Apply minimum/maximum window size constraints and final size + ApplySizeFullWithConstraint(window, window->SizeFull); + window->Size = window->Collapsed ? window->TitleBarRect().GetSize() : window->SizeFull; + // POSITION // Position child window if (flags & ImGuiWindowFlags_ChildWindow) { + window->IndexWithinParent = parent_window->DC.ChildWindows.Size; parent_window->DC.ChildWindows.push_back(window); + } + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) + { window->Pos = window->PosFloat = parent_window->DC.CursorPos; - window->SizeFull = size_on_first_use; // NB: argument name 'size_on_first_use' misleading here, it's really just 'size' as provided by user. + window->Size = window->SizeFull = size_on_first_use; // NB: argument name 'size_on_first_use' misleading here, it's really just 'size' as provided by user passed via BeginChild()->Begin(). } - // Position popup - if ((flags & ImGuiWindowFlags_Popup) != 0 && window_appearing_after_being_hidden && !window_pos_set_by_api) + bool window_pos_center = false; + window_pos_center |= (window->SetWindowPosCenterWanted && window->HiddenFrames == 0); + window_pos_center |= ((flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api && window_appearing_after_being_hidden); + if (window_pos_center) + { + // Center (any sort of window) + SetWindowPos(ImMax(style.DisplaySafeAreaPadding, fullscreen_rect.GetCenter() - window->SizeFull * 0.5f)); + } + else if (flags & ImGuiWindowFlags_ChildMenu) + { + IM_ASSERT(window_pos_set_by_api); + ImRect rect_to_avoid; + if (parent_window->DC.MenuBarAppending) + rect_to_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight()); + else + rect_to_avoid = ImRect(parent_window->Pos.x + style.ItemSpacing.x, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - style.ItemSpacing.x - parent_window->ScrollbarSizes.x, FLT_MAX); // We want some overlap to convey the relative depth of each popup (here hard-coded to 4) + window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid); + } + else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_appearing_after_being_hidden) { ImRect rect_to_avoid(window->PosFloat.x - 1, window->PosFloat.y - 1, window->PosFloat.x + 1, window->PosFloat.y + 1); - window->PosFloat = FindBestWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid); + window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid); } // Position tooltip (always follows mouse) if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api) { ImRect rect_to_avoid(g.IO.MousePos.x - 16, g.IO.MousePos.y - 8, g.IO.MousePos.x + 24, g.IO.MousePos.y + 24); // FIXME: Completely hard-coded. Perhaps center on cursor hit-point instead? - window->PosFloat = FindBestWindowPos(g.IO.MousePos, window->Size, &window->AutoPosLastDirection, rect_to_avoid); + window->PosFloat = FindBestPopupWindowPos(g.IO.MousePos, window->Size, &window->AutoPosLastDirection, rect_to_avoid); + if (window->AutoPosLastDirection == -1) + window->PosFloat = g.IO.MousePos + ImVec2(2,2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible. } - // User moving window (at the beginning of the frame to avoid input lag or sheering). Only valid for root windows. - RegisterAliveId(window->MoveID); - if (g.ActiveId == window->MoveID) - { - if (g.IO.MouseDown[0]) - { - if (!(flags & ImGuiWindowFlags_NoMove)) - { - window->PosFloat += g.IO.MouseDelta; - if (!(flags & ImGuiWindowFlags_NoSavedSettings)) - MarkSettingsDirty(); - } - IM_ASSERT(g.MovedWindow != NULL); - FocusWindow(g.MovedWindow); - } - else - { - SetActiveId(0); - g.MovedWindow = NULL; // Not strictly necessary but doing it for sanity. - } - } - - // Clamp into display + // Clamp position so it stays visible if (!(flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip)) { - if (window->AutoFitFrames <= 0 && g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f) // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. + if (!window_pos_set_by_api && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f) // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. { ImVec2 padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); window->PosFloat = ImMax(window->PosFloat + window->Size, padding) - window->Size; @@ -3401,26 +4066,33 @@ bool ImGui::Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_ if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize)) window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f); else - window->ItemWidthDefault = 200.0f; + window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f); // Prepare for focus requests - if (window->FocusIdxAllRequestNext == IM_INT_MAX || window->FocusIdxAllCounter == -1) - window->FocusIdxAllRequestCurrent = IM_INT_MAX; - else - window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1); - if (window->FocusIdxTabRequestNext == IM_INT_MAX || window->FocusIdxTabCounter == -1) - window->FocusIdxTabRequestCurrent = IM_INT_MAX; - else - window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1); + window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext == INT_MAX || window->FocusIdxAllCounter == -1) ? INT_MAX : (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1); + window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext == INT_MAX || window->FocusIdxTabCounter == -1) ? INT_MAX : (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1); window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1; - window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = IM_INT_MAX; + window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = INT_MAX; // Apply scrolling - window->ScrollY = window->NextScrollY; - window->ScrollY = ImMax(window->ScrollY, 0.0f); + if (window->ScrollTarget.x < FLT_MAX) + { + window->Scroll.x = window->ScrollTarget.x; + window->ScrollTarget.x = FLT_MAX; + } + if (window->ScrollTarget.y < FLT_MAX) + { + float center_ratio = window->ScrollTargetCenterRatio.y; + window->Scroll.y = window->ScrollTarget.y - ((1.0f - center_ratio) * window->TitleBarHeight()) - (center_ratio * window->SizeFull.y); + window->ScrollTarget.y = FLT_MAX; + } + window->Scroll = ImMax(window->Scroll, ImVec2(0.0f, 0.0f)); if (!window->Collapsed && !window->SkipItems) - window->ScrollY = ImMin(window->ScrollY, ImMax(0.0f, window->SizeContents.y - window->SizeFull.y)); - window->NextScrollY = window->ScrollY; + window->Scroll = ImMin(window->Scroll, ImMax(ImVec2(0.0f, 0.0f), window->SizeContents - window->SizeFull + window->ScrollbarSizes)); + + // Modal window darkens what is behind them + if ((flags & ImGuiWindowFlags_Modal) != 0 && window == GetFrontMostModalRootWindow()) + window->DrawList->AddRectFilled(fullscreen_rect.Min, fullscreen_rect.Max, GetColorU32(ImGuiCol_ModalWindowDarkening, g.ModalWindowDarkeningRatio)); // Draw window + handle manual resize ImRect title_bar_rect = window->TitleBarRect(); @@ -3428,24 +4100,21 @@ bool ImGui::Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_ if (window->Collapsed) { // Draw title bar only - window->DrawList->AddRectFilled(title_bar_rect.GetTL(), title_bar_rect.GetBR(), window->Color(ImGuiCol_TitleBgCollapsed), window_rounding); - if (flags & ImGuiWindowFlags_ShowBorders) - { - window->DrawList->AddRect(title_bar_rect.GetTL()+ImVec2(1,1), title_bar_rect.GetBR()+ImVec2(1,1), window->Color(ImGuiCol_BorderShadow), window_rounding); - window->DrawList->AddRect(title_bar_rect.GetTL(), title_bar_rect.GetBR(), window->Color(ImGuiCol_Border), window_rounding); - } + RenderFrame(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32(ImGuiCol_TitleBgCollapsed), true, window_rounding); } else { ImU32 resize_col = 0; - if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFrames <= 0 && !(flags & ImGuiWindowFlags_NoResize)) + const float resize_corner_size = ImMax(g.FontSize * 1.35f, window_rounding + 1.0f + g.FontSize * 0.2f); + if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && !(flags & ImGuiWindowFlags_NoResize)) { // Manual resize - const ImRect resize_rect(window->Rect().GetBR()-ImVec2(14,14), window->Rect().GetBR()); + const ImVec2 br = window->Rect().GetBR(); + const ImRect resize_rect(br - ImVec2(resize_corner_size * 0.75f, resize_corner_size * 0.75f), br); const ImGuiID resize_id = window->GetID("#RESIZE"); bool hovered, held; - ButtonBehavior(resize_rect, resize_id, &hovered, &held, true, ImGuiButtonFlags_FlattenChilds); - resize_col = window->Color(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip); + ButtonBehavior(resize_rect, resize_id, &hovered, &held, ImGuiButtonFlags_FlattenChilds); + resize_col = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip); if (hovered || held) g.MouseCursor = ImGuiMouseCursor_ResizeNWSE; @@ -3453,14 +4122,15 @@ bool ImGui::Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_ if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0]) { // Manual auto-fit when double-clicking - window->SizeFull = size_auto_fit; + ApplySizeFullWithConstraint(window, size_auto_fit); if (!(flags & ImGuiWindowFlags_NoSavedSettings)) MarkSettingsDirty(); - SetActiveId(0); + SetActiveID(0); } else if (held) { - window->SizeFull = ImMax(window->SizeFull + g.IO.MouseDelta, style.WindowMinSize); + // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position + ApplySizeFullWithConstraint(window, (g.IO.MousePos - g.ActiveIdClickOffset + resize_rect.GetSize()) - window->Pos); if (!(flags & ImGuiWindowFlags_NoSavedSettings)) MarkSettingsDirty(); } @@ -3469,124 +4139,140 @@ bool ImGui::Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_ title_bar_rect = window->TitleBarRect(); } - // Scrollbar - window->ScrollbarY = (window->SizeContents.y > window->Size.y) && !(flags & ImGuiWindowFlags_NoScrollbar); + // Scrollbars + window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > window->Size.y + style.ItemSpacing.y) && !(flags & ImGuiWindowFlags_NoScrollbar)); + window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > window->Size.x - (window->ScrollbarY ? style.ScrollbarSize : 0.0f) - window->WindowPadding.x) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); + window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f); + window->BorderSize = (flags & ImGuiWindowFlags_ShowBorders) ? 1.0f : 0.0f; // Window background - if (bg_alpha > 0.0f) - { - if ((flags & ImGuiWindowFlags_ComboBox) != 0) - window->DrawList->AddRectFilled(window->Pos, window->Pos+window->Size, window->Color(ImGuiCol_ComboBg, bg_alpha), window_rounding); - else if ((flags & ImGuiWindowFlags_Tooltip) != 0) - window->DrawList->AddRectFilled(window->Pos, window->Pos+window->Size, window->Color(ImGuiCol_TooltipBg, bg_alpha), window_rounding); - else if ((flags & ImGuiWindowFlags_ChildWindow) != 0) - window->DrawList->AddRectFilled(window->Pos, window->Pos+window->Size-ImVec2(window->ScrollbarY?style.ScrollbarWidth:0.0f,0.0f), window->Color(ImGuiCol_ChildWindowBg, bg_alpha), window_rounding, window->ScrollbarY ? (1|8) : (0xF)); - else - window->DrawList->AddRectFilled(window->Pos, window->Pos+window->Size, window->Color(ImGuiCol_WindowBg, bg_alpha), window_rounding); - } + // Default alpha + ImGuiCol bg_color_idx = ImGuiCol_WindowBg; + if ((flags & ImGuiWindowFlags_ComboBox) != 0) + bg_color_idx = ImGuiCol_ComboBg; + else if ((flags & ImGuiWindowFlags_Tooltip) != 0 || (flags & ImGuiWindowFlags_Popup) != 0) + bg_color_idx = ImGuiCol_PopupBg; + else if ((flags & ImGuiWindowFlags_ChildWindow) != 0) + bg_color_idx = ImGuiCol_ChildWindowBg; + ImVec4 bg_color = style.Colors[bg_color_idx]; + if (bg_alpha >= 0.0f) + bg_color.w = bg_alpha; + bg_color.w *= style.Alpha; + if (bg_color.w > 0.0f) + window->DrawList->AddRectFilled(window->Pos+ImVec2(0,window->TitleBarHeight()), window->Pos+window->Size, ColorConvertFloat4ToU32(bg_color), window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 15 : 4|8); // Title bar if (!(flags & ImGuiWindowFlags_NoTitleBar)) - window->DrawList->AddRectFilled(title_bar_rect.GetTL(), title_bar_rect.GetBR(), window->Color(ImGuiCol_TitleBg), window_rounding, 1|2); + window->DrawList->AddRectFilled(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32((g.FocusedWindow && window->RootNonPopupWindow == g.FocusedWindow->RootNonPopupWindow) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg), window_rounding, 1|2); - // Borders - if (flags & ImGuiWindowFlags_ShowBorders) + // Menu bar + if (flags & ImGuiWindowFlags_MenuBar) { - window->DrawList->AddRect(window->Pos+ImVec2(1,1), window->Pos+window->Size+ImVec2(1,1), window->Color(ImGuiCol_BorderShadow), window_rounding); - window->DrawList->AddRect(window->Pos, window->Pos+window->Size, window->Color(ImGuiCol_Border), window_rounding); - if (!(flags & ImGuiWindowFlags_NoTitleBar)) - window->DrawList->AddLine(title_bar_rect.GetBL(), title_bar_rect.GetBR(), window->Color(ImGuiCol_Border)); + ImRect menu_bar_rect = window->MenuBarRect(); + window->DrawList->AddRectFilled(menu_bar_rect.GetTL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, 1|2); + if (flags & ImGuiWindowFlags_ShowBorders) + window->DrawList->AddLine(menu_bar_rect.GetBL()-ImVec2(0,0), menu_bar_rect.GetBR()-ImVec2(0,0), GetColorU32(ImGuiCol_Border)); } - // Scrollbar + // Scrollbars + if (window->ScrollbarX) + Scrollbar(window, true); if (window->ScrollbarY) - Scrollbar(window); + Scrollbar(window, false); // Render resize grip // (after the input handling so we don't have a frame of latency) if (!(flags & ImGuiWindowFlags_NoResize)) { - const float r = window_rounding; const ImVec2 br = window->Rect().GetBR(); - if (r == 0.0f) - { - window->DrawList->AddTriangleFilled(br, br-ImVec2(0,14), br-ImVec2(14,0), resize_col); - } - else - { - // FIXME: We should draw 4 triangles and decide on a size that's not dependent on the rounding size (previously used 18) - window->DrawList->AddArcFast(br - ImVec2(r,r), r, resize_col, 6, 9, true); - window->DrawList->AddTriangleFilled(br+ImVec2(0,-2*r),br+ImVec2(0,-r),br+ImVec2(-r,-r), resize_col); - window->DrawList->AddTriangleFilled(br+ImVec2(-r,-r), br+ImVec2(-r,0),br+ImVec2(-2*r,0), resize_col); - } + window->DrawList->PathLineTo(br + ImVec2(-resize_corner_size, -window->BorderSize)); + window->DrawList->PathLineTo(br + ImVec2(-window->BorderSize, -resize_corner_size)); + window->DrawList->PathArcToFast(ImVec2(br.x - window_rounding - window->BorderSize, br.y - window_rounding - window->BorderSize), window_rounding, 0, 3); + window->DrawList->PathFill(resize_col); + } + + // Borders + if (flags & ImGuiWindowFlags_ShowBorders) + { + window->DrawList->AddRect(window->Pos+ImVec2(1,1), window->Pos+window->Size+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), window_rounding); + window->DrawList->AddRect(window->Pos, window->Pos+window->Size, GetColorU32(ImGuiCol_Border), window_rounding); + if (!(flags & ImGuiWindowFlags_NoTitleBar)) + window->DrawList->AddLine(title_bar_rect.GetBL()+ImVec2(1,0), title_bar_rect.GetBR()-ImVec2(1,0), GetColorU32(ImGuiCol_Border)); } } + // Update ContentsRegionMax. All the variable it depends on are set above in this function. + window->ContentsRegionRect.Min.x = -window->Scroll.x + window->WindowPadding.x; + window->ContentsRegionRect.Min.x = -window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight(); + window->ContentsRegionRect.Max.x = -window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x)); + window->ContentsRegionRect.Max.y = -window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y)); + // Setup drawing context - window->DC.ColumnsStartX = window->WindowPadding().x; + window->DC.IndentX = 0.0f + window->WindowPadding.x - window->Scroll.x; window->DC.ColumnsOffsetX = 0.0f; - window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.ColumnsStartX + window->DC.ColumnsOffsetX, window->TitleBarHeight() + window->WindowPadding().y) - ImVec2(0.0f, window->ScrollY); + window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.IndentX + window->DC.ColumnsOffsetX, window->TitleBarHeight() + window->MenuBarHeight() + window->WindowPadding.y - window->Scroll.y); window->DC.CursorPos = window->DC.CursorStartPos; window->DC.CursorPosPrevLine = window->DC.CursorPos; window->DC.CursorMaxPos = window->DC.CursorStartPos; window->DC.CurrentLineHeight = window->DC.PrevLineHeight = 0.0f; window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f; + window->DC.MenuBarAppending = false; + window->DC.MenuBarOffsetX = ImMax(window->WindowPadding.x, style.ItemSpacing.x); window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; window->DC.ChildWindows.resize(0); - window->DC.ItemWidth.resize(0); - window->DC.ItemWidth.push_back(window->ItemWidthDefault); - window->DC.AllowKeyboardFocus.resize(0); - window->DC.AllowKeyboardFocus.push_back(true); - window->DC.TextWrapPos.resize(0); - window->DC.TextWrapPos.push_back(-1.0f); // disabled + window->DC.LayoutType = ImGuiLayoutType_Vertical; + window->DC.ItemWidth = window->ItemWidthDefault; + window->DC.TextWrapPos = -1.0f; // disabled + window->DC.AllowKeyboardFocus = true; + window->DC.ButtonRepeat = false; + window->DC.ItemWidthStack.resize(0); + window->DC.TextWrapPosStack.resize(0); + window->DC.AllowKeyboardFocusStack.resize(0); + window->DC.ButtonRepeatStack.resize(0); window->DC.ColorEditMode = ImGuiColorEditMode_UserSelect; window->DC.ColumnsCurrent = 0; window->DC.ColumnsCount = 1; - window->DC.ColumnsStartPos = window->DC.CursorPos; - window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.ColumnsStartPos.y; + window->DC.ColumnsStartPosY = window->DC.CursorPos.y; + window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.ColumnsStartPosY; window->DC.TreeDepth = 0; window->DC.StateStorage = &window->StateStorage; window->DC.GroupStack.resize(0); + window->MenuColumns.Update(3, style.ItemSpacing.x, !window_was_active); - if (window->AutoFitFrames > 0) - window->AutoFitFrames--; + if (window->AutoFitFramesX > 0) + window->AutoFitFramesX--; + if (window->AutoFitFramesY > 0) + window->AutoFitFramesY--; // Title bar if (!(flags & ImGuiWindowFlags_NoTitleBar)) { - if (p_opened != NULL) - CloseWindowButton(p_opened); + if (p_open != NULL) + { + const float pad = 2.0f; + const float rad = (window->TitleBarHeight() - pad*2.0f) * 0.5f; + if (CloseButton(window->GetID("#CLOSE"), window->Rect().GetTR() + ImVec2(-pad - rad, pad + rad), rad)) + *p_open = false; + } const ImVec2 text_size = CalcTextSize(name, NULL, true); if (!(flags & ImGuiWindowFlags_NoCollapse)) RenderCollapseTriangle(window->Pos + style.FramePadding, !window->Collapsed, 1.0f, true); - + ImVec2 text_min = window->Pos + style.FramePadding; ImVec2 text_max = window->Pos + ImVec2(window->Size.x - style.FramePadding.x, style.FramePadding.y*2 + text_size.y); - ImVec2 clip_max = ImVec2(window->Pos.x + window->Size.x - (p_opened ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x), text_max.y); // Match the size of CloseWindowButton() + ImVec2 clip_max = ImVec2(window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x), text_max.y); // Match the size of CloseWindowButton() bool pad_left = (flags & ImGuiWindowFlags_NoCollapse) == 0; - bool pad_right = (p_opened != NULL); + bool pad_right = (p_open != NULL); if (style.WindowTitleAlign & ImGuiAlign_Center) pad_right = pad_left; if (pad_left) text_min.x += g.FontSize + style.ItemInnerSpacing.x; if (pad_right) text_max.x -= g.FontSize + style.ItemInnerSpacing.x; - RenderTextClipped(text_min, name, NULL, &text_size, text_max, &clip_max, style.WindowTitleAlign); - } - if (flags & ImGuiWindowFlags_Popup) - { - if (p_opened) - { - if (g.IO.MouseClicked[0] && (!g.HoveredWindow || g.HoveredWindow->RootWindow != window)) - *p_opened = false; - else if (!g.FocusedWindow) - *p_opened = false; - else if (g.FocusedWindow->RootWindow != window)// && !(g.FocusedWindow->RootWindow->Flags & ImGuiWindowFlags_Tooltip)) - *p_opened = false; - } + RenderTextClipped(text_min, text_max, name, NULL, &text_size, style.WindowTitleAlign, NULL, &clip_max); } // Save clipped aabb so we can access it in constant-time in FindHoveredWindow() - window->ClippedRect = window->Rect(); - window->ClippedRect.Clip(window->ClipRectStack.front()); + window->WindowRectClipped = window->Rect(); + window->WindowRectClipped.Clip(window->ClipRect); // Pressing CTRL+C while holding on a window copy its content to the clipboard // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope. @@ -3597,20 +4283,24 @@ bool ImGui::Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_ ImGui::LogToClipboard(); */ } - window->BeginCount++; // Inner clipping rectangle // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame // Note that if our window is collapsed we will end up with a null clipping rectangle which is the correct behavior. const ImRect title_bar_rect = window->TitleBarRect(); - ImVec4 clip_rect(title_bar_rect.Min.x+0.5f+window->WindowPadding().x*0.5f, title_bar_rect.Max.y+0.5f, window->Rect().Max.x+0.5f-window->WindowPadding().x*0.5f, window->Rect().Max.y-1.5f); - if (window->ScrollbarY) - clip_rect.z -= style.ScrollbarWidth; - PushClipRect(clip_rect); + const float border_size = window->BorderSize; + ImRect clip_rect; // Force round to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. + clip_rect.Min.x = ImFloor(0.5f + title_bar_rect.Min.x + ImMax(border_size, ImFloor(window->WindowPadding.x*0.5f))); + clip_rect.Min.y = ImFloor(0.5f + title_bar_rect.Max.y + window->MenuBarHeight() + border_size); + clip_rect.Max.x = ImFloor(0.5f + window->Pos.x + window->Size.x - window->ScrollbarSizes.x - ImMax(border_size, ImFloor(window->WindowPadding.x*0.5f))); + clip_rect.Max.y = ImFloor(0.5f + window->Pos.y + window->Size.y - window->ScrollbarSizes.y - border_size); + PushClipRect(clip_rect.Min, clip_rect.Max, true); // Clear 'accessed' flag last thing if (first_begin_of_the_frame) window->Accessed = false; + window->BeginCount++; + g.SetNextWindowSizeConstraint = false; // Child window can be out of sight and have "negative" clip windows. // Mark them as collapsed so commands are skipped earlier (we can't manually collapse because they have no title bar). @@ -3619,8 +4309,8 @@ bool ImGui::Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_ IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0); window->Collapsed = parent_window && parent_window->Collapsed; - const ImVec4 clip_rect_t = window->ClipRectStack.back(); - window->Collapsed |= (clip_rect_t.x >= clip_rect_t.z || clip_rect_t.y >= clip_rect_t.w); + if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) + window->Collapsed |= (window->WindowRectClipped.Min.x >= window->WindowRectClipped.Max.x || window->WindowRectClipped.Min.y >= window->WindowRectClipped.Max.y); // We also hide the window from rendering because we've already added its border to the command list. // (we could perform the check earlier in the function but it is simpler at this point) @@ -3631,102 +4321,137 @@ bool ImGui::Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_ window->Active = false; // Return false if we don't intend to display anything to allow user to perform an early out optimization - window->SkipItems = (window->Collapsed || !window->Active) && window->AutoFitFrames <= 0; + window->SkipItems = (window->Collapsed || !window->Active) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0; return !window->SkipItems; } void ImGui::End() { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - ImGui::Columns(1, "#CloseColumns"); + Columns(1, "#CloseColumns"); PopClipRect(); // inner window clip rectangle // Stop logging if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging - ImGui::LogFinish(); + LogFinish(); // Pop // NB: we don't clear 'window->RootWindow'. The pointer is allowed to live until the next call to Begin(). - CheckStacksSize(window, false); g.CurrentWindowStack.pop_back(); + if (window->Flags & ImGuiWindowFlags_Popup) + g.CurrentPopupStack.pop_back(); + CheckStacksSize(window, false); SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back()); } // Vertical scrollbar // The entire piece of code below is rather confusing because: // - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab) -// - We store values as ratio and in a form that allows the window content to change while we are holding on a scrollbar -static void Scrollbar(ImGuiWindow* window) +// - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar +// - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal. +static void Scrollbar(ImGuiWindow* window, bool horizontal) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - const ImGuiID id = window->GetID("#SCROLLY"); + const ImGuiID id = window->GetID(horizontal ? "#SCROLLX" : "#SCROLLY"); // Render background - ImRect bb(window->Rect().Max.x - style.ScrollbarWidth, window->Pos.y + window->TitleBarHeight()+1, window->Rect().Max.x, window->Rect().Max.y-1); - window->DrawList->AddRectFilled(bb.Min, bb.Max, window->Color(ImGuiCol_ScrollbarBg)); - bb.Expand(-3.0f); - const float scrollbar_height = bb.GetHeight(); + bool other_scrollbar = (horizontal ? window->ScrollbarY : window->ScrollbarX); + float other_scrollbar_size_w = other_scrollbar ? style.ScrollbarSize : 0.0f; + const ImRect window_rect = window->Rect(); + const float border_size = window->BorderSize; + ImRect bb = horizontal + ? ImRect(window->Pos.x + border_size, window_rect.Max.y - style.ScrollbarSize, window_rect.Max.x - other_scrollbar_size_w - border_size, window_rect.Max.y - border_size) + : ImRect(window_rect.Max.x - style.ScrollbarSize, window->Pos.y + border_size, window_rect.Max.x - border_size, window_rect.Max.y - other_scrollbar_size_w - border_size); + if (!horizontal) + bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() : 0.0f); + + float window_rounding = (window->Flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding; + int window_rounding_corners; + if (horizontal) + window_rounding_corners = 8 | (other_scrollbar ? 0 : 4); + else + window_rounding_corners = (((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? 2 : 0) | (other_scrollbar ? 0 : 4); + window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_ScrollbarBg), window_rounding, window_rounding_corners); + bb.Reduce(ImVec2(ImClamp((float)(int)((bb.Max.x - bb.Min.x - 2.0f) * 0.5f), 0.0f, 3.0f), ImClamp((float)(int)((bb.Max.y - bb.Min.y - 2.0f) * 0.5f), 0.0f, 3.0f))); + + // V denote the main axis of the scrollbar + float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight(); + float scroll_v = horizontal ? window->Scroll.x : window->Scroll.y; + float win_size_avail_v = (horizontal ? window->Size.x : window->Size.y) - other_scrollbar_size_w; + float win_size_contents_v = horizontal ? window->SizeContents.x : window->SizeContents.y; // The grabable box size generally represent the amount visible (vs the total scrollable amount) // But we maintain a minimum size in pixel to allow for the user to still aim inside. - const float grab_h_pixels = ImMin(ImMax(scrollbar_height * ImSaturate(window->Size.y / ImMax(window->SizeContents.y, window->Size.y)), style.GrabMinSize), scrollbar_height); - const float grab_h_norm = grab_h_pixels / scrollbar_height; + const float grab_h_pixels = ImMin(ImMax(scrollbar_size_v * ImSaturate(win_size_avail_v / ImMax(win_size_contents_v, win_size_avail_v)), style.GrabMinSize), scrollbar_size_v); + const float grab_h_norm = grab_h_pixels / scrollbar_size_v; // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar(). bool held = false; bool hovered = false; const bool previously_held = (g.ActiveId == id); - ButtonBehavior(bb, id, &hovered, &held, true); + ImGui::ButtonBehavior(bb, id, &hovered, &held); - const float scroll_max = ImMax(1.0f, window->SizeContents.y - window->Size.y); - float scroll_ratio = ImSaturate(window->ScrollY / scroll_max); - float grab_y_norm = scroll_ratio * (scrollbar_height - grab_h_pixels) / scrollbar_height; - if (held) + float scroll_max = ImMax(1.0f, win_size_contents_v - win_size_avail_v); + float scroll_ratio = ImSaturate(scroll_v / scroll_max); + float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; + if (held && grab_h_norm < 1.0f) { - const float clicked_y_norm = ImSaturate((g.IO.MousePos.y - bb.Min.y) / scrollbar_height); // Click position in scrollbar space (0.0f->1.0f) - g.HoveredId = id; + float scrollbar_pos_v = horizontal ? bb.Min.x : bb.Min.y; + float mouse_pos_v = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; + float* click_delta_to_grab_center_v = horizontal ? &g.ScrollbarClickDeltaToGrabCenter.x : &g.ScrollbarClickDeltaToGrabCenter.y; + + // Click position in scrollbar normalized space (0.0f->1.0f) + const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v); + ImGui::SetHoveredID(id); bool seek_absolute = false; if (!previously_held) { // On initial click calculate the distance between mouse and the center of the grab - if (clicked_y_norm >= grab_y_norm && clicked_y_norm <= grab_y_norm + grab_h_norm) + if (clicked_v_norm >= grab_v_norm && clicked_v_norm <= grab_v_norm + grab_h_norm) { - g.ScrollbarClickDeltaToGrabCenter = clicked_y_norm - grab_y_norm - grab_h_norm*0.5f; + *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f; } else { seek_absolute = true; - g.ScrollbarClickDeltaToGrabCenter = 0; + *click_delta_to_grab_center_v = 0.0f; } } // Apply scroll - const float scroll_y_norm = ImSaturate((clicked_y_norm - g.ScrollbarClickDeltaToGrabCenter - grab_h_norm*0.5f) / (1.0f - grab_h_norm)); - window->ScrollY = (float)(int)(0.5f + scroll_y_norm * (window->SizeContents.y - window->Size.y)); - window->NextScrollY = window->ScrollY; + // It is ok to modify Scroll here because we are being called in Begin() after the calculation of SizeContents and before setting up our starting position + const float scroll_v_norm = ImSaturate((clicked_v_norm - *click_delta_to_grab_center_v - grab_h_norm*0.5f) / (1.0f - grab_h_norm)); + scroll_v = (float)(int)(0.5f + scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v)); + if (horizontal) + window->Scroll.x = scroll_v; + else + window->Scroll.y = scroll_v; // Update values for rendering - scroll_ratio = ImSaturate(window->ScrollY / scroll_max); - grab_y_norm = scroll_ratio * (scrollbar_height - grab_h_pixels) / scrollbar_height; + scroll_ratio = ImSaturate(scroll_v / scroll_max); + grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; // Update distance to grab now that we have seeked and saturated if (seek_absolute) - g.ScrollbarClickDeltaToGrabCenter = clicked_y_norm - grab_y_norm - grab_h_norm*0.5f; + *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f; } // Render - const ImU32 grab_col = window->Color(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab); - window->DrawList->AddRectFilled(ImVec2(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_y_norm)), ImVec2(bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_y_norm) + grab_h_pixels), grab_col, style.ScrollbarRounding); + const ImU32 grab_col = ImGui::GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab); + if (horizontal) + window->DrawList->AddRectFilled(ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y), ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, bb.Max.y), grab_col, style.ScrollbarRounding); + else + window->DrawList->AddRectFilled(ImVec2(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm)), ImVec2(bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels), grab_col, style.ScrollbarRounding); } // Moving window to front of display (which happens to be back of our sorted list) -static void FocusWindow(ImGuiWindow* window) +void ImGui::FocusWindow(ImGuiWindow* window) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; // Always mark the window we passed as focused. This is used for keyboard interactions such as tabbing. g.FocusedWindow = window; @@ -3735,14 +4460,19 @@ static void FocusWindow(ImGuiWindow* window) if (!window) return; - // And move its root window to the top of the pile + // And move its root window to the top of the pile if (window->RootWindow) window = window->RootWindow; - if (g.Windows.back() == window) - return; + // Steal focus on active widgets + if (window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement should be unnecessary. Need further testing before removing it.. + if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != window) + SetActiveID(0); - for (size_t i = 0; i < g.Windows.size(); i++) + // Bring to front + if ((window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) || g.Windows.back() == window) + return; + for (int i = 0; i < g.Windows.Size; i++) if (g.Windows[i] == window) { g.Windows.erase(g.Windows.begin() + i); @@ -3754,47 +4484,49 @@ static void FocusWindow(ImGuiWindow* window) void ImGui::PushItemWidth(float item_width) { ImGuiWindow* window = GetCurrentWindow(); - window->DC.ItemWidth.push_back(item_width == 0.0f ? window->ItemWidthDefault : item_width); + window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width); + window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); } -static void PushMultiItemsWidths(int components, float w_full = 0.0f) +static void PushMultiItemsWidths(int components, float w_full) { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = ImGui::GetCurrentWindow(); const ImGuiStyle& style = GImGui->Style; if (w_full <= 0.0f) w_full = ImGui::CalcItemWidth(); - const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.FramePadding.x*2.0f + style.ItemInnerSpacing.x) * (components-1)) / (float)components)); - const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.FramePadding.x*2.0f + style.ItemInnerSpacing.x) * (components-1))); - window->DC.ItemWidth.push_back(w_item_last); + const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); + const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); + window->DC.ItemWidthStack.push_back(w_item_last); for (int i = 0; i < components-1; i++) - window->DC.ItemWidth.push_back(w_item_one); + window->DC.ItemWidthStack.push_back(w_item_one); + window->DC.ItemWidth = window->DC.ItemWidthStack.back(); } void ImGui::PopItemWidth() { ImGuiWindow* window = GetCurrentWindow(); - window->DC.ItemWidth.pop_back(); + window->DC.ItemWidthStack.pop_back(); + window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back(); } float ImGui::CalcItemWidth() { - ImGuiWindow* window = GetCurrentWindow(); - float w = window->DC.ItemWidth.back(); + ImGuiWindow* window = GetCurrentWindowRead(); + float w = window->DC.ItemWidth; if (w < 0.0f) { // Align to a right-side limit. We include 1 frame padding in the calculation because this is how the width is always used (we add 2 frame padding to it), but we could move that responsibility to the widget as well. - ImGuiState& g = *GImGui; - float width_to_right_edge = window->Pos.x + ImGui::GetContentRegionMax().x - window->DC.CursorPos.x; - w = ImMax(1.0f, width_to_right_edge + w - g.Style.FramePadding.x * 2.0f); + float width_to_right_edge = GetContentRegionAvail().x; + w = ImMax(1.0f, width_to_right_edge + w); } w = (float)(int)w; return w; } -static void SetFont(ImFont* font) +static void SetCurrentFont(ImFont* font) { - ImGuiState& g = *GImGui; - IM_ASSERT(font && font->IsLoaded()); + ImGuiContext& g = *GImGui; + IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? IM_ASSERT(font->Scale > 0.0f); g.Font = font; g.FontBaseSize = g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale; @@ -3804,49 +4536,67 @@ static void SetFont(ImFont* font) void ImGui::PushFont(ImFont* font) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; if (!font) font = g.IO.Fonts->Fonts[0]; - SetFont(font); + SetCurrentFont(font); g.FontStack.push_back(font); g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID); } void ImGui::PopFont() { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; g.CurrentWindow->DrawList->PopTextureID(); g.FontStack.pop_back(); - SetFont(g.FontStack.empty() ? g.IO.Fonts->Fonts[0] : g.FontStack.back()); + SetCurrentFont(g.FontStack.empty() ? g.IO.Fonts->Fonts[0] : g.FontStack.back()); } void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus) { ImGuiWindow* window = GetCurrentWindow(); - window->DC.AllowKeyboardFocus.push_back(allow_keyboard_focus); + window->DC.AllowKeyboardFocus = allow_keyboard_focus; + window->DC.AllowKeyboardFocusStack.push_back(allow_keyboard_focus); } void ImGui::PopAllowKeyboardFocus() { ImGuiWindow* window = GetCurrentWindow(); - window->DC.AllowKeyboardFocus.pop_back(); + window->DC.AllowKeyboardFocusStack.pop_back(); + window->DC.AllowKeyboardFocus = window->DC.AllowKeyboardFocusStack.empty() ? true : window->DC.AllowKeyboardFocusStack.back(); } -void ImGui::PushTextWrapPos(float wrap_x) +void ImGui::PushButtonRepeat(bool repeat) { ImGuiWindow* window = GetCurrentWindow(); - window->DC.TextWrapPos.push_back(wrap_x); + window->DC.ButtonRepeat = repeat; + window->DC.ButtonRepeatStack.push_back(repeat); +} + +void ImGui::PopButtonRepeat() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.ButtonRepeatStack.pop_back(); + window->DC.ButtonRepeat = window->DC.ButtonRepeatStack.empty() ? false : window->DC.ButtonRepeatStack.back(); +} + +void ImGui::PushTextWrapPos(float wrap_pos_x) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.TextWrapPos = wrap_pos_x; + window->DC.TextWrapPosStack.push_back(wrap_pos_x); } void ImGui::PopTextWrapPos() { ImGuiWindow* window = GetCurrentWindow(); - window->DC.TextWrapPos.pop_back(); + window->DC.TextWrapPosStack.pop_back(); + window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back(); } void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiColMod backup; backup.Col = idx; backup.PreviousValue = g.Style.Colors[idx]; @@ -3856,7 +4606,7 @@ void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col) void ImGui::PopStyleColor(int count) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; while (count > 0) { ImGuiColMod& backup = g.ColorModifiers.back(); @@ -3868,7 +4618,7 @@ void ImGui::PopStyleColor(int count) static float* GetStyleVarFloatAddr(ImGuiStyleVar idx) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; switch (idx) { case ImGuiStyleVar_Alpha: return &g.Style.Alpha; @@ -3883,10 +4633,11 @@ static float* GetStyleVarFloatAddr(ImGuiStyleVar idx) static ImVec2* GetStyleVarVec2Addr(ImGuiStyleVar idx) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; switch (idx) { case ImGuiStyleVar_WindowPadding: return &g.Style.WindowPadding; + case ImGuiStyleVar_WindowMinSize: return &g.Style.WindowMinSize; case ImGuiStyleVar_FramePadding: return &g.Style.FramePadding; case ImGuiStyleVar_ItemSpacing: return &g.Style.ItemSpacing; case ImGuiStyleVar_ItemInnerSpacing: return &g.Style.ItemInnerSpacing; @@ -3896,7 +4647,7 @@ static ImVec2* GetStyleVarVec2Addr(ImGuiStyleVar idx) void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; float* pvar = GetStyleVarFloatAddr(idx); IM_ASSERT(pvar != NULL); // Called function with wrong-type? Variable is not a float. ImGuiStyleMod backup; @@ -3909,7 +4660,7 @@ void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImVec2* pvar = GetStyleVarVec2Addr(idx); IM_ASSERT(pvar != NULL); // Called function with wrong-type? Variable is not a ImVec2. ImGuiStyleMod backup; @@ -3921,7 +4672,7 @@ void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) void ImGui::PopStyleVar(int count) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; while (count > 0) { ImGuiStyleMod& backup = g.StyleModifiers.back(); @@ -3940,8 +4691,10 @@ const char* ImGui::GetStyleColName(ImGuiCol idx) switch (idx) { case ImGuiCol_Text: return "Text"; + case ImGuiCol_TextDisabled: return "TextDisabled"; case ImGuiCol_WindowBg: return "WindowBg"; case ImGuiCol_ChildWindowBg: return "ChildWindowBg"; + case ImGuiCol_PopupBg: return "PopupBg"; case ImGuiCol_Border: return "Border"; case ImGuiCol_BorderShadow: return "BorderShadow"; case ImGuiCol_FrameBg: return "FrameBg"; @@ -3949,6 +4702,8 @@ const char* ImGui::GetStyleColName(ImGuiCol idx) case ImGuiCol_FrameBgActive: return "FrameBgActive"; case ImGuiCol_TitleBg: return "TitleBg"; case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed"; + case ImGuiCol_TitleBgActive: return "TitleBgActive"; + case ImGuiCol_MenuBarBg: return "MenuBarBg"; case ImGuiCol_ScrollbarBg: return "ScrollbarBg"; case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab"; case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered"; @@ -3977,51 +4732,75 @@ const char* ImGui::GetStyleColName(ImGuiCol idx) case ImGuiCol_PlotHistogram: return "PlotHistogram"; case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered"; case ImGuiCol_TextSelectedBg: return "TextSelectedBg"; - case ImGuiCol_TooltipBg: return "TooltipBg"; + case ImGuiCol_ModalWindowDarkening: return "ModalWindowDarkening"; } IM_ASSERT(0); return "Unknown"; } +bool ImGui::IsWindowHovered() +{ + ImGuiContext& g = *GImGui; + return g.HoveredWindow == g.CurrentWindow && IsWindowContentHoverable(g.HoveredRootWindow); +} + bool ImGui::IsWindowFocused() { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - return g.FocusedWindow == window; + ImGuiContext& g = *GImGui; + return g.FocusedWindow == g.CurrentWindow; } bool ImGui::IsRootWindowFocused() { - ImGuiState& g = *GImGui; - ImGuiWindow* root_window = GetCurrentWindow()->RootWindow; - return g.FocusedWindow == root_window; + ImGuiContext& g = *GImGui; + return g.FocusedWindow == g.CurrentWindow->RootWindow; } bool ImGui::IsRootWindowOrAnyChildFocused() { - ImGuiState& g = *GImGui; - ImGuiWindow* root_window = GetCurrentWindow()->RootWindow; - return g.FocusedWindow && g.FocusedWindow->RootWindow == root_window; + ImGuiContext& g = *GImGui; + return g.FocusedWindow && g.FocusedWindow->RootWindow == g.CurrentWindow->RootWindow; +} + +bool ImGui::IsRootWindowOrAnyChildHovered() +{ + ImGuiContext& g = *GImGui; + return g.HoveredRootWindow && (g.HoveredRootWindow == g.CurrentWindow->RootWindow) && IsWindowContentHoverable(g.HoveredRootWindow); } float ImGui::GetWindowWidth() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GImGui->CurrentWindow; return window->Size.x; } +float ImGui::GetWindowHeight() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->Size.y; +} + ImVec2 ImGui::GetWindowPos() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; return window->Pos; } +static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y) +{ + window->DC.CursorMaxPos.y += window->Scroll.y; + window->Scroll.y = new_scroll_y; + window->DC.CursorMaxPos.y -= window->Scroll.y; +} + static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowPosAllowFlags & cond) == 0) return; window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); + window->SetWindowPosCenterWanted = false; // Set const ImVec2 old_pos = window->Pos; @@ -4046,7 +4825,7 @@ void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond) ImVec2 ImGui::GetWindowSize() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); return window->Size; } @@ -4058,23 +4837,31 @@ static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond window->SetWindowSizeAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); // Set - if (ImLengthSqr(size) > 0.00001f) + if (size.x > 0.0f) { - window->SizeFull = size; - window->AutoFitFrames = 0; + window->AutoFitFramesX = 0; + window->SizeFull.x = size.x; } else { - // Autofit - window->AutoFitFrames = 2; + window->AutoFitFramesX = 2; + window->AutoFitOnlyGrows = false; + } + if (size.y > 0.0f) + { + window->AutoFitFramesY = 0; + window->SizeFull.y = size.y; + } + else + { + window->AutoFitFramesY = 2; window->AutoFitOnlyGrows = false; } } void ImGui::SetWindowSize(const ImVec2& size, ImGuiSetCond cond) { - ImGuiWindow* window = GetCurrentWindow(); - SetWindowSize(window, size, cond); + SetWindowSize(GImGui->CurrentWindow, size, cond); } void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond cond) @@ -4097,14 +4884,12 @@ static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond void ImGui::SetWindowCollapsed(bool collapsed, ImGuiSetCond cond) { - ImGuiWindow* window = GetCurrentWindow(); - SetWindowCollapsed(window, collapsed, cond); + SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond); } -bool ImGui::GetWindowCollapsed() +bool ImGui::IsWindowCollapsed() { - ImGuiWindow* window = GetCurrentWindow(); - return window->Collapsed; + return GImGui->CurrentWindow->Collapsed; } void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiSetCond cond) @@ -4116,8 +4901,7 @@ void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiSetCond co void ImGui::SetWindowFocus() { - ImGuiWindow* window = GetCurrentWindow(); - FocusWindow(window); + FocusWindow(GImGui->CurrentWindow); } void ImGui::SetWindowFocus(const char* name) @@ -4136,144 +4920,198 @@ void ImGui::SetWindowFocus(const char* name) void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiSetCond cond) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; g.SetNextWindowPosVal = pos; g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always; } +void ImGui::SetNextWindowPosCenter(ImGuiSetCond cond) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowPosVal = ImVec2(-FLT_MAX, -FLT_MAX); + g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always; +} + void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiSetCond cond) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; g.SetNextWindowSizeVal = size; g.SetNextWindowSizeCond = cond ? cond : ImGuiSetCond_Always; } +void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeConstraintCallback custom_callback, void* custom_callback_user_data) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowSizeConstraint = true; + g.SetNextWindowSizeConstraintRect = ImRect(size_min, size_max); + g.SetNextWindowSizeConstraintCallback = custom_callback; + g.SetNextWindowSizeConstraintCallbackUserData = custom_callback_user_data; +} + +void ImGui::SetNextWindowContentSize(const ImVec2& size) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowContentSizeVal = size; + g.SetNextWindowContentSizeCond = ImGuiSetCond_Always; +} + +void ImGui::SetNextWindowContentWidth(float width) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowContentSizeVal = ImVec2(width, g.SetNextWindowContentSizeCond ? g.SetNextWindowContentSizeVal.y : 0.0f); + g.SetNextWindowContentSizeCond = ImGuiSetCond_Always; +} + void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiSetCond cond) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; g.SetNextWindowCollapsedVal = collapsed; g.SetNextWindowCollapsedCond = cond ? cond : ImGuiSetCond_Always; } void ImGui::SetNextWindowFocus() { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; g.SetNextWindowFocus = true; } +// In window space (not screen space!) ImVec2 ImGui::GetContentRegionMax() { - ImGuiWindow* window = GetCurrentWindow(); - ImVec2 window_padding = window->WindowPadding(); - ImVec2 mx = window->Size - window_padding; + ImGuiWindow* window = GetCurrentWindowRead(); + ImVec2 mx = window->ContentsRegionRect.Max; if (window->DC.ColumnsCount != 1) - { - mx.x = ImGui::GetColumnOffset(window->DC.ColumnsCurrent + 1); - mx.x -= window_padding.x; - } - else - { - if (window->ScrollbarY) - mx.x -= GImGui->Style.ScrollbarWidth; - } + mx.x = GetColumnOffset(window->DC.ColumnsCurrent + 1) - window->WindowPadding.x; return mx; } +ImVec2 ImGui::GetContentRegionAvail() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return GetContentRegionMax() - (window->DC.CursorPos - window->Pos); +} + +float ImGui::GetContentRegionAvailWidth() +{ + return GetContentRegionAvail().x; +} + +// In window space (not screen space!) ImVec2 ImGui::GetWindowContentRegionMin() { - ImGuiWindow* window = GetCurrentWindow(); - return ImVec2(0, window->TitleBarHeight()) + window->WindowPadding(); + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ContentsRegionRect.Min; } ImVec2 ImGui::GetWindowContentRegionMax() { - ImGuiWindow* window = GetCurrentWindow(); - ImVec2 m = window->Size - window->WindowPadding(); - if (window->ScrollbarY) - m.x -= GImGui->Style.ScrollbarWidth; - return m; + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ContentsRegionRect.Max; +} + +float ImGui::GetWindowContentRegionWidth() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ContentsRegionRect.Max.x - window->ContentsRegionRect.Min.x; } float ImGui::GetTextLineHeight() { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; return g.FontSize; } float ImGui::GetTextLineHeightWithSpacing() { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; return g.FontSize + g.Style.ItemSpacing.y; } +float ImGui::GetItemsLineHeightWithSpacing() +{ + ImGuiContext& g = *GImGui; + return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y; +} + ImDrawList* ImGui::GetWindowDrawList() { ImGuiWindow* window = GetCurrentWindow(); return window->DrawList; } -ImFont* ImGui::GetWindowFont() +ImFont* ImGui::GetFont() { - ImGuiState& g = *GImGui; - return g.Font; + return GImGui->Font; } -float ImGui::GetWindowFontSize() +float ImGui::GetFontSize() { - ImGuiState& g = *GImGui; - return g.FontSize; + return GImGui->FontSize; +} + +ImVec2 ImGui::GetFontTexUvWhitePixel() +{ + return GImGui->FontTexUvWhitePixel; } void ImGui::SetWindowFontScale(float scale) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->FontWindowScale = scale; g.FontSize = window->CalcFontSize(); } -// NB: internally we store CursorPos in absolute screen coordinates because it is more convenient. -// Conversion happens as we pass the value to user, but it makes our naming convention dodgy. May want to rename 'DC.CursorPos'. +// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient. +// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'. ImVec2 ImGui::GetCursorPos() { - ImGuiWindow* window = GetCurrentWindow(); - return window->DC.CursorPos - window->Pos; + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorPos - window->Pos + window->Scroll; } float ImGui::GetCursorPosX() { - return ImGui::GetCursorPos().x; + ImGuiWindow* window = GetCurrentWindow(); + return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x; } float ImGui::GetCursorPosY() { - return ImGui::GetCursorPos().y; + ImGuiWindow* window = GetCurrentWindow(); + return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y; } -void ImGui::SetCursorPos(const ImVec2& pos) +void ImGui::SetCursorPos(const ImVec2& local_pos) { ImGuiWindow* window = GetCurrentWindow(); - window->DC.CursorPos = window->Pos + pos; + window->DC.CursorPos = window->Pos - window->Scroll + local_pos; window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); } void ImGui::SetCursorPosX(float x) { ImGuiWindow* window = GetCurrentWindow(); - window->DC.CursorPos.x = window->Pos.x + x; + window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x; window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x); } void ImGui::SetCursorPosY(float y) { ImGuiWindow* window = GetCurrentWindow(); - window->DC.CursorPos.y = window->Pos.y + y; + window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y; window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); } +ImVec2 ImGui::GetCursorStartPos() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorStartPos - window->Pos; +} + ImVec2 ImGui::GetCursorScreenPos() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos; } @@ -4283,29 +5121,66 @@ void ImGui::SetCursorScreenPos(const ImVec2& screen_pos) window->DC.CursorPos = screen_pos; } -float ImGui::GetScrollPosY() +float ImGui::GetScrollX() { - ImGuiWindow* window = GetCurrentWindow(); - return window->ScrollY; + return GImGui->CurrentWindow->Scroll.x; +} + +float ImGui::GetScrollY() +{ + return GImGui->CurrentWindow->Scroll.y; +} + +float ImGui::GetScrollMaxX() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->SizeContents.x - window->SizeFull.x - window->ScrollbarSizes.x; } float ImGui::GetScrollMaxY() { - ImGuiWindow* window = GetCurrentWindow(); - return window->SizeContents.y - window->SizeFull.y; + ImGuiWindow* window = GetCurrentWindowRead(); + return window->SizeContents.y - window->SizeFull.y - window->ScrollbarSizes.y; } -void ImGui::SetScrollPosHere() +void ImGui::SetScrollX(float scroll_x) { ImGuiWindow* window = GetCurrentWindow(); - window->NextScrollY = (window->DC.CursorPos.y + window->ScrollY) - (window->Pos.y + window->SizeFull.y * 0.5f) - (window->TitleBarHeight() + window->WindowPadding().y); + window->ScrollTarget.x = scroll_x; + window->ScrollTargetCenterRatio.x = 0.0f; +} + +void ImGui::SetScrollY(float scroll_y) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->ScrollTarget.y = scroll_y + window->TitleBarHeight(); // title bar height canceled out when using ScrollTargetRelY + window->ScrollTargetCenterRatio.y = 0.0f; +} + +void ImGui::SetScrollFromPosY(float pos_y, float center_y_ratio) +{ + // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size + ImGuiWindow* window = GetCurrentWindow(); + IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f); + window->ScrollTarget.y = (float)(int)(pos_y + window->Scroll.y); + if (center_y_ratio <= 0.0f && window->ScrollTarget.y <= window->WindowPadding.y) // Minor hack to make "scroll to top" take account of WindowPadding, else it would scroll to (WindowPadding.y - ItemSpacing.y) + window->ScrollTarget.y = 0.0f; + window->ScrollTargetCenterRatio.y = center_y_ratio; +} + +// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item. +void ImGui::SetScrollHere(float center_y_ratio) +{ + ImGuiWindow* window = GetCurrentWindow(); + float target_y = window->DC.CursorPosPrevLine.y + (window->DC.PrevLineHeight * center_y_ratio) + (GImGui->Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line. + SetScrollFromPosY(target_y - window->Pos.y, center_y_ratio); } void ImGui::SetKeyboardFocusHere(int offset) { ImGuiWindow* window = GetCurrentWindow(); window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset; - window->FocusIdxTabRequestNext = IM_INT_MAX; + window->FocusIdxTabRequestNext = INT_MAX; } void ImGui::SetStateStorage(ImGuiStorage* tree) @@ -4316,17 +5191,17 @@ void ImGui::SetStateStorage(ImGuiStorage* tree) ImGuiStorage* ImGui::GetStateStorage() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.StateStorage; } void ImGui::TextV(const char* fmt, va_list args) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; + ImGuiContext& g = *GImGui; const char* text_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); TextUnformatted(g.TempBuffer, text_end); } @@ -4341,9 +5216,9 @@ void ImGui::Text(const char* fmt, ...) void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args) { - ImGui::PushStyleColor(ImGuiCol_Text, col); + PushStyleColor(ImGuiCol_Text, col); TextV(fmt, args); - ImGui::PopStyleColor(); + PopStyleColor(); } void ImGui::TextColored(const ImVec4& col, const char* fmt, ...) @@ -4354,11 +5229,26 @@ void ImGui::TextColored(const ImVec4& col, const char* fmt, ...) va_end(args); } +void ImGui::TextDisabledV(const char* fmt, va_list args) +{ + PushStyleColor(ImGuiCol_Text, GImGui->Style.Colors[ImGuiCol_TextDisabled]); + TextV(fmt, args); + PopStyleColor(); +} + +void ImGui::TextDisabled(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextDisabledV(fmt, args); + va_end(args); +} + void ImGui::TextWrappedV(const char* fmt, va_list args) { - ImGui::PushTextWrapPos(0.0f); + PushTextWrapPos(0.0f); TextV(fmt, args); - ImGui::PopTextWrapPos(); + PopTextWrapPos(); } void ImGui::TextWrapped(const char* fmt, ...) @@ -4371,44 +5261,46 @@ void ImGui::TextWrapped(const char* fmt, ...) void ImGui::TextUnformatted(const char* text, const char* text_end) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; + ImGuiContext& g = *GImGui; IM_ASSERT(text != NULL); const char* text_begin = text; if (text_end == NULL) text_end = text + strlen(text); // FIXME-OPT - const float wrap_pos_x = window->DC.TextWrapPos.back(); + const float wrap_pos_x = window->DC.TextWrapPos; const bool wrap_enabled = wrap_pos_x >= 0.0f; if (text_end - text > 2000 && !wrap_enabled) { // Long text! // Perform manual coarse clipping to optimize for long multi-line text - // From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled. + // From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled. // We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line. const char* line = text; - const float line_height = ImGui::GetTextLineHeight(); + const float line_height = GetTextLineHeight(); const ImVec2 text_pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrentLineTextBaseOffset); - const ImVec4 clip_rect = window->ClipRectStack.back(); + const ImRect clip_rect = window->ClipRect; ImVec2 text_size(0,0); - if (text_pos.y <= clip_rect.w) + if (text_pos.y <= clip_rect.Max.y) { ImVec2 pos = text_pos; // Lines to skip (can't skip when logging text) if (!g.LogEnabled) { - int lines_skippable = (int)((clip_rect.y - text_pos.y) / line_height) - 1; + int lines_skippable = (int)((clip_rect.Min.y - text_pos.y) / line_height); if (lines_skippable > 0) { int lines_skipped = 0; - while (line < text_end && lines_skipped <= lines_skippable) + while (line < text_end && lines_skipped < lines_skippable) { const char* line_end = strchr(line, '\n'); + if (!line_end) + line_end = text_end; line = line_end + 1; lines_skipped++; } @@ -4419,7 +5311,7 @@ void ImGui::TextUnformatted(const char* text, const char* text_end) // Lines to render if (line < text_end) { - ImRect line_rect(pos, pos + ImVec2(ImGui::GetWindowWidth(), line_height)); + ImRect line_rect(pos, pos + ImVec2(GetWindowWidth(), line_height)); while (line < text_end) { const char* line_end = strchr(line, '\n'); @@ -4467,7 +5359,7 @@ void ImGui::TextUnformatted(const char* text, const char* text_end) text_pos.y += window->DC.CurrentLineTextBaseOffset; ImRect bb(text_pos, text_pos + text_size); - ItemSize(bb.GetSize()); + ItemSize(text_size); if (!ItemAdd(bb, NULL)) return; @@ -4478,40 +5370,40 @@ void ImGui::TextUnformatted(const char* text, const char* text_end) void ImGui::AlignFirstTextHeightToWidgets() { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; // Declare a dummy item size to that upcoming items that are smaller will center-align on the newly expanded line height. + ImGuiContext& g = *GImGui; ItemSize(ImVec2(0, g.FontSize + g.Style.FramePadding.y*2), g.Style.FramePadding.y); - ImGui::SameLine(0, 0); + SameLine(0, 0); } // Add a label+text combo aligned to other label+value widgets void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - const float w = ImGui::CalcItemWidth(); - - const char* value_text_begin = &g.TempBuffer[0]; - const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + style.FramePadding.x*2, label_size.y + style.FramePadding.y*2)); - const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + style.FramePadding.x*2 + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y*2) + label_size); + const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2)); + const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y*2) + label_size); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, NULL)) return; // Render - RenderTextClipped(ImVec2(value_bb.Min.x, value_bb.Min.y + style.FramePadding.y), value_text_begin, value_text_end, NULL, value_bb.Max); - RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label); + const char* value_text_begin = &g.TempBuffer[0]; + const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImGuiAlign_VCenter); + if (label_size.x > 0.0f) + RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label); } void ImGui::LabelText(const char* label, const char* fmt, ...) @@ -4525,8 +5417,8 @@ void ImGui::LabelText(const char* label, const char* fmt, ...) static inline bool IsWindowContentHoverable(ImGuiWindow* window) { // An active popup disable hovering on other windows (apart from its own children) - ImGuiState& g = *GImGui; - if (ImGuiWindow* focused_window = g.FocusedWindow) + ImGuiContext& g = *GImGui; + if (ImGuiWindow* focused_window = g.FocusedWindow) if (ImGuiWindow* focused_root_window = focused_window->RootWindow) if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) != 0 && focused_root_window->WasActive && focused_root_window != window->RootWindow) return false; @@ -4534,49 +5426,57 @@ static inline bool IsWindowContentHoverable(ImGuiWindow* window) return true; } -static bool IsHovered(const ImRect& bb, ImGuiID id, bool flatten_childs = false) +bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags) { - ImGuiState& g = *GImGui; - if (g.HoveredId == 0) - { - ImGuiWindow* window = GetCurrentWindow(); - if (g.HoveredWindow == window || (flatten_childs && g.HoveredRootWindow == window->RootWindow)) - if ((g.ActiveId == 0 || g.ActiveId == id || g.ActiveIdIsFocusedOnly) && IsMouseHoveringRect(bb)) - if (IsWindowContentHoverable(g.HoveredRootWindow)) - return true; - } - return false; -} - -static bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, bool allow_key_modifiers, ImGuiButtonFlags flags) -{ - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); + if (flags & ImGuiButtonFlags_Disabled) + { + if (out_hovered) *out_hovered = false; + if (out_held) *out_held = false; + if (g.ActiveId == id) SetActiveID(0); + return false; + } + + if ((flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick)) == 0) + flags |= ImGuiButtonFlags_PressedOnClickRelease; + bool pressed = false; - const bool hovered = IsHovered(bb, id, (flags & ImGuiButtonFlags_FlattenChilds) != 0); + bool hovered = IsHovered(bb, id, (flags & ImGuiButtonFlags_FlattenChilds) != 0); if (hovered) { - g.HoveredId = id; - if (allow_key_modifiers || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt)) + SetHoveredID(id); + if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt)) { - if (g.IO.MouseClicked[0]) + // | CLICKING | HOLDING with ImGuiButtonFlags_Repeat + // PressedOnClickRelease | * | .. (NOT on release) <-- MOST COMMON! (*) only if both click/release were over bounds + // PressedOnClick | | .. + // PressedOnRelease | | .. (NOT on release) + // PressedOnDoubleClick | | .. + if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0]) { - if (flags & ImGuiButtonFlags_PressedOnClick) - { - pressed = true; - SetActiveId(0); - } - else - { - SetActiveId(id); - } + SetActiveID(id, window); // Hold on ID FocusWindow(window); + g.ActiveIdClickOffset = g.IO.MousePos - bb.Min; } - else if ((flags & ImGuiButtonFlags_Repeat) && g.ActiveId == id && ImGui::IsMouseClicked(0, true)) + if (((flags & ImGuiButtonFlags_PressedOnClick) && g.IO.MouseClicked[0]) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[0])) { pressed = true; + SetActiveID(0); + FocusWindow(window); } + if ((flags & ImGuiButtonFlags_PressedOnRelease) && g.IO.MouseReleased[0]) + { + if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps + pressed = true; + SetActiveID(0); + } + + // 'Repeat' mode acts when held regardless of _PressedOn flags (see table above). + // Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings. + if ((flags & ImGuiButtonFlags_Repeat) && g.ActiveId == id && g.IO.MouseDownDuration[0] > 0.0f && IsMouseClicked(0, true)) + pressed = true; } } @@ -4589,125 +5489,119 @@ static bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool } else { - if (hovered) - pressed = true; - SetActiveId(0); + if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease)) + if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps + pressed = true; + SetActiveID(0); } } + // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match. This allows using patterns where a later submitted widget overlaps a previous one. + if (hovered && (flags & ImGuiButtonFlags_AllowOverlapMode) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0)) + hovered = pressed = held = false; + if (out_hovered) *out_hovered = hovered; if (out_held) *out_held = held; return pressed; } -bool ImGui::Button(const char* label, const ImVec2& size_arg, bool repeat_when_held) +bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImVec2 size(size_arg.x != 0.0f ? size_arg.x : (label_size.x + style.FramePadding.x*2), size_arg.y != 0.0f ? size_arg.y : (label_size.y + style.FramePadding.y*2)); - const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + ImVec2 pos = window->DC.CursorPos; + if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrentLineTextBaseOffset) + pos.y += window->DC.CurrentLineTextBaseOffset - style.FramePadding.y; + ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f); + + const ImRect bb(pos, pos + size); ItemSize(bb, style.FramePadding.y); if (!ItemAdd(bb, &id)) return false; + if (window->DC.ButtonRepeat) flags |= ImGuiButtonFlags_Repeat; bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held, true, repeat_when_held ? ImGuiButtonFlags_Repeat : 0); + bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); // Render - const ImU32 col = window->Color((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); + RenderTextClipped(bb.Min, bb.Max, label, NULL, &label_size, ImGuiAlign_Center | ImGuiAlign_VCenter); - const ImVec2 off = ImVec2(ImMax(0.0f, size.x - label_size.x) * 0.5f, ImMax(0.0f, size.y - label_size.y) * 0.5f); // Center (only applies if we explicitly gave a size bigger than the text size, which isn't the common path) - RenderTextClipped(bb.Min + off, label, NULL, &label_size, bb.Max); // Render clip (only applies if we explicitly gave a size smaller than the text size, which isn't the commmon path) + // Automatically close popups + //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) + // CloseCurrentPopup(); return pressed; } -// Small buttons fits within text without additional spacing. +bool ImGui::Button(const char* label, const ImVec2& size_arg) +{ + return ButtonEx(label, size_arg, 0); +} + +// Small buttons fits within text without additional vertical spacing. bool ImGui::SmallButton(const char* label) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - if (window->SkipItems) - return false; - - const ImGuiStyle& style = g.Style; - const ImGuiID id = window->GetID(label); - const ImVec2 label_size = CalcTextSize(label, NULL, true); - - ImVec2 text_pos = window->DC.CursorPos; - text_pos.y += window->DC.CurrentLineTextBaseOffset; - ImRect bb(text_pos, text_pos + label_size + ImVec2(style.FramePadding.x*2,0)); - ItemSize(bb); - if (!ItemAdd(bb, &id)) - return false; - - bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held, true); - - // Render - const ImU32 col = window->Color((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); - RenderFrame(bb.Min, bb.Max, col); - RenderText(bb.Min + ImVec2(style.FramePadding.x,0), label); - + ImGuiContext& g = *GImGui; + float backup_padding_y = g.Style.FramePadding.y; + g.Style.FramePadding.y = 0.0f; + bool pressed = ButtonEx(label, ImVec2(0,0), ImGuiButtonFlags_AlignTextBaseLine); + g.Style.FramePadding.y = backup_padding_y; return pressed; } // Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack. // Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id) -bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size) +bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiID id = window->GetID(str_id); + ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); ItemSize(bb); if (!ItemAdd(bb, &id)) return false; bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held, true); + bool pressed = ButtonBehavior(bb, id, &hovered, &held); return pressed; } // Upper-right button to close a window. -static bool CloseWindowButton(bool* p_opened) +bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius) { ImGuiWindow* window = GetCurrentWindow(); - const ImGuiID id = window->GetID("#CLOSE"); - const float size = window->TitleBarHeight() - 4.0f; - const ImRect bb(window->Rect().GetTR() + ImVec2(-3.0f-size,2.0f), window->Rect().GetTR() + ImVec2(-3.0f,2.0f+size)); + const ImRect bb(pos - ImVec2(radius,radius), pos + ImVec2(radius,radius)); bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held, true); + bool pressed = ButtonBehavior(bb, id, &hovered, &held); // Render - const ImU32 col = window->Color((held && hovered) ? ImGuiCol_CloseButtonActive : hovered ? ImGuiCol_CloseButtonHovered : ImGuiCol_CloseButton); + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_CloseButtonActive : hovered ? ImGuiCol_CloseButtonHovered : ImGuiCol_CloseButton); const ImVec2 center = bb.GetCenter(); - window->DrawList->AddCircleFilled(center, ImMax(2.0f,size*0.5f), col, 16); + window->DrawList->AddCircleFilled(center, ImMax(2.0f, radius), col, 12); - const float cross_extent = (size * 0.5f * 0.7071f) - 1.0f; + const float cross_extent = (radius * 0.7071f) - 1.0f; if (hovered) { - window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), window->Color(ImGuiCol_Text)); - window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), window->Color(ImGuiCol_Text)); + window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), GetColorU32(ImGuiCol_Text)); + window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), GetColorU32(ImGuiCol_Text)); } - if (p_opened != NULL && pressed) - *p_opened = !*p_opened; - return pressed; } @@ -4726,12 +5620,12 @@ void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& if (border_col.w > 0.0f) { - window->DrawList->AddRect(bb.Min, bb.Max, window->Color(border_col), 0.0f); - window->DrawList->AddImage(user_texture_id, bb.Min+ImVec2(1,1), bb.Max-ImVec2(1,1), uv0, uv1, window->Color(tint_col)); + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f); + window->DrawList->AddImage(user_texture_id, bb.Min+ImVec2(1,1), bb.Max-ImVec2(1,1), uv0, uv1, GetColorU32(tint_col)); } else { - window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, window->Color(tint_col)); + window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, GetColorU32(tint_col)); } } @@ -4741,36 +5635,35 @@ void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& // The color used are the button colors. bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; // Default to using texture ID as ID. User can still push string/integer prefixes. - // We could hash the size/uv to create a unique ID but that would prevent the user from animating buttons. - ImGui::PushID((void *)user_texture_id); + // We could hash the size/uv to create a unique ID but that would prevent the user from animating UV. + PushID((void *)user_texture_id); const ImGuiID id = window->GetID("#image"); - ImGui::PopID(); + PopID(); const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding; const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding*2); - const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size); + const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size); ItemSize(bb); if (!ItemAdd(bb, &id)) return false; bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held, true); + bool pressed = ButtonBehavior(bb, id, &hovered, &held); // Render - const ImU32 col = window->Color((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); - if (padding.x > 0.0f || padding.y > 0.0f) - RenderFrame(bb.Min, bb.Max, col); + const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding)); if (bg_col.w > 0.0f) - window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, window->Color(bg_col)); - window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, window->Color(tint_col)); + window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col)); + window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col)); return pressed; } @@ -4778,10 +5671,10 @@ bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const I // Start logging ImGui output to TTY void ImGui::LogToTTY(int max_depth) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); + ImGuiContext& g = *GImGui; if (g.LogEnabled) return; + ImGuiWindow* window = GetCurrentWindowRead(); g.LogEnabled = true; g.LogFile = stdout; @@ -4793,10 +5686,11 @@ void ImGui::LogToTTY(int max_depth) // Start logging ImGui output to given file void ImGui::LogToFile(int max_depth, const char* filename) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); + ImGuiContext& g = *GImGui; if (g.LogEnabled) return; + ImGuiWindow* window = GetCurrentWindowRead(); + if (!filename) { filename = g.IO.LogFilename; @@ -4819,10 +5713,10 @@ void ImGui::LogToFile(int max_depth, const char* filename) // Start logging ImGui output to clipboard void ImGui::LogToClipboard(int max_depth) { - ImGuiWindow* window = GetCurrentWindow(); - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; if (g.LogEnabled) return; + ImGuiWindow* window = GetCurrentWindowRead(); g.LogEnabled = true; g.LogFile = NULL; @@ -4833,11 +5727,11 @@ void ImGui::LogToClipboard(int max_depth) void ImGui::LogFinish() { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; if (!g.LogEnabled) return; - ImGui::LogText(STR_NEWLINE); + LogText(IM_NEWLINE); g.LogEnabled = false; if (g.LogFile != NULL) { @@ -4858,22 +5752,18 @@ void ImGui::LogFinish() // Helper to display logging buttons void ImGui::LogButtons() { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; - ImGui::PushID("LogButtons"); - const bool log_to_tty = ImGui::Button("Log To TTY"); - ImGui::SameLine(); - const bool log_to_file = ImGui::Button("Log To File"); - ImGui::SameLine(); - const bool log_to_clipboard = ImGui::Button("Log To Clipboard"); - ImGui::SameLine(); - - ImGui::PushItemWidth(80.0f); - ImGui::PushAllowKeyboardFocus(false); - ImGui::SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL); - ImGui::PopAllowKeyboardFocus(); - ImGui::PopItemWidth(); - ImGui::PopID(); + PushID("LogButtons"); + const bool log_to_tty = Button("Log To TTY"); SameLine(); + const bool log_to_file = Button("Log To File"); SameLine(); + const bool log_to_clipboard = Button("Log To Clipboard"); SameLine(); + PushItemWidth(80.0f); + PushAllowKeyboardFocus(false); + SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL); + PopAllowKeyboardFocus(); + PopItemWidth(); + PopID(); // Start logging at the end of the function so that the buttons don't appear in the log if (log_to_tty) @@ -4884,31 +5774,23 @@ void ImGui::LogButtons() LogToClipboard(g.LogAutoExpandMaxDepth); } -bool ImGui::CollapsingHeader(const char* label, const char* str_id, bool display_frame, bool default_open) +bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - if (window->SkipItems) - return false; - - const ImGuiStyle& style = g.Style; - - IM_ASSERT(str_id != NULL || label != NULL); - if (str_id == NULL) - str_id = label; - if (label == NULL) - label = str_id; - const ImGuiID id = window->GetID(str_id); + if (flags & ImGuiTreeNodeFlags_Leaf) + return true; // We only write to the tree storage if the user clicks (or explicitely use SetNextTreeNode*** functions) + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; ImGuiStorage* storage = window->DC.StateStorage; - bool opened; - if (g.SetNextTreeNodeOpenedCond != 0) + + bool is_open; + if (g.SetNextTreeNodeOpenCond != 0) { - if (g.SetNextTreeNodeOpenedCond & ImGuiSetCond_Always) + if (g.SetNextTreeNodeOpenCond & ImGuiSetCond_Always) { - opened = g.SetNextTreeNodeOpenedVal; - storage->SetInt(id, opened); + is_open = g.SetNextTreeNodeOpenVal; + storage->SetInt(id, is_open); } else { @@ -4916,217 +5798,274 @@ bool ImGui::CollapsingHeader(const char* label, const char* str_id, bool display const int stored_value = storage->GetInt(id, -1); if (stored_value == -1) { - opened = g.SetNextTreeNodeOpenedVal; - storage->SetInt(id, opened); + is_open = g.SetNextTreeNodeOpenVal; + storage->SetInt(id, is_open); } else { - opened = stored_value != 0; + is_open = stored_value != 0; } } - g.SetNextTreeNodeOpenedCond = 0; + g.SetNextTreeNodeOpenCond = 0; } else { - opened = storage->GetInt(id, default_open) != 0; + is_open = storage->GetInt(id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0; } - // Framed header expand a little outside the default padding - const ImVec2 window_padding = window->WindowPadding(); - const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImVec2 pos_min = window->DC.CursorPos; - const ImVec2 pos_max = window->Pos + GetContentRegionMax(); - ImRect bb = ImRect(pos_min, ImVec2(pos_max.x, pos_min.y + label_size.y)); + // When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior). + // NB- If we are above max depth we still allow manually opened nodes to be logged. + if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && window->DC.TreeDepth < g.LogAutoExpandMaxDepth) + is_open = true; + + return is_open; +} + +bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0; + const ImVec2 padding = display_frame ? style.FramePadding : ImVec2(style.FramePadding.x, 0.0f); + + if (!label_end) + label_end = FindRenderedTextEnd(label); + const ImVec2 label_size = CalcTextSize(label, label_end, false); + + // We vertically grow up to current line height up the typical widget height. + const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset - padding.y); // Latch before ItemSize changes it + const float frame_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2); + ImRect bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height)); if (display_frame) { - bb.Min.x -= window_padding.x*0.5f - 1; - bb.Max.x += window_padding.x*0.5f - 1; - bb.Max.y += style.FramePadding.y * 2; + // Framed header expand a little outside the default padding + bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1; + bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1; } - // FIXME: we don't provide our width so that it doesn't get feed back into AutoFit. Should manage that better so we can still hover without extending ContentsSize - const ImRect text_bb(bb.Min, bb.Min + ImVec2(g.FontSize + style.FramePadding.x*2*2,0) + label_size); - ItemSize(ImVec2(text_bb.GetSize().x, bb.GetSize().y), display_frame ? style.FramePadding.y : 0.0f); + const float text_offset_x = (g.FontSize + (display_frame ? padding.x*3 : padding.x*2)); // Collapser arrow width + Spacing + const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x*2 : 0.0f); // Include collapser + ItemSize(ImVec2(text_width, frame_height), text_base_offset_y); - // When logging is enabled, if automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior). - // NB- If we are above max depth we still allow manually opened nodes to be logged. - if (g.LogEnabled && !display_frame && window->DC.TreeDepth < g.LogAutoExpandMaxDepth) - opened = true; - - if (!ItemAdd(bb, &id)) - return opened; - - bool hovered, held; - bool pressed = ButtonBehavior(display_frame ? bb : text_bb, id, &hovered, &held, false); - if (pressed) + // For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing + // (Ideally we'd want to add a flag for the user to specify we want want the hit test to be done up to the right side of the content or not) + const ImRect interact_bb = display_frame ? bb : ImRect(bb.Min.x, bb.Min.y, bb.Min.x + text_width + style.ItemSpacing.x*2, bb.Max.y); + bool is_open = TreeNodeBehaviorIsOpen(id, flags); + if (!ItemAdd(interact_bb, &id)) { - opened = !opened; - storage->SetInt(id, opened); + if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) + TreePushRawID(id); + return is_open; } + // Flags that affects opening behavior: + // - 0(default) ..................... single-click anywhere to open + // - OpenOnDoubleClick .............. double-click anywhere to open + // - OpenOnArrow .................... single-click on arrow to open + // - OpenOnDoubleClick|OpenOnArrow .. single-click on arrow or double-click anywhere to open + ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers | ((flags & ImGuiTreeNodeFlags_AllowOverlapMode) ? ImGuiButtonFlags_AllowOverlapMode : 0); + if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) + button_flags |= ImGuiButtonFlags_PressedOnDoubleClick | ((flags & ImGuiTreeNodeFlags_OpenOnArrow) ? ImGuiButtonFlags_PressedOnClickRelease : 0); + bool hovered, held, pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags); + if (pressed && !(flags & ImGuiTreeNodeFlags_Leaf)) + { + bool toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)); + if (flags & ImGuiTreeNodeFlags_OpenOnArrow) + toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y)); + if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) + toggled |= g.IO.MouseDoubleClicked[0]; + if (toggled) + { + is_open = !is_open; + window->DC.StateStorage->SetInt(id, is_open); + } + } + if (flags & ImGuiTreeNodeFlags_AllowOverlapMode) + SetItemAllowOverlap(); + // Render - const ImU32 col = window->Color((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + const ImVec2 text_pos = bb.Min + ImVec2(text_offset_x, padding.y + text_base_offset_y); if (display_frame) { // Framed type RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); - RenderCollapseTriangle(bb.Min + style.FramePadding, opened, 1.0f, true); + RenderCollapseTriangle(bb.Min + padding + ImVec2(0.0f, text_base_offset_y), is_open, 1.0f, true); if (g.LogEnabled) { // NB: '##' is normally used to hide text (as a library-wide feature), so we need to specify the text range to make sure the ## aren't stripped out here. const char log_prefix[] = "\n##"; - LogText(bb.Min + style.FramePadding, log_prefix, log_prefix+3); - } - RenderText(bb.Min + style.FramePadding + ImVec2(g.FontSize + style.FramePadding.x*2,0), label); - if (g.LogEnabled) - { const char log_suffix[] = "##"; - LogText(bb.Min + style.FramePadding, log_suffix, log_suffix+2); + LogRenderedText(text_pos, log_prefix, log_prefix+3); + RenderTextClipped(text_pos, bb.Max, label, label_end, &label_size); + LogRenderedText(text_pos, log_suffix+1, log_suffix+3); + } + else + { + RenderTextClipped(text_pos, bb.Max, label, label_end, &label_size); } } else { // Unframed typed for tree nodes - if ((held && hovered) || hovered) + if (hovered || (flags & ImGuiTreeNodeFlags_Selected)) RenderFrame(bb.Min, bb.Max, col, false); - RenderCollapseTriangle(bb.Min + ImVec2(style.FramePadding.x, g.FontSize*0.15f), opened, 0.70f, false); + + if (flags & ImGuiTreeNodeFlags_Bullet) + RenderBullet(bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y)); + else if (!(flags & ImGuiTreeNodeFlags_Leaf)) + RenderCollapseTriangle(bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open, 0.70f, false); if (g.LogEnabled) - LogText(bb.Min, ">"); - RenderText(bb.Min + ImVec2(g.FontSize + style.FramePadding.x*2,0), label); + LogRenderedText(text_pos, ">"); + RenderText(text_pos, label, label_end, false); } - return opened; + if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) + TreePushRawID(id); + return is_open; } -void ImGui::Bullet() +// CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag). +// This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode(). +bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - if (window->SkipItems) - return; - - const ImGuiStyle& style = g.Style; - const float line_height = g.FontSize; - const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(line_height, line_height)); - ItemSize(bb); - if (!ItemAdd(bb, NULL)) - return; - - // Render - const float bullet_size = line_height*0.15f; - window->DrawList->AddCircleFilled(bb.Min + ImVec2(style.FramePadding.x + line_height*0.5f, line_height*0.5f), bullet_size, window->Color(ImGuiCol_Text)); - - // Stay on same line - ImGui::SameLine(0, -1); -} - -// Text with a little bullet aligned to the typical tree node. -void ImGui::BulletTextV(const char* fmt, va_list args) -{ - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - if (window->SkipItems) - return; - - const char* text_begin = g.TempBuffer; - const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); - - const ImGuiStyle& style = g.Style; - const float line_height = g.FontSize; - const ImVec2 label_size = CalcTextSize(text_begin, text_end, true); - const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(line_height + (label_size.x > 0.0f ? (style.FramePadding.x*2) : 0.0f),0) + label_size); // Empty text doesn't add padding - ItemSize(bb); - if (!ItemAdd(bb, NULL)) - return; - - // Render - const float bullet_size = line_height*0.15f; - window->DrawList->AddCircleFilled(bb.Min + ImVec2(style.FramePadding.x + line_height*0.5f, line_height*0.5f), bullet_size, window->Color(ImGuiCol_Text)); - RenderText(bb.Min+ImVec2(g.FontSize + style.FramePadding.x*2,0), text_begin, text_end); -} - -void ImGui::BulletText(const char* fmt, ...) -{ - va_list args; - va_start(args, fmt); - BulletTextV(fmt, args); - va_end(args); -} - -// If returning 'true' the node is open and the user is responsible for calling TreePop -bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args) -{ - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; - ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + return TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen, label); +} - if (!str_id || !str_id[0]) - str_id = fmt; +bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; - ImGui::PushID(str_id); - const bool opened = ImGui::CollapsingHeader(g.TempBuffer, "", false); - ImGui::PopID(); + if (p_open && !*p_open) + return false; - if (opened) - ImGui::TreePush(str_id); + ImGuiID id = window->GetID(label); + bool is_open = TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen | (p_open ? ImGuiTreeNodeFlags_AllowOverlapMode : 0), label); + if (p_open) + { + // Create a small overlapping close button // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc. + ImGuiContext& g = *GImGui; + float button_sz = g.FontSize * 0.5f; + if (CloseButton(window->GetID((void*)(intptr_t)(id+1)), ImVec2(ImMin(window->DC.LastItemRect.Max.x, window->ClipRect.Max.x) - g.Style.FramePadding.x - button_sz, window->DC.LastItemRect.Min.y + g.Style.FramePadding.y + button_sz), button_sz)) + *p_open = false; + } - return opened; + return is_open; +} + +bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + return TreeNodeBehavior(window->GetID(label), flags, label, NULL); +} + +bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + return TreeNodeBehavior(window->GetID(str_id), flags, g.TempBuffer, label_end); +} + +bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + return TreeNodeBehavior(window->GetID(ptr_id), flags, g.TempBuffer, label_end); +} + +bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args) +{ + return TreeNodeExV(str_id, 0, fmt, args); +} + +bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args) +{ + return TreeNodeExV(ptr_id, 0, fmt, args); +} + +bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(str_id, flags, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(ptr_id, flags, fmt, args); + va_end(args); + return is_open; } bool ImGui::TreeNode(const char* str_id, const char* fmt, ...) { va_list args; va_start(args, fmt); - bool s = TreeNodeV(str_id, fmt, args); + bool is_open = TreeNodeExV(str_id, 0, fmt, args); va_end(args); - return s; -} - -// If returning 'true' the node is open and the user is responsible for calling TreePop -bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args) -{ - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - if (window->SkipItems) - return false; - - ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); - - if (!ptr_id) - ptr_id = fmt; - - ImGui::PushID(ptr_id); - const bool opened = ImGui::CollapsingHeader(g.TempBuffer, "", false); - ImGui::PopID(); - - if (opened) - ImGui::TreePush(ptr_id); - - return opened; + return is_open; } bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...) { va_list args; va_start(args, fmt); - bool s = TreeNodeV(ptr_id, fmt, args); + bool is_open = TreeNodeExV(ptr_id, 0, fmt, args); va_end(args); - return s; + return is_open; } -bool ImGui::TreeNode(const char* str_label_id) +bool ImGui::TreeNode(const char* label) { - return TreeNode(str_label_id, "%s", str_label_id); + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + return TreeNodeBehavior(window->GetID(label), 0, label, NULL); } -void ImGui::SetNextTreeNodeOpened(bool opened, ImGuiSetCond cond) +void ImGui::TreeAdvanceToLabelPos() { - ImGuiState& g = *GImGui; - g.SetNextTreeNodeOpenedVal = opened; - g.SetNextTreeNodeOpenedCond = cond ? cond : ImGuiSetCond_Always; + ImGuiContext& g = *GImGui; + g.CurrentWindow->DC.CursorPos.x += GetTreeNodeToLabelSpacing(); +} + +// Horizontal distance preceeding label when using TreeNode() or Bullet() +float ImGui::GetTreeNodeToLabelSpacing() +{ + ImGuiContext& g = *GImGui; + return g.FontSize + (g.Style.FramePadding.x * 2.0f); +} + +void ImGui::SetNextTreeNodeOpen(bool is_open, ImGuiSetCond cond) +{ + ImGuiContext& g = *GImGui; + g.SetNextTreeNodeOpenVal = is_open; + g.SetNextTreeNodeOpenCond = cond ? cond : ImGuiSetCond_Always; } void ImGui::PushID(const char* str_id) @@ -5147,7 +6086,7 @@ void ImGui::PushID(const void* ptr_id) window->IDStack.push_back(window->GetID(ptr_id)); } -void ImGui::PushID(const int int_id) +void ImGui::PushID(int int_id) { const void* ptr_id = (void*)(intptr_t)int_id; ImGuiWindow* window = GetCurrentWindow(); @@ -5162,25 +6101,120 @@ void ImGui::PopID() ImGuiID ImGui::GetID(const char* str_id) { - ImGuiWindow* window = GetCurrentWindow(); - return window->GetID(str_id); + return GImGui->CurrentWindow->GetID(str_id); } ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end) { - ImGuiWindow* window = GetCurrentWindow(); - return window->GetID(str_id_begin, str_id_end); + return GImGui->CurrentWindow->GetID(str_id_begin, str_id_end); } ImGuiID ImGui::GetID(const void* ptr_id) +{ + return GImGui->CurrentWindow->GetID(ptr_id); +} + +void ImGui::Bullet() { ImGuiWindow* window = GetCurrentWindow(); - return window->GetID(ptr_id); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height)); + ItemSize(bb); + if (!ItemAdd(bb, NULL)) + { + SameLine(0, style.FramePadding.x*2); + return; + } + + // Render and stay on same line + RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f)); + SameLine(0, style.FramePadding.x*2); +} + +// Text with a little bullet aligned to the typical tree node. +void ImGui::BulletTextV(const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + const char* text_begin = g.TempBuffer; + const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + const ImVec2 label_size = CalcTextSize(text_begin, text_end, true); + const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it + const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x*2) : 0.0f), ImMax(line_height, label_size.y))); // Empty text doesn't add padding + ItemSize(bb); + if (!ItemAdd(bb, NULL)) + return; + + // Render + RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f)); + RenderText(bb.Min+ImVec2(g.FontSize + style.FramePadding.x*2, text_base_offset_y), text_begin, text_end); +} + +void ImGui::BulletText(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + BulletTextV(fmt, args); + va_end(args); +} + +static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size) +{ + if (data_type == ImGuiDataType_Int) + ImFormatString(buf, buf_size, display_format, *(int*)data_ptr); + else if (data_type == ImGuiDataType_Float) + ImFormatString(buf, buf_size, display_format, *(float*)data_ptr); +} + +static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size) +{ + if (data_type == ImGuiDataType_Int) + { + if (decimal_precision < 0) + ImFormatString(buf, buf_size, "%d", *(int*)data_ptr); + else + ImFormatString(buf, buf_size, "%.*d", decimal_precision, *(int*)data_ptr); + } + else if (data_type == ImGuiDataType_Float) + { + if (decimal_precision < 0) + ImFormatString(buf, buf_size, "%f", *(float*)data_ptr); // Ideally we'd have a minimum decimal precision of 1 to visually denote that it is a float, while hiding non-significant digits? + else + ImFormatString(buf, buf_size, "%.*f", decimal_precision, *(float*)data_ptr); + } +} + +static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2)// Store into value1 +{ + if (data_type == ImGuiDataType_Int) + { + if (op == '+') + *(int*)value1 = *(int*)value1 + *(const int*)value2; + else if (op == '-') + *(int*)value1 = *(int*)value1 - *(const int*)value2; + } + else if (data_type == ImGuiDataType_Float) + { + if (op == '+') + *(float*)value1 = *(float*)value1 + *(const float*)value2; + else if (op == '-') + *(float*)value1 = *(float*)value1 - *(const float*)value2; + } } // User can input math operators (e.g. +100) to edit a numerical values. -// NB: only call right after InputText because we are using its InitialValue storage -static void ApplyNumericalTextInput(const char* buf, float *v) +static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format) { while (ImCharIsSpace(*buf)) buf++; @@ -5199,69 +6233,84 @@ static void ApplyNumericalTextInput(const char* buf, float *v) op = 0; } if (!buf[0]) - return; + return false; - float ref_v = *v; - if (op) - if (sscanf(GImGui->InputTextState.InitialText, "%f", &ref_v) < 1) - return; - - float op_v = 0.0f; - if (sscanf(buf, "%f", &op_v) < 1) - return; - - if (op == '+') - *v = ref_v + op_v; - else if (op == '*') - *v = ref_v * op_v; - else if (op == '/') + if (data_type == ImGuiDataType_Int) { - if (op_v == 0.0f) - return; - *v = ref_v / op_v; + if (!scalar_format) + scalar_format = "%d"; + int* v = (int*)data_ptr; + const int old_v = *v; + int arg0 = *v; + if (op && sscanf(initial_value_buf, scalar_format, &arg0) < 1) + return false; + + // Store operand in a float so we can use fractional value for multipliers (*1.1), but constant always parsed as integer so we can fit big integers (e.g. 2000000003) past float precision + float arg1 = 0.0f; + if (op == '+') { if (sscanf(buf, "%f", &arg1) == 1) *v = (int)(arg0 + arg1); } // Add (use "+-" to subtract) + else if (op == '*') { if (sscanf(buf, "%f", &arg1) == 1) *v = (int)(arg0 * arg1); } // Multiply + else if (op == '/') { if (sscanf(buf, "%f", &arg1) == 1 && arg1 != 0.0f) *v = (int)(arg0 / arg1); }// Divide + else { if (sscanf(buf, scalar_format, &arg0) == 1) *v = arg0; } // Assign constant + return (old_v != *v); } - else - *v = op_v; + else if (data_type == ImGuiDataType_Float) + { + // For floats we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in + scalar_format = "%f"; + float* v = (float*)data_ptr; + const float old_v = *v; + float arg0 = *v; + if (op && sscanf(initial_value_buf, scalar_format, &arg0) < 1) + return false; + + float arg1 = 0.0f; + if (sscanf(buf, scalar_format, &arg1) < 1) + return false; + if (op == '+') { *v = arg0 + arg1; } // Add (use "+-" to subtract) + else if (op == '*') { *v = arg0 * arg1; } // Multiply + else if (op == '/') { if (arg1 != 0.0f) *v = arg0 / arg1; } // Divide + else { *v = arg1; } // Assign constant + return (old_v != *v); + } + + return false; } // Create text input in place of a slider (when CTRL+Clicking on slider) -static bool SliderFloatAsInputText(const char* label, float* v, ImGuiID id, int decimal_precision) +bool ImGui::InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); - char text_buf[64]; - ImFormatString(text_buf, IM_ARRAYSIZE(text_buf), "%.*f", decimal_precision, *v); - - SetActiveId(g.ScalarAsInputTextId); - g.HoveredId = 0; - // Our replacement widget will override the focus ID (registered previously to allow for a TAB focus to happen) - window->FocusItemUnregister(); + SetActiveID(g.ScalarAsInputTextId, window); + SetHoveredID(0); + FocusableItemUnregister(window); - bool value_changed = ImGui::InputText(label, text_buf, IM_ARRAYSIZE(text_buf), ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_AutoSelectAll); + char buf[32]; + DataTypeFormatString(data_type, data_ptr, decimal_precision, buf, IM_ARRAYSIZE(buf)); + bool text_value_changed = InputTextEx(label, buf, IM_ARRAYSIZE(buf), aabb.GetSize(), ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_AutoSelectAll); if (g.ScalarAsInputTextId == 0) { // First frame IM_ASSERT(g.ActiveId == id); // InputText ID expected to match the Slider ID (else we'd need to store them both, which is also possible) g.ScalarAsInputTextId = g.ActiveId; - g.HoveredId = id; + SetHoveredID(id); } else if (g.ActiveId != g.ScalarAsInputTextId) { // Release g.ScalarAsInputTextId = 0; } - if (value_changed) - { - ApplyNumericalTextInput(text_buf, v); - } - return value_changed; + if (text_value_changed) + return DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, NULL); + return false; } // Parse display precision back from the display format string -static inline void ParseFormat(const char* fmt, int& decimal_precision) +int ImGui::ParseFormatPrecision(const char* fmt, int default_precision) { + int precision = default_precision; while ((fmt = strchr(fmt, '%')) != NULL) { fmt++; @@ -5270,52 +6319,54 @@ static inline void ParseFormat(const char* fmt, int& decimal_precision) fmt++; if (*fmt == '.') { - decimal_precision = atoi(fmt + 1); - if (decimal_precision < 0 || decimal_precision > 10) - decimal_precision = 3; + precision = atoi(fmt + 1); + if (precision < 0 || precision > 10) + precision = default_precision; } break; } + return precision; } -static inline float RoundScalar(float value, int decimal_precision) +float ImGui::RoundScalar(float value, int decimal_precision) { // Round past decimal precision - // 0: 1, 1: 0.1, 2: 0.01, etc. // So when our value is 1.99999 with a precision of 0.001 we'll end up rounding to 2.0 // FIXME: Investigate better rounding methods - const float min_step = 1.0f / powf(10.0f, (float)decimal_precision); - const float remainder = fmodf(value, min_step); + static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f }; + float min_step = (decimal_precision >= 0 && decimal_precision < 10) ? min_steps[decimal_precision] : powf(10.0f, (float)-decimal_precision); + bool negative = value < 0.0f; + value = fabsf(value); + float remainder = fmodf(value, min_step); if (remainder <= min_step*0.5f) value -= remainder; else value += (min_step - remainder); - return value; + return negative ? -value : value; } -static bool SliderScalarBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, bool horizontal) +bool ImGui::SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); const ImGuiStyle& style = g.Style; // Draw frame - RenderFrame(frame_bb.Min, frame_bb.Max, window->Color(ImGuiCol_FrameBg), true, style.FrameRounding); + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); const bool is_non_linear = fabsf(power - 1.0f) > 0.0001f; + const bool is_horizontal = (flags & ImGuiSliderFlags_Vertical) == 0; - const float padding = horizontal ? style.FramePadding.x : style.FramePadding.y; - const float slider_sz = horizontal ? (frame_bb.GetWidth() - padding * 2.0f) : (frame_bb.GetHeight() - padding * 2.0f); + const float grab_padding = 2.0f; + const float slider_sz = is_horizontal ? (frame_bb.GetWidth() - grab_padding * 2.0f) : (frame_bb.GetHeight() - grab_padding * 2.0f); float grab_sz; if (decimal_precision > 0) grab_sz = ImMin(style.GrabMinSize, slider_sz); else grab_sz = ImMin(ImMax(1.0f * (slider_sz / (v_max-v_min+1.0f)), style.GrabMinSize), slider_sz); // Integer sliders, if possible have the grab size represent 1 unit const float slider_usable_sz = slider_sz - grab_sz; - const float slider_usable_pos_min = (horizontal ? frame_bb.Min.x : frame_bb.Min.y) + padding + grab_sz*0.5f; - const float slider_usable_pos_max = (horizontal ? frame_bb.Max.x : frame_bb.Max.y) - padding - grab_sz*0.5f; - - bool value_changed = false; + const float slider_usable_pos_min = (is_horizontal ? frame_bb.Min.x : frame_bb.Min.y) + grab_padding + grab_sz*0.5f; + const float slider_usable_pos_max = (is_horizontal ? frame_bb.Max.x : frame_bb.Max.y) - grab_padding - grab_sz*0.5f; // For logarithmic sliders that cross over sign boundary we want the exponential increase to be symmetric around 0.0f float linear_zero_pos = 0.0f; // 0.0->1.0f @@ -5333,13 +6384,14 @@ static bool SliderScalarBehavior(const ImRect& frame_bb, ImGuiID id, float* v, f } // Process clicking on the slider + bool value_changed = false; if (g.ActiveId == id) { if (g.IO.MouseDown[0]) { - const float mouse_abs_pos = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; + const float mouse_abs_pos = is_horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; float normalized_pos = ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f); - if (!horizontal) + if (!is_horizontal) normalized_pos = 1.0f - normalized_pos; float new_value; @@ -5357,7 +6409,7 @@ static bool SliderScalarBehavior(const ImRect& frame_bb, ImGuiID id, float* v, f { // Positive: rescale to the positive range before powering float a; - if (fabsf(linear_zero_pos - 1.0f) > 1.e-6) + if (fabsf(linear_zero_pos - 1.0f) > 1.e-6f) a = (normalized_pos - linear_zero_pos) / (1.0f - linear_zero_pos); else a = normalized_pos; @@ -5373,7 +6425,6 @@ static bool SliderScalarBehavior(const ImRect& frame_bb, ImGuiID id, float* v, f // Round past decimal precision new_value = RoundScalar(new_value, decimal_precision); - if (*v != new_value) { *v = new_value; @@ -5382,7 +6433,7 @@ static bool SliderScalarBehavior(const ImRect& frame_bb, ImGuiID id, float* v, f } else { - SetActiveId(0); + SetActiveID(0); } } @@ -5409,15 +6460,15 @@ static bool SliderScalarBehavior(const ImRect& frame_bb, ImGuiID id, float* v, f } // Draw - if (!horizontal) + if (!is_horizontal) grab_t = 1.0f - grab_t; const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t); ImRect grab_bb; - if (horizontal) - grab_bb = ImRect(ImVec2(grab_pos - grab_sz*0.5f, frame_bb.Min.y + 2.0f), ImVec2(grab_pos + grab_sz*0.5f, frame_bb.Max.y - 2.0f)); + if (is_horizontal) + grab_bb = ImRect(ImVec2(grab_pos - grab_sz*0.5f, frame_bb.Min.y + grab_padding), ImVec2(grab_pos + grab_sz*0.5f, frame_bb.Max.y - grab_padding)); else - grab_bb = ImRect(ImVec2(frame_bb.Min.x + 2.0f, grab_pos - grab_sz*0.5f), ImVec2(frame_bb.Max.x - 2.0f, grab_pos + grab_sz*0.5f)); - window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, window->Color(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab)); + grab_bb = ImRect(ImVec2(frame_bb.Min.x + grab_padding, grab_pos - grab_sz*0.5f), ImVec2(frame_bb.Max.x - grab_padding, grab_pos + grab_sz*0.5f)); + window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding); return value_changed; } @@ -5429,17 +6480,17 @@ static bool SliderScalarBehavior(const ImRect& frame_bb, ImGuiID id, float* v, f // "Gold: %.0f" Gold: 1 bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format, float power) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); - const float w = ImGui::CalcItemWidth(); + const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y) + style.FramePadding*2.0f); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); // NB- we don't call ItemSize() yet because we may turn into a text edit box below @@ -5451,41 +6502,38 @@ bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, c const bool hovered = IsHovered(frame_bb, id); if (hovered) - g.HoveredId = id; + SetHoveredID(id); if (!display_format) display_format = "%.3f"; - int decimal_precision = 3; - ParseFormat(display_format, decimal_precision); + int decimal_precision = ParseFormatPrecision(display_format, 3); // Tabbing or CTRL-clicking on Slider turns it into an input box bool start_text_input = false; - const bool tab_focus_requested = window->FocusItemRegister(g.ActiveId == id); + const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id); if (tab_focus_requested || (hovered && g.IO.MouseClicked[0])) { - SetActiveId(id); + SetActiveID(id, window); FocusWindow(window); - const bool is_ctrl_down = g.IO.KeyCtrl; - if (tab_focus_requested || is_ctrl_down) + if (tab_focus_requested || g.IO.KeyCtrl) { start_text_input = true; g.ScalarAsInputTextId = 0; } } if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) - return SliderFloatAsInputText(label, v, id, decimal_precision); + return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision); ItemSize(total_bb, style.FramePadding.y); // Actual slider behavior + render grab - const bool value_changed = SliderScalarBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision, true); + const bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision); // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. char value_buf[64]; const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); - const ImVec2 value_text_size = CalcTextSize(value_buf, value_buf_end, true); - RenderTextClipped(ImVec2(ImMax(frame_bb.Min.x + style.FramePadding.x, frame_bb.GetCenter().x - value_text_size.x*0.5f), frame_bb.Min.y + style.FramePadding.y), value_buf, value_buf_end, &value_text_size, frame_bb.Max); + RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImGuiAlign_Center|ImGuiAlign_VCenter); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); @@ -5495,11 +6543,11 @@ bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, c bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* display_format, float power) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); @@ -5513,29 +6561,26 @@ bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float const bool hovered = IsHovered(frame_bb, id); if (hovered) - g.HoveredId = id; + SetHoveredID(id); if (!display_format) display_format = "%.3f"; - int decimal_precision = 3; - ParseFormat(display_format, decimal_precision); + int decimal_precision = ParseFormatPrecision(display_format, 3); if (hovered && g.IO.MouseClicked[0]) { - SetActiveId(id); + SetActiveID(id, window); FocusWindow(window); } // Actual slider behavior + render grab - bool value_changed = SliderScalarBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision, false); + bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision, ImGuiSliderFlags_Vertical); // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. // For the vertical slider we allow centered text to overlap the frame padding char value_buf[64]; char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); - const ImVec2 value_text_size = CalcTextSize(value_buf, value_buf_end, true); - RenderTextClipped(ImVec2(ImMax(frame_bb.Min.x, frame_bb.GetCenter().x - value_text_size.x*0.5f), frame_bb.Min.y + style.FramePadding.y), value_buf, value_buf_end, &value_text_size, frame_bb.Max); - + RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImGuiAlign_Center); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); @@ -5544,9 +6589,9 @@ bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max) { - float v_deg = (*v_rad) * 360.0f / (2*PI); - bool value_changed = ImGui::SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, "%.0f deg", 1.0f); - *v_rad = v_deg * (2*PI) / 360.0f; + float v_deg = (*v_rad) * 360.0f / (2*IM_PI); + bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, "%.0f deg", 1.0f); + *v_rad = v_deg * (2*IM_PI) / 360.0f; return value_changed; } @@ -5555,7 +6600,7 @@ bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const cha if (!display_format) display_format = "%.0f"; float v_f = (float)*v; - bool value_changed = ImGui::SliderFloat(label, &v_f, (float)v_min, (float)v_max, display_format, 1.0f); + bool value_changed = SliderFloat(label, &v_f, (float)v_min, (float)v_max, display_format, 1.0f); *v = (int)v_f; return value_changed; } @@ -5565,35 +6610,35 @@ bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, if (!display_format) display_format = "%.0f"; float v_f = (float)*v; - bool value_changed = ImGui::VSliderFloat(label, size, &v_f, (float)v_min, (float)v_max, display_format, 1.0f); + bool value_changed = VSliderFloat(label, size, &v_f, (float)v_min, (float)v_max, display_format, 1.0f); *v = (int)v_f; return value_changed; } // Add multiple sliders on 1 line for compact edition of multiple components -static bool SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power) +bool ImGui::SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; bool value_changed = false; - ImGui::BeginGroup(); - ImGui::PushID(label); + BeginGroup(); + PushID(label); PushMultiItemsWidths(components); for (int i = 0; i < components; i++) { - ImGui::PushID(i); - value_changed |= ImGui::SliderFloat("##v", &v[i], v_min, v_max, display_format, power); - ImGui::SameLine(0, (int)g.Style.ItemInnerSpacing.x); - ImGui::PopID(); - ImGui::PopItemWidth(); + PushID(i); + value_changed |= SliderFloat("##v", &v[i], v_min, v_max, display_format, power); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); } - ImGui::PopID(); + PopID(); - ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); - ImGui::EndGroup(); + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); return value_changed; } @@ -5613,29 +6658,29 @@ bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max return SliderFloatN(label, v, 4, v_min, v_max, display_format, power); } -static bool SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format) +bool ImGui::SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; bool value_changed = false; - ImGui::BeginGroup(); - ImGui::PushID(label); + BeginGroup(); + PushID(label); PushMultiItemsWidths(components); for (int i = 0; i < components; i++) { - ImGui::PushID(i); - value_changed |= ImGui::SliderInt("##v", &v[i], v_min, v_max, display_format); - ImGui::SameLine(0, (int)g.Style.ItemInnerSpacing.x); - ImGui::PopID(); - ImGui::PopItemWidth(); + PushID(i); + value_changed |= SliderInt("##v", &v[i], v_min, v_max, display_format); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); } - ImGui::PopID(); + PopID(); - ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); - ImGui::EndGroup(); + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); return value_changed; } @@ -5655,15 +6700,13 @@ bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const return SliderIntN(label, v, 4, v_min, v_max, display_format); } -// FIXME-WIP: Work in progress. May change API / behavior. -static bool DragScalarBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_speed, float v_min, float v_max, int decimal_precision, float power) +bool ImGui::DragBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_speed, float v_min, float v_max, int decimal_precision, float power) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; // Draw frame - const ImU32 frame_col = window->Color(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); + const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding); bool value_changed = false; @@ -5680,7 +6723,8 @@ static bool DragScalarBehavior(const ImRect& frame_bb, ImGuiID id, float* v, flo g.DragLastMouseDelta = ImVec2(0.f, 0.f); } - const ImVec2 mouse_drag_delta = ImGui::GetMouseDragDelta(0, 1.0f); + float v_cur = g.DragCurrentValue; + const ImVec2 mouse_drag_delta = GetMouseDragDelta(0, 1.0f); if (fabsf(mouse_drag_delta.x - g.DragLastMouseDelta.x) > 0.0f) { float speed = v_speed; @@ -5691,7 +6735,6 @@ static bool DragScalarBehavior(const ImRect& frame_bb, ImGuiID id, float* v, flo if (g.IO.KeyAlt && g.DragSpeedScaleSlow >= 0.0f) speed = speed * g.DragSpeedScaleSlow; - float v_cur = g.DragCurrentValue; float delta = (mouse_drag_delta.x - g.DragLastMouseDelta.x) * speed; if (fabsf(power - 1.0f) > 0.001f) { @@ -5713,38 +6756,38 @@ static bool DragScalarBehavior(const ImRect& frame_bb, ImGuiID id, float* v, flo if (v_min < v_max) v_cur = ImClamp(v_cur, v_min, v_max); g.DragCurrentValue = v_cur; + } - // Round to user desired precision, then apply - v_cur = RoundScalar(v_cur, decimal_precision); - if (*v != v_cur) - { - *v = v_cur; - value_changed = true; - } + // Round to user desired precision, then apply + v_cur = RoundScalar(v_cur, decimal_precision); + if (*v != v_cur) + { + *v = v_cur; + value_changed = true; } } else { - SetActiveId(0); + SetActiveID(0); } } return value_changed; } -bool ImGui::DragFloat(const char* label, float *v, float v_speed, float v_min, float v_max, const char* display_format, float power) +bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* display_format, float power) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); - const float w = ImGui::CalcItemWidth(); + const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y) + style.FramePadding*2.0f); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); @@ -5757,19 +6800,18 @@ bool ImGui::DragFloat(const char* label, float *v, float v_speed, float v_min, f const bool hovered = IsHovered(frame_bb, id); if (hovered) - g.HoveredId = id; + SetHoveredID(id); if (!display_format) display_format = "%.3f"; - int decimal_precision = 3; - ParseFormat(display_format, decimal_precision); + int decimal_precision = ParseFormatPrecision(display_format, 3); // Tabbing or CTRL-clicking on Drag turns it into an input box bool start_text_input = false; - const bool tab_focus_requested = window->FocusItemRegister(g.ActiveId == id); + const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id); if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] | g.IO.MouseDoubleClicked[0]))) { - SetActiveId(id); + SetActiveID(id, window); FocusWindow(window); if (tab_focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0]) @@ -5779,18 +6821,16 @@ bool ImGui::DragFloat(const char* label, float *v, float v_speed, float v_min, f } } if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) - return SliderFloatAsInputText(label, v, id, decimal_precision); - - ItemSize(total_bb, style.FramePadding.y); + return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision); // Actual drag behavior - const bool value_changed = DragScalarBehavior(frame_bb, id, v, v_speed, v_min, v_max, decimal_precision, power); + ItemSize(total_bb, style.FramePadding.y); + const bool value_changed = DragBehavior(frame_bb, id, v, v_speed, v_min, v_max, decimal_precision, power); // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. char value_buf[64]; const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); - const ImVec2 value_text_size = CalcTextSize(value_buf, value_buf_end, true); - RenderTextClipped(ImVec2(ImMax(frame_bb.Min.x + style.FramePadding.x, inner_bb.GetCenter().x - value_text_size.x*0.5f), frame_bb.Min.y + style.FramePadding.y), value_buf, value_buf_end, &value_text_size, frame_bb.Max); + RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImGuiAlign_Center|ImGuiAlign_VCenter); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); @@ -5798,29 +6838,29 @@ bool ImGui::DragFloat(const char* label, float *v, float v_speed, float v_min, f return value_changed; } -static bool DragFloatN(const char* label, float* v, int components, float v_speed, float v_min, float v_max, const char* display_format, float power) +bool ImGui::DragFloatN(const char* label, float* v, int components, float v_speed, float v_min, float v_max, const char* display_format, float power) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; bool value_changed = false; - ImGui::BeginGroup(); - ImGui::PushID(label); + BeginGroup(); + PushID(label); PushMultiItemsWidths(components); for (int i = 0; i < components; i++) { - ImGui::PushID(i); - value_changed |= ImGui::DragFloat("##v", &v[i], v_speed, v_min, v_max, display_format, power); - ImGui::SameLine(0, (int)g.Style.ItemInnerSpacing.x); - ImGui::PopID(); - ImGui::PopItemWidth(); + PushID(i); + value_changed |= DragFloat("##v", &v[i], v_speed, v_min, v_max, display_format, power); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); } - ImGui::PopID(); + PopID(); - ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); - ImGui::EndGroup(); + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); return value_changed; } @@ -5830,50 +6870,75 @@ bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min return DragFloatN(label, v, 2, v_speed, v_min, v_max, display_format, power); } -bool ImGui::DragFloat3(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* display_format, float power) +bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* display_format, float power) { return DragFloatN(label, v, 3, v_speed, v_min, v_max, display_format, power); } -bool ImGui::DragFloat4(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* display_format, float power) +bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* display_format, float power) { return DragFloatN(label, v, 4, v_speed, v_min, v_max, display_format, power); } +bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* display_format, const char* display_format_max, float power) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + PushID(label); + BeginGroup(); + PushMultiItemsWidths(2); + + bool value_changed = DragFloat("##min", v_current_min, v_speed, (v_min >= v_max) ? -FLT_MAX : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), display_format, power); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + value_changed |= DragFloat("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? FLT_MAX : v_max, display_format_max ? display_format_max : display_format, power); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + PopID(); + + return value_changed; +} + // NB: v_speed is float to allow adjusting the drag speed with more precision bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* display_format) { if (!display_format) display_format = "%.0f"; float v_f = (float)*v; - bool value_changed = ImGui::DragFloat(label, &v_f, v_speed, (float)v_min, (float)v_max, display_format); + bool value_changed = DragFloat(label, &v_f, v_speed, (float)v_min, (float)v_max, display_format); *v = (int)v_f; return value_changed; } -static bool DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format) +bool ImGui::DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; bool value_changed = false; - ImGui::BeginGroup(); - ImGui::PushID(label); + BeginGroup(); + PushID(label); PushMultiItemsWidths(components); for (int i = 0; i < components; i++) { - ImGui::PushID(i); - value_changed |= ImGui::DragInt("##v", &v[i], v_speed, v_min, v_max, display_format); - ImGui::SameLine(0, (int)g.Style.ItemInnerSpacing.x); - ImGui::PopID(); - ImGui::PopItemWidth(); + PushID(i); + value_changed |= DragInt("##v", &v[i], v_speed, v_min, v_max, display_format); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); } - ImGui::PopID(); + PopID(); - ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); - ImGui::EndGroup(); + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); return value_changed; } @@ -5893,24 +6958,43 @@ bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int return DragIntN(label, v, 4, v_speed, v_min, v_max, display_format); } -enum ImGuiPlotType +bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* display_format, const char* display_format_max) { - ImGuiPlotType_Lines, - ImGuiPlotType_Histogram -}; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; -static void Plot(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) + ImGuiContext& g = *GImGui; + PushID(label); + BeginGroup(); + PushMultiItemsWidths(2); + + bool value_changed = DragInt("##min", v_current_min, v_speed, (v_min >= v_max) ? INT_MIN : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), display_format); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + value_changed |= DragInt("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? INT_MAX : v_max, display_format_max ? display_format_max : display_format); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + PopID(); + + return value_changed; +} + +void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - const ImVec2 label_size = ImGui::CalcTextSize(label, NULL, true); + const ImVec2 label_size = CalcTextSize(label, NULL, true); if (graph_size.x == 0.0f) - graph_size.x = ImGui::CalcItemWidth() + (style.FramePadding.x * 2); + graph_size.x = CalcItemWidth(); if (graph_size.y == 0.0f) graph_size.y = label_size.y + (style.FramePadding.y * 2); @@ -5938,26 +7022,25 @@ static void Plot(ImGuiPlotType plot_type, const char* label, float (*values_gett scale_max = v_max; } - RenderFrame(frame_bb.Min, frame_bb.Max, window->Color(ImGuiCol_FrameBg), true, style.FrameRounding); + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); - int res_w = ImMin((int)graph_size.x, values_count); - if (plot_type == ImGuiPlotType_Lines) - res_w -= 1; + int res_w = ImMin((int)graph_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); + int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); // Tooltip on hover int v_hovered = -1; - if (IsMouseHoveringRect(inner_bb)) + if (IsHovered(inner_bb, 0)) { const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f); - const int v_idx = (int)(t * (values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0))); + const int v_idx = (int)(t * item_count); IM_ASSERT(v_idx >= 0 && v_idx < values_count); - + const float v0 = values_getter(data, (v_idx + values_offset) % values_count); const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count); if (plot_type == ImGuiPlotType_Lines) - ImGui::SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1); + SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1); else if (plot_type == ImGuiPlotType_Histogram) - ImGui::SetTooltip("%d: %8.4g", v_idx, v0); + SetTooltip("%d: %8.4g", v_idx, v0); v_hovered = v_idx; } @@ -5965,42 +7048,51 @@ static void Plot(ImGuiPlotType plot_type, const char* label, float (*values_gett float v0 = values_getter(data, (0 + values_offset) % values_count); float t0 = 0.0f; - ImVec2 p0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) / (scale_max - scale_min)) ); + ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) / (scale_max - scale_min)) ); // Point in the normalized space of our target rectangle - const ImU32 col_base = window->Color((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram); - const ImU32 col_hovered = window->Color((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered); + const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram); + const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered); for (int n = 0; n < res_w; n++) { const float t1 = t0 + t_step; - const int v_idx = (int)(t0 * values_count); - IM_ASSERT(v_idx >= 0 && v_idx < values_count); - const float v1 = values_getter(data, (v_idx + values_offset + 1) % values_count); - const ImVec2 p1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) / (scale_max - scale_min)) ); + const int v1_idx = (int)(t0 * item_count + 0.5f); + IM_ASSERT(v1_idx >= 0 && v1_idx < values_count); + const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count); + const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) / (scale_max - scale_min)) ); - // NB- Draw calls are merged together by the DrawList system. + // NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU. + ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0); + ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, 1.0f)); if (plot_type == ImGuiPlotType_Lines) - window->DrawList->AddLine(ImLerp(inner_bb.Min, inner_bb.Max, p0), ImLerp(inner_bb.Min, inner_bb.Max, p1), v_hovered == v_idx ? col_hovered : col_base); + { + window->DrawList->AddLine(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base); + } else if (plot_type == ImGuiPlotType_Histogram) - window->DrawList->AddRectFilled(ImLerp(inner_bb.Min, inner_bb.Max, p0), ImLerp(inner_bb.Min, inner_bb.Max, ImVec2(p1.x, 1.0f))+ImVec2(-1,0), v_hovered == v_idx ? col_hovered : col_base); + { + if (pos1.x >= pos0.x + 2.0f) + pos1.x -= 1.0f; + window->DrawList->AddRectFilled(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base); + } t0 = t1; - p0 = p1; + tp0 = tp1; } // Text overlay if (overlay_text) - RenderTextClipped(ImVec2(ImMax(inner_bb.Min.x, inner_bb.GetCenter().x - ImGui::CalcTextSize(overlay_text, NULL, true).x*0.5f), frame_bb.Min.y + style.FramePadding.y), overlay_text, NULL, NULL, frame_bb.Max); + RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImGuiAlign_Center); - RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); } struct ImGuiPlotArrayGetterData { const float* Values; - size_t Stride; + int Stride; - ImGuiPlotArrayGetterData(const float* values, size_t stride) { Values = values; Stride = stride; } + ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; } }; static float Plot_ArrayGetter(void* data, int idx) @@ -6010,35 +7102,71 @@ static float Plot_ArrayGetter(void* data, int idx) return v; } -void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, size_t stride) +void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) { ImGuiPlotArrayGetterData data(values, stride); - Plot(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); + PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } void ImGui::PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { - Plot(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); + PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } -void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, size_t stride) +void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) { ImGuiPlotArrayGetterData data(values, stride); - Plot(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); + PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } void ImGui::PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { - Plot(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); + PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +// size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size +void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + ImVec2 pos = window->DC.CursorPos; + ImRect bb(pos, pos + CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f)); + ItemSize(bb, style.FramePadding.y); + if (!ItemAdd(bb, NULL)) + return; + + // Render + fraction = ImSaturate(fraction); + RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + bb.Reduce(ImVec2(window->BorderSize, window->BorderSize)); + const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y); + RenderFrame(bb.Min, fill_br, GetColorU32(ImGuiCol_PlotHistogram), false, style.FrameRounding); + + // Default displaying the fraction as percentage string, but user can override it + char overlay_buf[32]; + if (!overlay) + { + ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction*100+0.01f); + overlay = overlay_buf; + } + + ImVec2 overlay_size = CalcTextSize(overlay, NULL); + if (overlay_size.x > 0.0f) + RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImGuiAlign_Left|ImGuiAlign_VCenter, &bb.Min, &bb.Max); } bool ImGui::Checkbox(const char* label, bool* v) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); @@ -6048,7 +7176,7 @@ bool ImGui::Checkbox(const char* label, bool* v) ImRect total_bb = check_bb; if (label_size.x > 0) - SameLine(0, (int)style.ItemInnerSpacing.x); + SameLine(0, style.ItemInnerSpacing.x); const ImRect text_bb(window->DC.CursorPos + ImVec2(0,style.FramePadding.y), window->DC.CursorPos + ImVec2(0,style.FramePadding.y) + label_size); if (label_size.x > 0) { @@ -6060,43 +7188,48 @@ bool ImGui::Checkbox(const char* label, bool* v) return false; bool hovered, held; - bool pressed = ButtonBehavior(total_bb, id, &hovered, &held, true); + bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); if (pressed) *v = !(*v); - RenderFrame(check_bb.Min, check_bb.Max, window->Color((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding); + RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding); if (*v) { const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight()); - const float pad = check_sz < 8.0f ? 1.0f : check_sz < 13.0f ? 2.0f : 3.0f; - window->DrawList->AddRectFilled(check_bb.Min+ImVec2(pad,pad), check_bb.Max-ImVec2(pad,pad), window->Color(ImGuiCol_CheckMark), style.FrameRounding); + const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f)); + window->DrawList->AddRectFilled(check_bb.Min+ImVec2(pad,pad), check_bb.Max-ImVec2(pad,pad), GetColorU32(ImGuiCol_CheckMark), style.FrameRounding); } if (g.LogEnabled) - LogText(text_bb.GetTL(), *v ? "[x]" : "[ ]"); - RenderText(text_bb.GetTL(), label); + LogRenderedText(text_bb.GetTL(), *v ? "[x]" : "[ ]"); + if (label_size.x > 0.0f) + RenderText(text_bb.GetTL(), label); return pressed; } bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value) { - bool v = (*flags & flags_value) ? true : false; - bool pressed = ImGui::Checkbox(label, &v); - if (v) - *flags |= flags_value; - else - *flags &= ~flags_value; + bool v = ((*flags & flags_value) == flags_value); + bool pressed = Checkbox(label, &v); + if (pressed) + { + if (v) + *flags |= flags_value; + else + *flags &= ~flags_value; + } + return pressed; } bool ImGui::RadioButton(const char* label, bool active) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); @@ -6106,7 +7239,7 @@ bool ImGui::RadioButton(const char* label, bool active) ImRect total_bb = check_bb; if (label_size.x > 0) - SameLine(0, (int)style.ItemInnerSpacing.x); + SameLine(0, style.ItemInnerSpacing.x); const ImRect text_bb(window->DC.CursorPos + ImVec2(0, style.FramePadding.y), window->DC.CursorPos + ImVec2(0, style.FramePadding.y) + label_size); if (label_size.x > 0) { @@ -6123,32 +7256,33 @@ bool ImGui::RadioButton(const char* label, bool active) const float radius = check_bb.GetHeight() * 0.5f; bool hovered, held; - bool pressed = ButtonBehavior(total_bb, id, &hovered, &held, true); + bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); - window->DrawList->AddCircleFilled(center, radius, window->Color((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16); + window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16); if (active) { const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight()); - const float pad = check_sz < 8.0f ? 1.0f : check_sz < 13.0f ? 2.0f : 3.0f; - window->DrawList->AddCircleFilled(center, radius-pad, window->Color(ImGuiCol_CheckMark), 16); + const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f)); + window->DrawList->AddCircleFilled(center, radius-pad, GetColorU32(ImGuiCol_CheckMark), 16); } if (window->Flags & ImGuiWindowFlags_ShowBorders) { - window->DrawList->AddCircle(center+ImVec2(1,1), radius, window->Color(ImGuiCol_BorderShadow), 16); - window->DrawList->AddCircle(center, radius, window->Color(ImGuiCol_Border), 16); + window->DrawList->AddCircle(center+ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16); + window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16); } if (g.LogEnabled) - LogText(text_bb.GetTL(), active ? "(x)" : "( )"); - RenderText(text_bb.GetTL(), label); + LogRenderedText(text_bb.GetTL(), active ? "(x)" : "( )"); + if (label_size.x > 0.0f) + RenderText(text_bb.GetTL(), label); return pressed; } bool ImGui::RadioButton(const char* label, int* v, int v_button) { - const bool pressed = ImGui::RadioButton(label, *v == v_button); + const bool pressed = RadioButton(label, *v == v_button); if (pressed) { *v = v_button; @@ -6156,54 +7290,127 @@ bool ImGui::RadioButton(const char* label, int* v, int v_button) return pressed; } +static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end) +{ + int line_count = 0; + const char* s = text_begin; + while (char c = *s++) // We are only matching for \n so we can ignore UTF-8 decoding + if (c == '\n') + line_count++; + s--; + if (s[0] != '\n' && s[0] != '\r') + line_count++; + *out_text_end = s; + return line_count; +} + +static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line) +{ + ImFont* font = GImGui->Font; + const float line_height = GImGui->FontSize; + const float scale = line_height / font->FontSize; + + ImVec2 text_size = ImVec2(0,0); + float line_width = 0.0f; + + const ImWchar* s = text_begin; + while (s < text_end) + { + unsigned int c = (unsigned int)(*s++); + if (c == '\n') + { + text_size.x = ImMax(text_size.x, line_width); + text_size.y += line_height; + line_width = 0.0f; + if (stop_on_new_line) + break; + continue; + } + if (c == '\r') + continue; + + const float char_width = font->GetCharAdvance((unsigned short)c) * scale; + line_width += char_width; + } + + if (text_size.x < line_width) + text_size.x = line_width; + + if (out_offset) + *out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n + + if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n + text_size.y += line_height; + + if (remaining) + *remaining = s; + + return text_size; +} + // Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar) -static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return (int)ImStrlenW(obj->Text); } +namespace ImGuiStb +{ + +static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return obj->CurLenW; } static ImWchar STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return obj->Text[idx]; } -static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { (void)line_start_idx; return obj->Font->CalcTextSizeW(obj->FontSize, FLT_MAX, &obj->Text[char_idx], &obj->Text[char_idx]+1, NULL).x; } +static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { ImWchar c = obj->Text[line_start_idx+char_idx]; if (c == '\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; return GImGui->Font->GetCharAdvance(c) * (GImGui->FontSize / GImGui->Font->FontSize); } static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x10000 ? 0 : key; } static ImWchar STB_TEXTEDIT_NEWLINE = '\n'; static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx) { + const ImWchar* text = obj->Text.Data; const ImWchar* text_remaining = NULL; - const ImVec2 size = obj->Font->CalcTextSizeW(obj->FontSize, FLT_MAX, obj->Text + line_start_idx, NULL, &text_remaining); + const ImVec2 size = InputTextCalcTextSizeW(text + line_start_idx, text + obj->CurLenW, &text_remaining, NULL, true); r->x0 = 0.0f; r->x1 = size.x; r->baseline_y_delta = size.y; r->ymin = 0.0f; r->ymax = size.y; - r->num_chars = (int)(text_remaining - (obj->Text + line_start_idx)); + r->num_chars = (int)(text_remaining - (text + line_start_idx)); } -static bool is_separator(unsigned int c) { return c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; } -#define STB_TEXTEDIT_IS_SPACE(CH) ( ImCharIsSpace((unsigned int)CH) || is_separator((unsigned int)CH) ) +static bool is_separator(unsigned int c) { return ImCharIsSpace(c) || c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; } +static int is_word_boundary_from_right(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (is_separator( obj->Text[idx-1] ) && !is_separator( obj->Text[idx] ) ) : 1; } +static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; } +#ifdef __APPLE__ // FIXME: Move setting to IO structure +static int is_word_boundary_from_left(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (!is_separator( obj->Text[idx-1] ) && is_separator( obj->Text[idx] ) ) : 1; } +static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; } +#else +static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; } +#endif +#define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h +#define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL + static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n) { - ImWchar* dst = obj->Text + pos; + ImWchar* dst = obj->Text.Data + pos; // We maintain our buffer length in both UTF-8 and wchar formats obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n); obj->CurLenW -= n; // Offset remaining text - const ImWchar* src = obj->Text + pos + n; + const ImWchar* src = obj->Text.Data + pos + n; while (ImWchar c = *src++) - *dst++ = c; + *dst++ = c; *dst = '\0'; } static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const ImWchar* new_text, int new_text_len) { - const size_t text_len = obj->CurLenW; - if ((size_t)new_text_len + text_len + 1 > IM_ARRAYSIZE(obj->Text)) + const int text_len = obj->CurLenW; + if (new_text_len + text_len + 1 > obj->Text.Size) return false; const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len); - if ((size_t)new_text_len_utf8 + obj->CurLenA + 1 > obj->BufSizeA) + if (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufSizeA) return false; - if (pos != (int)text_len) - memmove(obj->Text + (size_t)pos + new_text_len, obj->Text + (size_t)pos, (text_len - (size_t)pos) * sizeof(ImWchar)); - memcpy(obj->Text + (size_t)pos, new_text, (size_t)new_text_len * sizeof(ImWchar)); + ImWchar* text = obj->Text.Data; + if (pos != text_len) + memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar)); + memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar)); obj->CurLenW += new_text_len; obj->CurLenA += new_text_len_utf8; @@ -6229,209 +7436,55 @@ static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const Im #define STB_TEXTEDIT_K_WORDRIGHT 0x1000D // keyboard input to move cursor right one word #define STB_TEXTEDIT_K_SHIFT 0x20000 -#ifdef IMGUI_STB_NAMESPACE -namespace IMGUI_STB_NAMESPACE -{ -#endif #define STB_TEXTEDIT_IMPLEMENTATION #include "stb_textedit.h" -#ifdef IMGUI_STB_NAMESPACE + } -#endif void ImGuiTextEditState::OnKeyPressed(int key) -{ - stb_textedit_key(this, &StbState, key); - CursorAnimReset(); -} - -void ImGuiTextEditState::UpdateScrollOffset() { - // Scroll in chunks of quarter width - const float scroll_x_increment = Width * 0.25f; - const float cursor_offset_x = Font->CalcTextSizeW(FontSize, FLT_MAX, Text, Text+StbState.cursor, NULL).x; - - // If widget became bigger than text (because of a resize), reset horizontal scrolling - if (ScrollX > 0.0f) - { - const float text_width = cursor_offset_x + Font->CalcTextSizeW(FontSize, FLT_MAX, Text+StbState.cursor, NULL, NULL).x; - if (text_width < Width) - { - ScrollX = 0.0f; - return; - } - } - - if (cursor_offset_x < ScrollX) - ScrollX = ImMax(0.0f, cursor_offset_x - scroll_x_increment); - else if (cursor_offset_x - Width >= ScrollX) - ScrollX = cursor_offset_x - Width + scroll_x_increment; -} - -ImVec2 ImGuiTextEditState::CalcDisplayOffsetFromCharIdx(int i) const -{ - const ImWchar* text_start = GetTextPointerClippedW(Font, FontSize, Text, ScrollX, NULL); - const ImWchar* text_end = (Text+i >= text_start) ? Text+i : text_start; // Clip if requested character is outside of display - IM_ASSERT(text_end >= text_start); - - const ImVec2 offset = Font->CalcTextSizeW(FontSize, Width+1, text_start, text_end, NULL); - return offset; -} - -// [Static] -const char* ImGuiTextEditState::GetTextPointerClippedA(ImFont* font, float font_size, const char* text, float width, ImVec2* out_text_size) -{ - if (width <= 0.0f) - return text; - - const char* text_clipped_end = NULL; - const ImVec2 text_size = font->CalcTextSizeA(font_size, width, 0.0f, text, NULL, &text_clipped_end); - if (out_text_size) - *out_text_size = text_size; - return text_clipped_end; -} - -// [Static] -const ImWchar* ImGuiTextEditState::GetTextPointerClippedW(ImFont* font, float font_size, const ImWchar* text, float width, ImVec2* out_text_size) -{ - if (width <= 0.0f) - return text; - - const ImWchar* text_clipped_end = NULL; - const ImVec2 text_size = font->CalcTextSizeW(font_size, width, text, NULL, &text_clipped_end); - if (out_text_size) - *out_text_size = text_size; - return text_clipped_end; -} - -// [Static] -void ImGuiTextEditState::RenderTextScrolledClipped(ImFont* font, float font_size, const char* buf, ImVec2 pos, float width, float scroll_x) -{ - ImGuiWindow* window = GetCurrentWindow(); - const ImU32 font_color = window->Color(ImGuiCol_Text); - //window->DrawList->AddLine(pos, pos+ImVec2(width,0), 0xFF00FFFF); - - // Determine start and end of visible string - // FIXME-OPT: This is pretty slow for what it does. - const char* text_start = scroll_x <= 0.0f ? buf : GetTextPointerClippedA(font, font_size, buf, scroll_x, NULL); - const char* text_end = GetTextPointerClippedA(font, font_size, text_start, width + 1, NULL); // +1 to allow character spacing to fit outside the allowed width - window->DrawList->AddText(font, font_size, pos, font_color, text_start, text_end); - - // Log as text - if (GImGui->LogEnabled) - LogText(pos, buf, NULL); -} - -bool ImGui::InputFloat(const char* label, float *v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags) -{ - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - if (window->SkipItems) - return false; - - const ImGuiStyle& style = g.Style; - const float w = ImGui::CalcItemWidth(); - const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y) + style.FramePadding*2.0f); - - ImGui::BeginGroup(); - ImGui::PushID(label); - const ImVec2 button_sz = ImVec2(g.FontSize, g.FontSize) + style.FramePadding * 2; - if (step > 0.0f) - ImGui::PushItemWidth(ImMax(1.0f, w - (button_sz.x + style.ItemInnerSpacing.x)*2)); - - char buf[64]; - if (decimal_precision < 0) - ImFormatString(buf, IM_ARRAYSIZE(buf), "%f", *v); // Ideally we'd have a minimum decimal precision of 1 to visually denote that it is a float, while hiding non-significant digits? - else - ImFormatString(buf, IM_ARRAYSIZE(buf), "%.*f", decimal_precision, *v); - bool value_changed = false; - const ImGuiInputTextFlags flags = extra_flags | (ImGuiInputTextFlags_CharsDecimal|ImGuiInputTextFlags_AutoSelectAll); - if (ImGui::InputText("", buf, IM_ARRAYSIZE(buf), flags)) - { - ApplyNumericalTextInput(buf, v); - value_changed = true; - } - - // Step buttons - if (step > 0.0f) - { - ImGui::PopItemWidth(); - ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); - if (ImGui::Button("-", button_sz, true)) - { - *v -= g.IO.KeyCtrl && step_fast > 0.0f ? step_fast : step; - value_changed = true; - } - ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); - if (ImGui::Button("+", button_sz, true)) - { - *v += g.IO.KeyCtrl && step_fast > 0.0f ? step_fast : step; - value_changed = true; - } - } - - ImGui::PopID(); - - if (label_size.x > 0) - { - ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); - RenderText(ImVec2(window->DC.CursorPos.x, window->DC.CursorPos.y + style.FramePadding.y), label); - ItemSize(label_size, style.FramePadding.y); - } - - ImGui::EndGroup(); - - return value_changed; -} - -bool ImGui::InputInt(const char* label, int *v, int step, int step_fast, ImGuiInputTextFlags extra_flags) -{ - float f = (float)*v; - const bool value_changed = ImGui::InputFloat(label, &f, (float)step, (float)step_fast, 0, extra_flags); - if (value_changed) - *v = (int)f; - return value_changed; + stb_textedit_key(this, &StbState, key); + CursorFollow = true; + CursorAnimReset(); } // Public API to manipulate UTF-8 text // We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar) +// FIXME: The existence of this rarely exercised code path is a bit of a nuisance. void ImGuiTextEditCallbackData::DeleteChars(int pos, int bytes_count) { + IM_ASSERT(pos + bytes_count <= BufTextLen); char* dst = Buf + pos; const char* src = Buf + pos + bytes_count; while (char c = *src++) *dst++ = c; *dst = '\0'; - BufDirty = true; if (CursorPos + bytes_count >= pos) CursorPos -= bytes_count; else if (CursorPos >= pos) CursorPos = pos; SelectionStart = SelectionEnd = CursorPos; + BufDirty = true; + BufTextLen -= bytes_count; } void ImGuiTextEditCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end) { - const size_t text_len = strlen(Buf); - if (!new_text_end) - new_text_end = new_text + strlen(new_text); - const size_t new_text_len = (size_t)(new_text_end - new_text); - - if (new_text_len + text_len + 1 >= BufSize) + const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text); + if (new_text_len + BufTextLen + 1 >= BufSize) return; - size_t upos = (size_t)pos; - if (text_len != upos) - memmove(Buf + upos + new_text_len, Buf + upos, text_len - upos); - memcpy(Buf + upos, new_text, new_text_len * sizeof(char)); - Buf[text_len + new_text_len] = '\0'; + if (BufTextLen != pos) + memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos)); + memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char)); + Buf[BufTextLen + new_text_len] = '\0'; - BufDirty = true; if (CursorPos >= pos) - CursorPos += (int)new_text_len; + CursorPos += new_text_len; SelectionStart = SelectionEnd = CursorPos; + BufDirty = true; + BufTextLen += new_text_len; } // Return false to discard a character. @@ -6440,7 +7493,13 @@ static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags f unsigned int c = *p_char; if (c < 128 && c != ' ' && !isprint((int)(c & 0xFF))) - return false; + { + bool pass = false; + pass |= (c == '\n' && (flags & ImGuiInputTextFlags_Multiline)); + pass |= (c == '\t' && (flags & ImGuiInputTextFlags_AllowTabInput)); + if (!pass) + return false; + } if (c >= 0xE000 && c <= 0xF8FF) // Filter private Unicode range. I don't imagine anybody would want to input them. GLFW on OSX seems to send private characters for special keys like arrow keys. return false; @@ -6468,7 +7527,7 @@ static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags f { ImGuiTextEditCallbackData callback_data; memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData)); - callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter; + callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter; callback_data.EventChar = (ImWchar)c; callback_data.Flags = flags; callback_data.UserData = user_data; @@ -6483,25 +7542,67 @@ static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags f } // Edit a string of text -bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) +// NB: when active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while active has no effect. +// FIXME: Rather messy function partly because we are doing UTF8 > u16 > UTF8 conversions on the go to more easily handle stb_textedit calls. Ideally we should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188 +bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys) + IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key) + + ImGuiContext& g = *GImGui; const ImGuiIO& io = g.IO; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); - const float w = ImGui::CalcItemWidth(); + const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0; + const bool is_editable = (flags & ImGuiInputTextFlags_ReadOnly) == 0; + const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0; const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y) + style.FramePadding*2.0f); + ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? GetTextLineHeight() * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? (style.ItemInnerSpacing.x + label_size.x) : 0.0f, 0.0f)); - ItemSize(total_bb, style.FramePadding.y); - if (!ItemAdd(total_bb, &id)) - return false; + + ImGuiWindow* draw_window = window; + if (is_multiline) + { + BeginGroup(); + if (!BeginChildFrame(id, frame_bb.GetSize())) + { + EndChildFrame(); + EndGroup(); + return false; + } + draw_window = GetCurrentWindow(); + size.x -= draw_window->ScrollbarSizes.x; + } + else + { + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, &id)) + return false; + } + + // Password pushes a temporary font with only a fallback glyph + if (is_password) + { + const ImFont::Glyph* glyph = g.Font->FindGlyph('*'); + ImFont* password_font = &g.InputTextPasswordFont; + password_font->FontSize = g.Font->FontSize; + password_font->Scale = g.Font->Scale; + password_font->DisplayOffset = g.Font->DisplayOffset; + password_font->Ascent = g.Font->Ascent; + password_font->Descent = g.Font->Descent; + password_font->ContainerAtlas = g.Font->ContainerAtlas; + password_font->FallbackGlyph = glyph; + password_font->FallbackXAdvance = glyph->XAdvance; + IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexXAdvance.empty() && password_font->IndexLookup.empty()); + PushFont(password_font); + } // NB: we are only allowed to access 'edit_state' if we are the active widget. ImGuiTextEditState& edit_state = g.InputTextState; @@ -6509,103 +7610,115 @@ bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputT const bool is_ctrl_down = io.KeyCtrl; const bool is_shift_down = io.KeyShift; const bool is_alt_down = io.KeyAlt; - const bool focus_requested = window->FocusItemRegister(g.ActiveId == id, (flags & ImGuiInputTextFlags_CallbackCompletion) == 0); // Using completion callback disable keyboard tabbing + const bool is_super_down = io.KeySuper; + const bool focus_requested = FocusableItemRegister(window, g.ActiveId == id, (flags & (ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_AllowTabInput)) == 0); // Using completion callback disable keyboard tabbing const bool focus_requested_by_code = focus_requested && (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent); const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code; const bool hovered = IsHovered(frame_bb, id); if (hovered) { - g.HoveredId = id; + SetHoveredID(id); g.MouseCursor = ImGuiMouseCursor_TextInput; } const bool user_clicked = hovered && io.MouseClicked[0]; + const bool user_scrolled = is_multiline && g.ActiveId == 0 && edit_state.Id == id && g.ActiveIdPreviousFrame == draw_window->GetID("#SCROLLY"); bool select_all = (g.ActiveId != id) && (flags & ImGuiInputTextFlags_AutoSelectAll) != 0; - if (focus_requested || user_clicked) + if (focus_requested || user_clicked || user_scrolled) { if (g.ActiveId != id) { // Start edition // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar) - // From the moment we focused we are ignoring the content of 'buf' - ImFormatString(edit_state.InitialText, IM_ARRAYSIZE(edit_state.InitialText), "%s", buf); + // From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode) + const int prev_len_w = edit_state.CurLenW; + edit_state.Text.resize(buf_size+1); // wchar count <= utf-8 count. we use +1 to make sure that .Data isn't NULL so it doesn't crash. + edit_state.InitialText.resize(buf_size+1); // utf-8. we use +1 to make sure that .Data isn't NULL so it doesn't crash. + ImFormatString(edit_state.InitialText.Data, edit_state.InitialText.Size, "%s", buf); const char* buf_end = NULL; - edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text, IM_ARRAYSIZE(edit_state.Text), buf, NULL, &buf_end); - edit_state.CurLenA = buf_end - buf; // We can't get the result from ImFormatString() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8. - edit_state.Width = w + style.FramePadding.x; - edit_state.InputCursorScreenPos = ImVec2(-1.f,-1.f); + edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end); + edit_state.CurLenA = (int)(buf_end - buf); // We can't get the result from ImFormatString() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8. edit_state.CursorAnimReset(); - if (edit_state.Id != id) - { - edit_state.Id = id; - edit_state.ScrollX = 0.0f; - stb_textedit_initialize_state(&edit_state.StbState, true); - if (focus_requested_by_code) - select_all = true; - } - else + // Preserve cursor position and undo/redo stack if we come back to same widget + // FIXME: We should probably compare the whole buffer to be on the safety side. Comparing buf (utf8) and edit_state.Text (wchar). + const bool recycle_state = (edit_state.Id == id) && (prev_len_w == edit_state.CurLenW); + if (recycle_state) { // Recycle existing cursor/selection/undo stack but clamp position // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler. - edit_state.StbState.cursor = ImMin(edit_state.StbState.cursor, (int)edit_state.CurLenW); - edit_state.StbState.select_start = ImMin(edit_state.StbState.select_start, (int)edit_state.CurLenW); - edit_state.StbState.select_end = ImMin(edit_state.StbState.select_end, (int)edit_state.CurLenW); + edit_state.CursorClamp(); } - if (focus_requested_by_tab || (user_clicked && is_ctrl_down)) + else + { + edit_state.Id = id; + edit_state.ScrollX = 0.0f; + stb_textedit_initialize_state(&edit_state.StbState, !is_multiline); + if (!is_multiline && focus_requested_by_code) + select_all = true; + } + if (flags & ImGuiInputTextFlags_AlwaysInsertMode) + edit_state.StbState.insert_mode = true; + if (!is_multiline && (focus_requested_by_tab || (user_clicked && is_ctrl_down))) select_all = true; } - SetActiveId(id); + SetActiveID(id, window); FocusWindow(window); } else if (io.MouseClicked[0]) { // Release focus when we click outside if (g.ActiveId == id) - { - SetActiveId(0); - } + SetActiveID(0); } - // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget. - // Down the line we should have a cleaner concept of focused vs active in the library. - if (g.ActiveId == id) - g.ActiveIdIsFocusedOnly = !io.MouseDown[0]; - bool value_changed = false; - bool cancel_edit = false; bool enter_pressed = false; - if (g.ActiveId == id) - //if (edit_state.Id == id) // Works, but double-click to select-all sets cursors to end which in turn tends to scroll toward the right when shrinking widget. - { - // Update some data if we are active or last active - edit_state.Width = w + style.FramePadding.x; - edit_state.BufSizeA = buf_size; - edit_state.Font = g.Font; - edit_state.FontSize = g.FontSize; - edit_state.UpdateScrollOffset(); - } - if (g.ActiveId == id) - { - // Edit in progress - const float mx = g.IO.MousePos.x - frame_bb.Min.x - style.FramePadding.x; - const float my = g.FontSize*0.5f; // Flatten mouse because we are doing a single-line edit - if (select_all || (hovered && io.MouseDoubleClicked[0])) + if (g.ActiveId == id) + { + if (!is_editable && !g.ActiveIdIsJustActivated) + { + // When read-only we always use the live data passed to the function + edit_state.Text.resize(buf_size+1); + const char* buf_end = NULL; + edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end); + edit_state.CurLenA = (int)(buf_end - buf); + edit_state.CursorClamp(); + } + + edit_state.BufSizeA = buf_size; + + // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget. + // Down the line we should have a cleaner library-wide concept of Selected vs Active. + g.ActiveIdAllowOverlap = !io.MouseDown[0]; + + // Edit in progress + const float mouse_x = (g.IO.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + edit_state.ScrollX; + const float mouse_y = (is_multiline ? (g.IO.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize*0.5f)); + + if (select_all || (hovered && !io.DoubleClickSelectsWord && io.MouseDoubleClicked[0])) { edit_state.SelectAll(); edit_state.SelectedAllMouseLock = true; } + else if (hovered && io.DoubleClickSelectsWord && io.MouseDoubleClicked[0]) + { + // Select a word only, OS X style (by simulating keystrokes) + edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT); + edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT); + } else if (io.MouseClicked[0] && !edit_state.SelectedAllMouseLock) { - stb_textedit_click(&edit_state, &edit_state.StbState, mx + edit_state.ScrollX, my); + stb_textedit_click(&edit_state, &edit_state.StbState, mouse_x, mouse_y); edit_state.CursorAnimReset(); } - else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock) + else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)) { - stb_textedit_drag(&edit_state, &edit_state.StbState, mx + edit_state.ScrollX, my); + stb_textedit_drag(&edit_state, &edit_state.StbState, mouse_x, mouse_y); edit_state.CursorAnimReset(); + edit_state.CursorFollow = true; } if (edit_state.SelectedAllMouseLock && !io.MouseDown[0]) edit_state.SelectedAllMouseLock = false; @@ -6613,36 +7726,63 @@ bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputT if (g.IO.InputCharacters[0]) { // Process text input (before we check for Return because using some IME will effectively send a Return?) - for (int n = 0; n < IM_ARRAYSIZE(g.IO.InputCharacters) && g.IO.InputCharacters[n]; n++) + // We ignore CTRL inputs, but need to allow CTRL+ALT as some keyboards (e.g. German) use AltGR - which is Alt+Ctrl - to input certain characters. + if (!(is_ctrl_down && !is_alt_down) && is_editable) { - unsigned int c = (unsigned int)g.IO.InputCharacters[n]; - if (c) - { - // Insert character if they pass filtering - if (!InputTextFilterCharacter(&c, flags, callback, user_data)) - continue; - edit_state.OnKeyPressed((int)c); - } + for (int n = 0; n < IM_ARRAYSIZE(g.IO.InputCharacters) && g.IO.InputCharacters[n]; n++) + if (unsigned int c = (unsigned int)g.IO.InputCharacters[n]) + { + // Insert character if they pass filtering + if (!InputTextFilterCharacter(&c, flags, callback, user_data)) + continue; + edit_state.OnKeyPressed((int)c); + } } // Consume characters memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters)); } + // Handle various key-presses + bool cancel_edit = false; const int k_mask = (is_shift_down ? STB_TEXTEDIT_K_SHIFT : 0); - const bool is_ctrl_only = is_ctrl_down && !is_alt_down && !is_shift_down; - if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_WORDLEFT | k_mask : STB_TEXTEDIT_K_LEFT | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_WORDRIGHT | k_mask : STB_TEXTEDIT_K_RIGHT | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_Home)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_End)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_Delete)) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_Backspace)) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_Enter)) { SetActiveId(0); enter_pressed = true; } - else if (IsKeyPressedMap(ImGuiKey_Escape)) { SetActiveId(0); cancel_edit = true; } - else if (is_ctrl_only && IsKeyPressedMap(ImGuiKey_Z)) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); } - else if (is_ctrl_only && IsKeyPressedMap(ImGuiKey_Y)) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_REDO); } - else if (is_ctrl_only && IsKeyPressedMap(ImGuiKey_A)) { edit_state.SelectAll(); } - else if (is_ctrl_only && (IsKeyPressedMap(ImGuiKey_X) || IsKeyPressedMap(ImGuiKey_C))) + const bool is_shortcutkey_only = (io.ShortcutsUseSuperKey ? (is_super_down && !is_alt_down && !is_shift_down && !is_ctrl_down) : (is_ctrl_down && !is_alt_down && !is_shift_down && !is_super_down)); + const bool is_wordmove_key_down = (io.WordMovementUsesAltKey ? io.KeyAlt : io.KeyCtrl); + + if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { edit_state.OnKeyPressed(is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT | k_mask : STB_TEXTEDIT_K_LEFT | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { edit_state.OnKeyPressed(is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT | k_mask : STB_TEXTEDIT_K_RIGHT | k_mask); } + else if (is_multiline && IsKeyPressedMap(ImGuiKey_UpArrow)) { if (is_ctrl_down) SetWindowScrollY(draw_window, draw_window->Scroll.y - g.FontSize); else edit_state.OnKeyPressed(STB_TEXTEDIT_K_UP | k_mask); } + else if (is_multiline && IsKeyPressedMap(ImGuiKey_DownArrow)) { if (is_ctrl_down) SetWindowScrollY(draw_window, draw_window->Scroll.y + g.FontSize); else edit_state.OnKeyPressed(STB_TEXTEDIT_K_DOWN| k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Home)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_End)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Delete) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Backspace) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Enter)) + { + bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0; + if (!is_multiline || (ctrl_enter_for_new_line && !is_ctrl_down) || (!ctrl_enter_for_new_line && is_ctrl_down)) + { + SetActiveID(0); + enter_pressed = true; + } + else if (is_editable) + { + unsigned int c = '\n'; // Insert new line + if (InputTextFilterCharacter(&c, flags, callback, user_data)) + edit_state.OnKeyPressed((int)c); + } + } + else if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !is_ctrl_down && !is_shift_down && !is_alt_down && is_editable) + { + unsigned int c = '\t'; // Insert TAB + if (InputTextFilterCharacter(&c, flags, callback, user_data)) + edit_state.OnKeyPressed((int)c); + } + else if (IsKeyPressedMap(ImGuiKey_Escape)) { SetActiveID(0); cancel_edit = true; } + else if (is_shortcutkey_only && IsKeyPressedMap(ImGuiKey_Z) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); edit_state.ClearSelection(); } + else if (is_shortcutkey_only && IsKeyPressedMap(ImGuiKey_Y) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_REDO); edit_state.ClearSelection(); } + else if (is_shortcutkey_only && IsKeyPressedMap(ImGuiKey_A)) { edit_state.SelectAll(); edit_state.CursorFollow = true; } + else if (is_shortcutkey_only && !is_password && ((IsKeyPressedMap(ImGuiKey_X) && is_editable) || IsKeyPressedMap(ImGuiKey_C)) && (!is_multiline || edit_state.HasSelection())) { // Cut, Copy const bool cut = IsKeyPressedMap(ImGuiKey_X); @@ -6652,15 +7792,19 @@ bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputT if (g.IO.SetClipboardTextFn) { const int ib = edit_state.HasSelection() ? ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end) : 0; - const int ie = edit_state.HasSelection() ? ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end) : (int)edit_state.CurLenW; - ImTextStrToUtf8(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), edit_state.Text+ib, edit_state.Text+ie); - g.IO.SetClipboardTextFn(g.TempBuffer); + const int ie = edit_state.HasSelection() ? ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end) : edit_state.CurLenW; + edit_state.TempTextBuffer.resize((ie-ib) * 4 + 1); + ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data+ib, edit_state.Text.Data+ie); + g.IO.SetClipboardTextFn(edit_state.TempTextBuffer.Data); } if (cut) + { + edit_state.CursorFollow = true; stb_textedit_cut(&edit_state, &edit_state.StbState); + } } - else if (is_ctrl_only && IsKeyPressedMap(ImGuiKey_V)) + else if (is_shortcutkey_only && IsKeyPressedMap(ImGuiKey_V) && is_editable) { // Paste if (g.IO.GetClipboardTextFn) @@ -6668,7 +7812,7 @@ bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputT if (const char* clipboard = g.IO.GetClipboardTextFn()) { // Remove new-line from pasted buffer - const size_t clipboard_len = strlen(clipboard); + const int clipboard_len = (int)strlen(clipboard); ImWchar* clipboard_filtered = (ImWchar*)ImGui::MemAlloc((clipboard_len+1) * sizeof(ImWchar)); int clipboard_filtered_len = 0; for (const char* s = clipboard; *s; ) @@ -6677,36 +7821,41 @@ bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputT s += ImTextCharFromUtf8(&c, s, NULL); if (c == 0) break; - if (c >= 0x10000) - continue; - if (!InputTextFilterCharacter(&c, flags, callback, user_data)) + if (c >= 0x10000 || !InputTextFilterCharacter(&c, flags, callback, user_data)) continue; clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c; } clipboard_filtered[clipboard_filtered_len] = 0; if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation + { stb_textedit_paste(&edit_state, &edit_state.StbState, clipboard_filtered, clipboard_filtered_len); + edit_state.CursorFollow = true; + } ImGui::MemFree(clipboard_filtered); } } } - edit_state.CursorAnim += g.IO.DeltaTime; - edit_state.UpdateScrollOffset(); - if (cancel_edit) { // Restore initial value - ImFormatString(buf, buf_size, "%s", edit_state.InitialText); - value_changed = true; + if (is_editable) + { + ImFormatString(buf, buf_size, "%s", edit_state.InitialText.Data); + value_changed = true; + } } else { // Apply new value immediately - copy modified buffer back - // Note that as soon as we can focus into the input box, the in-widget value gets priority over any underlying modification of the input buffer - // FIXME: We actually always render 'buf' in RenderTextScrolledClipped - // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks - ImTextStrToUtf8(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), edit_state.Text, NULL); + // Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer + // FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect. + // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks. + if (is_editable) + { + edit_state.TempTextBuffer.resize(edit_state.Text.Size * 4); + ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data, NULL); + } // User callback if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackAlways)) != 0) @@ -6731,28 +7880,35 @@ bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputT event_flag = ImGuiInputTextFlags_CallbackHistory; event_key = ImGuiKey_DownArrow; } + else if (flags & ImGuiInputTextFlags_CallbackAlways) + event_flag = ImGuiInputTextFlags_CallbackAlways; - if (event_key != ImGuiKey_COUNT || (flags & ImGuiInputTextFlags_CallbackAlways) != 0) + if (event_flag) { ImGuiTextEditCallbackData callback_data; - callback_data.EventFlag = event_flag; - callback_data.EventKey = event_key; - callback_data.Buf = g.TempBuffer; - callback_data.BufSize = edit_state.BufSizeA; - callback_data.BufDirty = false; + memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData)); + callback_data.EventFlag = event_flag; callback_data.Flags = flags; callback_data.UserData = user_data; + callback_data.ReadOnly = !is_editable; - // We have to convert from position from wchar to UTF-8 positions - const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(edit_state.Text, edit_state.Text + edit_state.StbState.cursor); - const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(edit_state.Text, edit_state.Text + edit_state.StbState.select_start); - const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(edit_state.Text, edit_state.Text + edit_state.StbState.select_end); + callback_data.EventKey = event_key; + callback_data.Buf = edit_state.TempTextBuffer.Data; + callback_data.BufTextLen = edit_state.CurLenA; + callback_data.BufSize = edit_state.BufSizeA; + callback_data.BufDirty = false; + + // We have to convert from wchar-positions to UTF-8-positions, which can be pretty slow (an incentive to ditch the ImWchar buffer, see https://github.com/nothings/stb/issues/188) + ImWchar* text = edit_state.Text.Data; + const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.cursor); + const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_start); + const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_end); // Call user code callback(&callback_data); // Read back what user may have modified - IM_ASSERT(callback_data.Buf == g.TempBuffer); // Invalid to modify those fields + IM_ASSERT(callback_data.Buf == edit_state.TempTextBuffer.Data); // Invalid to modify those fields IM_ASSERT(callback_data.BufSize == edit_state.BufSizeA); IM_ASSERT(callback_data.Flags == flags); if (callback_data.CursorPos != utf8_cursor_pos) edit_state.StbState.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); @@ -6760,57 +7916,187 @@ bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputT if (callback_data.SelectionEnd != utf8_selection_end) edit_state.StbState.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); if (callback_data.BufDirty) { - edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text, IM_ARRAYSIZE(edit_state.Text), g.TempBuffer, NULL); - edit_state.CurLenA = strlen(g.TempBuffer); + IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text! + edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, callback_data.Buf, NULL); + edit_state.CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen() edit_state.CursorAnimReset(); } } } - if (strcmp(g.TempBuffer, buf) != 0) + // Copy back to user buffer + if (is_editable && strcmp(edit_state.TempTextBuffer.Data, buf) != 0) { - ImFormatString(buf, buf_size, "%s", g.TempBuffer); + ImFormatString(buf, buf_size, "%s", edit_state.TempTextBuffer.Data); value_changed = true; } } } - - RenderFrame(frame_bb.Min, frame_bb.Max, window->Color(ImGuiCol_FrameBg), true, style.FrameRounding); - const ImVec2 font_off_up = ImVec2(0.0f, g.FontSize+1.0f); // FIXME: those offsets are part of the style or font API - const ImVec2 font_off_dn = ImVec2(0.0f, 2.0f); + if (!is_multiline) + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); - if (g.ActiveId == id) + // Render + const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + size.x, frame_bb.Min.y + size.y); // Not using frame_bb.Max because we have adjusted size + ImVec2 render_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding; + ImVec2 text_size(0.f, 0.f); + if (g.ActiveId == id || (edit_state.Id == id && is_multiline && g.ActiveId == draw_window->GetID("#SCROLLY"))) { - // Draw selection - const int select_begin_idx = edit_state.StbState.select_start; - const int select_end_idx = edit_state.StbState.select_end; - if (select_begin_idx != select_end_idx) + edit_state.CursorAnim += g.IO.DeltaTime; + + // We need to: + // - Display the text (this can be more easily clipped) + // - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation) + // - Measure text height (for scrollbar) + // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort) + const ImWchar* text_begin = edit_state.Text.Data; + ImVec2 cursor_offset, select_start_offset; + { - const ImVec2 select_begin_pos = frame_bb.Min + style.FramePadding + edit_state.CalcDisplayOffsetFromCharIdx(ImMin(select_begin_idx,select_end_idx)); - const ImVec2 select_end_pos = frame_bb.Min + style.FramePadding + edit_state.CalcDisplayOffsetFromCharIdx(ImMax(select_begin_idx,select_end_idx)); - window->DrawList->AddRectFilled(select_begin_pos - font_off_up, select_end_pos + font_off_dn, window->Color(ImGuiCol_TextSelectedBg)); + // Count lines + find lines numbers straddling 'cursor' and 'select_start' position. + const ImWchar* searches_input_ptr[2]; + searches_input_ptr[0] = text_begin + edit_state.StbState.cursor; + searches_input_ptr[1] = NULL; + int searches_remaining = 1; + int searches_result_line_number[2] = { -1, -999 }; + if (edit_state.StbState.select_start != edit_state.StbState.select_end) + { + searches_input_ptr[1] = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end); + searches_result_line_number[1] = -1; + searches_remaining++; + } + + // Iterate all lines to find our line numbers + // In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter. + searches_remaining += is_multiline ? 1 : 0; + int line_count = 0; + for (const ImWchar* s = text_begin; *s != 0; s++) + if (*s == '\n') + { + line_count++; + if (searches_result_line_number[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_number[0] = line_count; if (--searches_remaining <= 0) break; } + if (searches_result_line_number[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_number[1] = line_count; if (--searches_remaining <= 0) break; } + } + line_count++; + if (searches_result_line_number[0] == -1) searches_result_line_number[0] = line_count; + if (searches_result_line_number[1] == -1) searches_result_line_number[1] = line_count; + + // Calculate 2d position by finding the beginning of the line and measuring distance + cursor_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x; + cursor_offset.y = searches_result_line_number[0] * g.FontSize; + if (searches_result_line_number[1] >= 0) + { + select_start_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x; + select_start_offset.y = searches_result_line_number[1] * g.FontSize; + } + + // Calculate text height + if (is_multiline) + text_size = ImVec2(size.x, line_count * g.FontSize); } - } - //const float render_scroll_x = (g.ActiveId == id) ? edit_state.ScrollX : 0.0f; - const float render_scroll_x = (edit_state.Id == id) ? edit_state.ScrollX : 0.0f; - ImGuiTextEditState::RenderTextScrolledClipped(g.Font, g.FontSize, buf, frame_bb.Min + style.FramePadding, w + style.FramePadding.x, render_scroll_x); + // Scroll + if (edit_state.CursorFollow) + { + // Horizontal scroll in chunks of quarter width + if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll)) + { + const float scroll_increment_x = size.x * 0.25f; + if (cursor_offset.x < edit_state.ScrollX) + edit_state.ScrollX = (float)(int)ImMax(0.0f, cursor_offset.x - scroll_increment_x); + else if (cursor_offset.x - size.x >= edit_state.ScrollX) + edit_state.ScrollX = (float)(int)(cursor_offset.x - size.x + scroll_increment_x); + } + else + { + edit_state.ScrollX = 0.0f; + } - if (g.ActiveId == id) - { - const ImVec2 cursor_pos = frame_bb.Min + style.FramePadding + edit_state.CalcDisplayOffsetFromCharIdx(edit_state.StbState.cursor); + // Vertical scroll + if (is_multiline) + { + float scroll_y = draw_window->Scroll.y; + if (cursor_offset.y - g.FontSize < scroll_y) + scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize); + else if (cursor_offset.y - size.y >= scroll_y) + scroll_y = cursor_offset.y - size.y; + draw_window->DC.CursorPos.y += (draw_window->Scroll.y - scroll_y); // To avoid a frame of lag + draw_window->Scroll.y = scroll_y; + render_pos.y = draw_window->DC.CursorPos.y; + } + } + edit_state.CursorFollow = false; + const ImVec2 render_scroll = ImVec2(edit_state.ScrollX, 0.0f); + + // Draw selection + if (edit_state.StbState.select_start != edit_state.StbState.select_end) + { + const ImWchar* text_selected_begin = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end); + const ImWchar* text_selected_end = text_begin + ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end); + + float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection. + float bg_offy_dn = is_multiline ? 0.0f : 2.0f; + ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg); + ImVec2 rect_pos = render_pos + select_start_offset - render_scroll; + for (const ImWchar* p = text_selected_begin; p < text_selected_end; ) + { + if (rect_pos.y > clip_rect.w + g.FontSize) + break; + if (rect_pos.y < clip_rect.y) + { + while (p < text_selected_end) + if (*p++ == '\n') + break; + } + else + { + ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true); + if (rect_size.x <= 0.0f) rect_size.x = (float)(int)(g.Font->GetCharAdvance((unsigned short)' ') * 0.50f); // So we can see selected empty lines + ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos +ImVec2(rect_size.x, bg_offy_dn)); + rect.Clip(clip_rect); + if (rect.Overlaps(clip_rect)) + draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color); + } + rect_pos.x = render_pos.x - render_scroll.x; + rect_pos.y += g.FontSize; + } + } + + draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos - render_scroll, GetColorU32(ImGuiCol_Text), buf, buf+edit_state.CurLenA, 0.0f, is_multiline ? NULL : &clip_rect); // Draw blinking cursor - if (g.InputTextState.CursorIsVisible()) - window->DrawList->AddLine(cursor_pos - font_off_up + ImVec2(0,2), cursor_pos + font_off_dn - ImVec2(0,3), window->Color(ImGuiCol_Text)); - - // Notify OS of text input position for advanced IME - if (io.ImeSetInputScreenPosFn && ImLengthSqr(edit_state.InputCursorScreenPos - cursor_pos) > 0.0001f) - io.ImeSetInputScreenPosFn((int)cursor_pos.x - 1, (int)(cursor_pos.y - g.FontSize)); // -1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety. + bool cursor_is_visible = (g.InputTextState.CursorAnim <= 0.0f) || fmodf(g.InputTextState.CursorAnim, 1.20f) <= 0.80f; + ImVec2 cursor_screen_pos = render_pos + cursor_offset - render_scroll; + ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y-g.FontSize+0.5f, cursor_screen_pos.x+1.0f, cursor_screen_pos.y-1.5f); + if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) + draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text)); - edit_state.InputCursorScreenPos = cursor_pos; + // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.) + if (is_editable) + g.OsImePosRequest = ImVec2(cursor_screen_pos.x - 1, cursor_screen_pos.y - g.FontSize); } + else + { + // Render text only + const char* buf_end = NULL; + if (is_multiline) + text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf, &buf_end) * g.FontSize); // We don't need width + draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos, GetColorU32(ImGuiCol_Text), buf, buf_end, 0.0f, is_multiline ? NULL : &clip_rect); + } + + if (is_multiline) + { + Dummy(text_size + ImVec2(0.0f, g.FontSize)); // Always add room to scroll an extra line + EndChildFrame(); + EndGroup(); + } + + if (is_password) + PopFont(); + + // Log as text + if (g.LogEnabled && !is_password) + LogRenderedText(render_pos, buf, NULL); if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); @@ -6821,30 +8107,117 @@ bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputT return value_changed; } -static bool InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags) +bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) +{ + IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() + bool ret = InputTextEx(label, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data); + return ret; +} + +bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) +{ + bool ret = InputTextEx(label, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data); + return ret; +} + +// NB: scalar_format here must be a simple "%xx" format string with no prefix/suffix (unlike the Drag/Slider functions "display_format" argument) +bool ImGui::InputScalarEx(const char* label, ImGuiDataType data_type, void* data_ptr, void* step_ptr, void* step_fast_ptr, const char* scalar_format, ImGuiInputTextFlags extra_flags) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + BeginGroup(); + PushID(label); + const ImVec2 button_sz = ImVec2(g.FontSize, g.FontSize) + style.FramePadding*2.0f; + if (step_ptr) + PushItemWidth(ImMax(1.0f, CalcItemWidth() - (button_sz.x + style.ItemInnerSpacing.x)*2)); + + char buf[64]; + DataTypeFormatString(data_type, data_ptr, scalar_format, buf, IM_ARRAYSIZE(buf)); + bool value_changed = false; - ImGui::BeginGroup(); - ImGui::PushID(label); + if (!(extra_flags & ImGuiInputTextFlags_CharsHexadecimal)) + extra_flags |= ImGuiInputTextFlags_CharsDecimal; + extra_flags |= ImGuiInputTextFlags_AutoSelectAll; + if (InputText("", buf, IM_ARRAYSIZE(buf), extra_flags)) + value_changed = DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, scalar_format); + + // Step buttons + if (step_ptr) + { + PopItemWidth(); + SameLine(0, style.ItemInnerSpacing.x); + if (ButtonEx("-", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups)) + { + DataTypeApplyOp(data_type, '-', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr); + value_changed = true; + } + SameLine(0, style.ItemInnerSpacing.x); + if (ButtonEx("+", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups)) + { + DataTypeApplyOp(data_type, '+', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr); + value_changed = true; + } + } + PopID(); + + if (label_size.x > 0) + { + SameLine(0, style.ItemInnerSpacing.x); + RenderText(ImVec2(window->DC.CursorPos.x, window->DC.CursorPos.y + style.FramePadding.y), label); + ItemSize(label_size, style.FramePadding.y); + } + EndGroup(); + + return value_changed; +} + +bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags) +{ + char display_format[16]; + if (decimal_precision < 0) + strcpy(display_format, "%f"); // Ideally we'd have a minimum decimal precision of 1 to visually denote that this is a float, while hiding non-significant digits? %f doesn't have a minimum of 1 + else + ImFormatString(display_format, 16, "%%.%df", decimal_precision); + return InputScalarEx(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), display_format, extra_flags); +} + +bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags extra_flags) +{ + // Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes. + const char* scalar_format = (extra_flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d"; + return InputScalarEx(label, ImGuiDataType_Int, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), scalar_format, extra_flags); +} + +bool ImGui::InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); PushMultiItemsWidths(components); for (int i = 0; i < components; i++) { - ImGui::PushID(i); - value_changed |= ImGui::InputFloat("##v", &v[i], 0, 0, decimal_precision, extra_flags); - ImGui::SameLine(0, (int)g.Style.ItemInnerSpacing.x); - ImGui::PopID(); - ImGui::PopItemWidth(); + PushID(i); + value_changed |= InputFloat("##v", &v[i], 0, 0, decimal_precision, extra_flags); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); } - ImGui::PopID(); + PopID(); window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y); - ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); - ImGui::EndGroup(); + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); return value_changed; } @@ -6864,30 +8237,30 @@ bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision, Im return InputFloatN(label, v, 4, decimal_precision, extra_flags); } -static bool InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags) +bool ImGui::InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; bool value_changed = false; - ImGui::BeginGroup(); - ImGui::PushID(label); + BeginGroup(); + PushID(label); PushMultiItemsWidths(components); for (int i = 0; i < components; i++) { - ImGui::PushID(i); - value_changed |= ImGui::InputInt("##v", &v[i], 0, 0, extra_flags); - ImGui::SameLine(0, (int)g.Style.ItemInnerSpacing.x); - ImGui::PopID(); - ImGui::PopItemWidth(); + PushID(i); + value_changed |= InputInt("##v", &v[i], 0, 0, extra_flags); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); } - ImGui::PopID(); + PopID(); window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y); - ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); - ImGui::EndGroup(); + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); return value_changed; } @@ -6946,7 +8319,7 @@ bool ImGui::Combo(const char* label, int* current_item, const char** items, int bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items) { int items_count = 0; - const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this + const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open while (*p) { p += strlen(p) + 1; @@ -6959,160 +8332,194 @@ bool ImGui::Combo(const char* label, int* current_item, const char* items_separa // Combo box function. bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); - const float w = ImGui::CalcItemWidth(); + const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y) + style.FramePadding*2.0f); - const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(style.ItemInnerSpacing.x + label_size.x,0)); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, &id)) return false; const float arrow_size = (g.FontSize + style.FramePadding.x * 2.0f); const bool hovered = IsHovered(frame_bb, id); + bool popup_open = IsPopupOpen(id); + bool popup_opened_now = false; - bool value_changed = false; const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f)); - RenderFrame(frame_bb.Min, frame_bb.Max, window->Color(ImGuiCol_FrameBg), true, style.FrameRounding); - RenderFrame(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y), frame_bb.Max, window->Color(hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button), true, style.FrameRounding); // FIXME-ROUNDING + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + RenderFrame(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y), frame_bb.Max, GetColorU32(popup_open || hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button), true, style.FrameRounding); // FIXME-ROUNDING RenderCollapseTriangle(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y) + style.FramePadding, true); if (*current_item >= 0 && *current_item < items_count) { const char* item_text; if (items_getter(data, *current_item, &item_text)) - RenderTextClipped(frame_bb.Min + style.FramePadding, item_text, NULL, NULL, value_bb.Max); + RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, item_text, NULL, NULL); } if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); - - ImGui::PushID((int)id); - bool menu_toggled = false; + if (hovered) { - g.HoveredId = id; + SetHoveredID(id); if (g.IO.MouseClicked[0]) { - menu_toggled = true; - g.ActiveComboID = (g.ActiveComboID == id) ? 0 : id; - if (g.ActiveComboID) + SetActiveID(0); + if (IsPopupOpen(id)) + { + ClosePopup(id); + } + else + { FocusWindow(window); + OpenPopup(label); + popup_open = popup_opened_now = true; + } } } - - if (g.ActiveComboID == id) + + bool value_changed = false; + if (IsPopupOpen(id)) { // Size default to hold ~7 items if (height_in_items < 0) height_in_items = 7; - const ImVec2 backup_pos = ImGui::GetCursorPos(); - const float popup_off_x = 0.0f;//style.ItemInnerSpacing.x; - const float popup_height = (label_size.y + style.ItemSpacing.y) * ImMin(items_count, height_in_items) + (style.FramePadding.y * 3); - const ImRect popup_rect(ImVec2(frame_bb.Min.x+popup_off_x, frame_bb.Max.y), ImVec2(frame_bb.Max.x+popup_off_x, frame_bb.Max.y + popup_height)); - ImGui::SetCursorPos(popup_rect.Min - window->Pos); + float popup_height = (label_size.y + style.ItemSpacing.y) * ImMin(items_count, height_in_items) + (style.FramePadding.y * 3); + float popup_y1 = frame_bb.Max.y; + float popup_y2 = ImClamp(popup_y1 + popup_height, popup_y1, g.IO.DisplaySize.y - style.DisplaySafeAreaPadding.y); + if ((popup_y2 - popup_y1) < ImMin(popup_height, frame_bb.Min.y - style.DisplaySafeAreaPadding.y)) + { + // Position our combo ABOVE because there's more space to fit! (FIXME: Handle in Begin() or use a shared helper. We have similar code in Begin() for popup placement) + popup_y1 = ImClamp(frame_bb.Min.y - popup_height, style.DisplaySafeAreaPadding.y, frame_bb.Min.y); + popup_y2 = frame_bb.Min.y; + } + ImRect popup_rect(ImVec2(frame_bb.Min.x, popup_y1), ImVec2(frame_bb.Max.x, popup_y2)); + SetNextWindowPos(popup_rect.Min); + SetNextWindowSize(popup_rect.GetSize()); + PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding); const ImGuiWindowFlags flags = ImGuiWindowFlags_ComboBox | ((window->Flags & ImGuiWindowFlags_ShowBorders) ? ImGuiWindowFlags_ShowBorders : 0); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding); - ImGui::BeginChild("#ComboBox", popup_rect.GetSize(), false, flags); - ImGui::Spacing(); - - bool combo_item_active = false; - combo_item_active |= (g.ActiveId == GetCurrentWindow()->GetID("#SCROLLY")); - - // Display items - for (int i = 0; i < items_count; i++) + if (BeginPopupEx(label, flags)) { - ImGui::PushID((void*)(intptr_t)i); - const bool item_selected = (i == *current_item); - const char* item_text; - if (!items_getter(data, i, &item_text)) - item_text = "*Unknown item*"; - if (ImGui::Selectable(item_text, item_selected)) + // Display items + Spacing(); + for (int i = 0; i < items_count; i++) { - SetActiveId(0); - g.ActiveComboID = 0; - value_changed = true; - *current_item = i; + PushID((void*)(intptr_t)i); + const bool item_selected = (i == *current_item); + const char* item_text; + if (!items_getter(data, i, &item_text)) + item_text = "*Unknown item*"; + if (Selectable(item_text, item_selected)) + { + SetActiveID(0); + value_changed = true; + *current_item = i; + } + if (item_selected && popup_opened_now) + SetScrollHere(); + PopID(); } - if (item_selected && menu_toggled) - ImGui::SetScrollPosHere(); - combo_item_active |= ImGui::IsItemActive(); - ImGui::PopID(); + EndPopup(); } - ImGui::EndChild(); - ImGui::PopStyleVar(); - ImGui::SetCursorPos(backup_pos); - - if (!combo_item_active && g.ActiveId != 0) - g.ActiveComboID = 0; + PopStyleVar(); } - - ImGui::PopID(); - return value_changed; } // Tip: pass an empty label (e.g. "##dummy") then you can use the space to draw other text or image. // But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID. -bool ImGui::Selectable(const char* label, bool selected, const ImVec2& size_arg) +bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - const ImGuiID id = window->GetID(label); - const ImVec2 label_size = CalcTextSize(label, NULL, true); - - const float w = ImMax(label_size.x, window->Pos.x + ImGui::GetContentRegionMax().x - style.WindowPadding.x - window->DC.CursorPos.x); - const ImVec2 size(size_arg.x != 0.0f ? size_arg.x : w, size_arg.y != 0.0f ? size_arg.y : label_size.y); - ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); - ItemSize(bb); - if (size_arg.x == 0.0f) - bb.Max.x += style.WindowPadding.x; - // Selectables are meant to be tightly packed together. So for both rendering and collision we extend to compensate for spacing. - ImRect bb_with_spacing = bb; - const float spacing_L = (float)(int)(style.ItemSpacing.x * 0.5f); - const float spacing_U = (float)(int)(style.ItemSpacing.y * 0.5f); - const float spacing_R = style.ItemSpacing.x - spacing_L; - const float spacing_D = style.ItemSpacing.y - spacing_U; + if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1) + PopClipRect(); + + ImGuiID id = window->GetID(label); + ImVec2 label_size = CalcTextSize(label, NULL, true); + ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y); + ImVec2 pos = window->DC.CursorPos; + pos.y += window->DC.CurrentLineTextBaseOffset; + ImRect bb(pos, pos + size); + ItemSize(bb); + + // Fill horizontal space. + ImVec2 window_padding = window->WindowPadding; + float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? GetWindowContentRegionMax().x : GetContentRegionMax().x; + float w_draw = ImMax(label_size.x, window->Pos.x + max_x - window_padding.x - window->DC.CursorPos.x); + ImVec2 size_draw((size_arg.x != 0 && !(flags & ImGuiSelectableFlags_DrawFillAvailWidth)) ? size_arg.x : w_draw, size_arg.y != 0.0f ? size_arg.y : size.y); + ImRect bb_with_spacing(pos, pos + size_draw); + if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth)) + bb_with_spacing.Max.x += window_padding.x; + + // Selectables are tightly packed together, we extend the box to cover spacing between selectable. + float spacing_L = (float)(int)(style.ItemSpacing.x * 0.5f); + float spacing_U = (float)(int)(style.ItemSpacing.y * 0.5f); + float spacing_R = style.ItemSpacing.x - spacing_L; + float spacing_D = style.ItemSpacing.y - spacing_U; bb_with_spacing.Min.x -= spacing_L; bb_with_spacing.Min.y -= spacing_U; bb_with_spacing.Max.x += spacing_R; bb_with_spacing.Max.y += spacing_D; if (!ItemAdd(bb_with_spacing, &id)) + { + if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1) + PushColumnClipRect(); return false; + } + ImGuiButtonFlags button_flags = 0; + if (flags & ImGuiSelectableFlags_Menu) button_flags |= ImGuiButtonFlags_PressedOnClick; + if (flags & ImGuiSelectableFlags_MenuItem) button_flags |= ImGuiButtonFlags_PressedOnClick|ImGuiButtonFlags_PressedOnRelease; + if (flags & ImGuiSelectableFlags_Disabled) button_flags |= ImGuiButtonFlags_Disabled; + if (flags & ImGuiSelectableFlags_AllowDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; bool hovered, held; - bool pressed = ButtonBehavior(bb_with_spacing, id, &hovered, &held, true); + bool pressed = ButtonBehavior(bb_with_spacing, id, &hovered, &held, button_flags); + if (flags & ImGuiSelectableFlags_Disabled) + selected = false; // Render if (hovered || selected) { - const ImU32 col = window->Color((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); - RenderFrame(bb_with_spacing.Min, bb_with_spacing.Max, col, false, style.FrameRounding); + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + RenderFrame(bb_with_spacing.Min, bb_with_spacing.Max, col, false, 0.0f); } - //const ImVec2 off = ImVec2(ImMax(0.0f, size.x - text_size.x) * 0.5f, ImMax(0.0f, size.y - text_size.y) * 0.5f); - RenderTextClipped(bb.Min, label, NULL, &label_size, bb_with_spacing.Max); + if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1) + { + PushColumnClipRect(); + bb_with_spacing.Max.x -= (GetContentRegionMax().x - max_x); + } + if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); + RenderTextClipped(bb.Min, bb_with_spacing.Max, label, NULL, &label_size); + if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor(); + + // Automatically close popups + if (pressed && !(flags & ImGuiSelectableFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) + CloseCurrentPopup(); return pressed; } -bool ImGui::Selectable(const char* label, bool* p_selected, const ImVec2& size_arg) +bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) { - if (ImGui::Selectable(label, *p_selected, size_arg)) + if (Selectable(label, *p_selected, flags, size_arg)) { *p_selected = !*p_selected; return true; @@ -7125,25 +8532,25 @@ bool ImGui::Selectable(const char* label, bool* p_selected, const ImVec2& size_a bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg) { ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; - const ImGuiStyle& style = ImGui::GetStyle(); - const ImGuiID id = ImGui::GetID(label); - const ImVec2 label_size = ImGui::CalcTextSize(label, NULL, true); + const ImGuiStyle& style = GetStyle(); + const ImGuiID id = GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. - ImVec2 size; - size.x = (size_arg.x != 0.0f) ? (size_arg.x) : ImGui::CalcItemWidth() + style.FramePadding.x * 2.0f; - size.y = (size_arg.y != 0.0f) ? (size_arg.y) : ImGui::GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y; - const ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y)); - const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); - const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y); + ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y)); + ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); + ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); window->DC.LastItemRect = bb; - ImGui::BeginGroup(); + BeginGroup(); if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); - ImGui::BeginChildFrame(id, frame_bb.GetSize()); + BeginChildFrame(id, frame_bb.GetSize()); return true; } @@ -7159,24 +8566,24 @@ bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_item // We include ItemSpacing.y so that a list sized for the exact number of items doesn't make a scrollbar appears. We could also enforce that by passing a flag to BeginChild(). ImVec2 size; size.x = 0.0f; - size.y = ImGui::GetTextLineHeightWithSpacing() * height_in_items_f + ImGui::GetStyle().ItemSpacing.y; - return ImGui::ListBoxHeader(label, size); + size.y = GetTextLineHeightWithSpacing() * height_in_items_f + GetStyle().ItemSpacing.y; + return ListBoxHeader(label, size); } void ImGui::ListBoxFooter() { ImGuiWindow* parent_window = GetParentWindow(); const ImRect bb = parent_window->DC.LastItemRect; - const ImGuiStyle& style = ImGui::GetStyle(); - - ImGui::EndChildFrame(); + const ImGuiStyle& style = GetStyle(); + + EndChildFrame(); // Redeclare item size so that it includes the label (we have stored the full size in LastItemRect) // We call SameLine() to restore DC.CurrentLine* data - ImGui::SameLine(); + SameLine(); parent_window->DC.CursorPos = bb.Min; ItemSize(bb, style.FramePadding.y); - ImGui::EndGroup(); + EndGroup(); } bool ImGui::ListBox(const char* label, int* current_item, const char** items, int items_count, int height_items) @@ -7187,61 +8594,62 @@ bool ImGui::ListBox(const char* label, int* current_item, const char** items, in bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items) { - ImGuiWindow* window = GetCurrentWindow(); - if (window->SkipItems) - return false; - - if (!ImGui::ListBoxHeader(label, items_count, height_in_items)) + if (!ListBoxHeader(label, items_count, height_in_items)) return false; + // Assume all items have even height (= 1 line of text). If you need items of different or variable sizes you can create a custom version of ListBox() in your code without using the clipper. bool value_changed = false; - for (int i = 0; i < items_count; i++) - { - const bool item_selected = (i == *current_item); - const char* item_text; - if (!items_getter(data, i, &item_text)) - item_text = "*Unknown item*"; - - ImGui::PushID(i); - if (ImGui::Selectable(item_text, item_selected)) + ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing()); + while (clipper.Step()) + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) { - *current_item = i; - value_changed = true; - } - ImGui::PopID(); - } + const bool item_selected = (i == *current_item); + const char* item_text; + if (!items_getter(data, i, &item_text)) + item_text = "*Unknown item*"; - ImGui::ListBoxFooter(); + PushID(i); + if (Selectable(item_text, item_selected)) + { + *current_item = i; + value_changed = true; + } + PopID(); + } + ListBoxFooter(); return value_changed; } -bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected) +bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled) { - (void)shortcut; // FIXME-MENU: Shortcut are not supported yet. Argument is reserved. - - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; - ImVec2 pos = ImGui::GetCursorScreenPos(); - const ImVec2 label_size = CalcTextSize(label, NULL, true); - const float symbol_spacing = (float)(int)(g.FontSize * 1.50f + 0.5f); - const float w = ImMax(label_size.x + symbol_spacing, window->Pos.x + ImGui::GetContentRegionMax().x - window->DC.CursorPos.x); // Feedback to next frame - bool ret = ImGui::Selectable(label, false, ImVec2(w, 0.0f)); + ImGuiContext& g = *GImGui; + ImVec2 pos = window->DC.CursorPos; + ImVec2 label_size = CalcTextSize(label, NULL, true); + ImVec2 shortcut_size = shortcut ? CalcTextSize(shortcut, NULL) : ImVec2(0.0f, 0.0f); + float w = window->MenuColumns.DeclColumns(label_size.x, shortcut_size.x, (float)(int)(g.FontSize * 1.20f)); // Feedback for next frame + float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w); - if (selected) + bool pressed = Selectable(label, false, ImGuiSelectableFlags_MenuItem | ImGuiSelectableFlags_DrawFillAvailWidth | (enabled ? 0 : ImGuiSelectableFlags_Disabled), ImVec2(w, 0.0f)); + if (shortcut_size.x > 0.0f) { - pos.x = window->Pos.x + ImGui::GetContentRegionMax().x - g.FontSize; - RenderCheckMark(pos, window->Color(ImGuiCol_Text)); + PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); + RenderText(pos + ImVec2(window->MenuColumns.Pos[1] + extra_w, 0.0f), shortcut, NULL, false); + PopStyleColor(); } - return ret; + if (selected) + RenderCheckMark(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled)); + + return pressed; } -bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected) +bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled) { - if (ImGui::MenuItem(label, shortcut, p_selected ? *p_selected : false)) + if (MenuItem(label, shortcut, p_selected ? *p_selected : false, enabled)) { if (p_selected) *p_selected = !*p_selected; @@ -7250,34 +8658,200 @@ bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected) return false; } -// A little colored square. Return true when clicked. -bool ImGui::ColorButton(const ImVec4& col, bool small_height, bool outline_border) +bool ImGui::BeginMainMenuBar() +{ + ImGuiContext& g = *GImGui; + SetNextWindowPos(ImVec2(0.0f, 0.0f)); + SetNextWindowSize(ImVec2(g.IO.DisplaySize.x, g.FontBaseSize + g.Style.FramePadding.y * 2.0f)); + PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); + PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0,0)); + if (!Begin("##MainMenuBar", NULL, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoScrollbar|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_MenuBar) + || !BeginMenuBar()) + { + End(); + PopStyleVar(2); + return false; + } + g.CurrentWindow->DC.MenuBarOffsetX += g.Style.DisplaySafeAreaPadding.x; + return true; +} + +void ImGui::EndMainMenuBar() +{ + EndMenuBar(); + End(); + PopStyleVar(2); +} + +bool ImGui::BeginMenuBar() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + if (!(window->Flags & ImGuiWindowFlags_MenuBar)) + return false; + + IM_ASSERT(!window->DC.MenuBarAppending); + BeginGroup(); // Save position + PushID("##menubar"); + ImRect rect = window->MenuBarRect(); + PushClipRect(ImVec2(ImFloor(rect.Min.x+0.5f), ImFloor(rect.Min.y + window->BorderSize + 0.5f)), ImVec2(ImFloor(rect.Max.x+0.5f), ImFloor(rect.Max.y+0.5f)), false); + window->DC.CursorPos = ImVec2(rect.Min.x + window->DC.MenuBarOffsetX, rect.Min.y);// + g.Style.FramePadding.y); + window->DC.LayoutType = ImGuiLayoutType_Horizontal; + window->DC.MenuBarAppending = true; + AlignFirstTextHeightToWidgets(); + return true; +} + +void ImGui::EndMenuBar() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar); + IM_ASSERT(window->DC.MenuBarAppending); + PopClipRect(); + PopID(); + window->DC.MenuBarOffsetX = window->DC.CursorPos.x - window->MenuBarRect().Min.x; + window->DC.GroupStack.back().AdvanceCursor = false; + EndGroup(); + window->DC.LayoutType = ImGuiLayoutType_Vertical; + window->DC.MenuBarAppending = false; +} + +bool ImGui::BeginMenu(const char* label, bool enabled) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + + ImVec2 label_size = CalcTextSize(label, NULL, true); + ImGuiWindow* backed_focused_window = g.FocusedWindow; + + bool pressed; + bool menu_is_open = IsPopupOpen(id); + bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentMenuSet == window->GetID("##menus")); + if (menuset_is_open) + g.FocusedWindow = window; + + ImVec2 popup_pos, pos = window->DC.CursorPos; + if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) + { + popup_pos = ImVec2(pos.x - window->WindowPadding.x, pos.y - style.FramePadding.y + window->MenuBarHeight()); + window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f); + PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f); + float w = label_size.x; + pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f)); + PopStyleVar(); + SameLine(); + window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f); + } + else + { + popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y); + float w = window->MenuColumns.DeclColumns(label_size.x, 0.0f, (float)(int)(g.FontSize * 1.20f)); // Feedback to next frame + float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w); + pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f)); + if (!enabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); + RenderCollapseTriangle(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), false); + if (!enabled) PopStyleColor(); + } + + bool hovered = enabled && IsHovered(window->DC.LastItemRect, id); + if (menuset_is_open) + g.FocusedWindow = backed_focused_window; + + bool want_open = false, want_close = false; + if (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) + { + // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive. + bool moving_within_opened_triangle = false; + if (g.HoveredWindow == window && g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentWindow == window) + { + if (ImGuiWindow* next_window = g.OpenPopupStack[g.CurrentPopupStack.Size].Window) + { + ImRect next_window_rect = next_window->Rect(); + ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta; + ImVec2 tb = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR(); + ImVec2 tc = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR(); + float extra = ImClamp(fabsf(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack. + ta.x += (window->Pos.x < next_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues + tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -100.0f); // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale? + tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f); + moving_within_opened_triangle = ImIsPointInTriangle(g.IO.MousePos, ta, tb, tc); + //window->DrawList->PushClipRectFullScreen(); window->DrawList->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? 0x80008000 : 0x80000080); window->DrawList->PopClipRect(); // Debug + } + } + + want_close = (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_within_opened_triangle); + want_open = (!menu_is_open && hovered && !moving_within_opened_triangle) || (!menu_is_open && hovered && pressed); + } + else if (menu_is_open && pressed && menuset_is_open) // menu-bar: click open menu to close + { + want_close = true; + want_open = menu_is_open = false; + } + else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // menu-bar: first click to open, then hover to open others + want_open = true; + if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }' + want_close = true; + if (want_close && IsPopupOpen(id)) + ClosePopupToLevel(GImGui->CurrentPopupStack.Size); + + if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.CurrentPopupStack.Size) + { + // Don't recycle same menu level in the same frame, first close the other menu and yield for a frame. + OpenPopup(label); + return false; + } + + menu_is_open |= want_open; + if (want_open) + OpenPopup(label); + + if (menu_is_open) + { + SetNextWindowPos(popup_pos, ImGuiSetCond_Always); + ImGuiWindowFlags flags = ImGuiWindowFlags_ShowBorders | ((window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) ? ImGuiWindowFlags_ChildMenu|ImGuiWindowFlags_ChildWindow : ImGuiWindowFlags_ChildMenu); + menu_is_open = BeginPopupEx(label, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + } + + return menu_is_open; +} + +void ImGui::EndMenu() +{ + EndPopup(); +} + +// A little colored square. Return true when clicked. +// FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip. +bool ImGui::ColorButton(const ImVec4& col, bool small_height, bool outline_border) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID("#colorbutton"); const float square_size = g.FontSize; - const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(square_size + style.FramePadding.x*2, square_size + (small_height ? 0 : style.FramePadding.y*2))); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(square_size + style.FramePadding.y*2, square_size + (small_height ? 0 : style.FramePadding.y*2))); ItemSize(bb, small_height ? 0.0f : style.FramePadding.y); if (!ItemAdd(bb, &id)) return false; bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held, true); - RenderFrame(bb.Min, bb.Max, window->Color(col), outline_border, style.FrameRounding); + bool pressed = ButtonBehavior(bb, id, &hovered, &held); + RenderFrame(bb.Min, bb.Max, GetColorU32(col), outline_border, style.FrameRounding); if (hovered) - { - int ix = (int)(col.x * 255.0f + 0.5f); - int iy = (int)(col.y * 255.0f + 0.5f); - int iz = (int)(col.z * 255.0f + 0.5f); - int iw = (int)(col.w * 255.0f + 0.5f); - ImGui::SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col.x, col.y, col.z, col.w, ix, iy, iz, iw); - } + SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col.x, col.y, col.z, col.w, IM_F32_TO_INT8(col.x), IM_F32_TO_INT8(col.y), IM_F32_TO_INT8(col.z), IM_F32_TO_INT8(col.z)); return pressed; } @@ -7289,7 +8863,7 @@ bool ImGui::ColorEdit3(const char* label, float col[3]) col4[1] = col[1]; col4[2] = col[2]; col4[3] = 1.0f; - const bool value_changed = ImGui::ColorEdit4(label, col4, false); + const bool value_changed = ColorEdit4(label, col4, false); col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2]; @@ -7300,32 +8874,31 @@ bool ImGui::ColorEdit3(const char* label, float col[3]) // Use CTRL-Click to input value and TAB to go to next item. bool ImGui::ColorEdit4(const char* label, float col[4], bool alpha) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); - const float w_full = ImGui::CalcItemWidth(); - const float square_sz = (g.FontSize + style.FramePadding.x * 2.0f); + const float w_full = CalcItemWidth(); + const float square_sz = (g.FontSize + style.FramePadding.y * 2.0f); ImGuiColorEditMode edit_mode = window->DC.ColorEditMode; if (edit_mode == ImGuiColorEditMode_UserSelect || edit_mode == ImGuiColorEditMode_UserSelectShowButton) edit_mode = g.ColorEditModeStorage.GetInt(id, 0) % 3; float f[4] = { col[0], col[1], col[2], col[3] }; - if (edit_mode == ImGuiColorEditMode_HSV) - ImGui::ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]); + ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]); - int i[4] = { (int)(f[0] * 255.0f + 0.5f), (int)(f[1] * 255.0f + 0.5f), (int)(f[2] * 255.0f + 0.5f), (int)(f[3] * 255.0f + 0.5f) }; + int i[4] = { IM_F32_TO_INT8(f[0]), IM_F32_TO_INT8(f[1]), IM_F32_TO_INT8(f[2]), IM_F32_TO_INT8(f[3]) }; int components = alpha ? 4 : 3; bool value_changed = false; - ImGui::BeginGroup(); - ImGui::PushID(label); + BeginGroup(); + PushID(label); const bool hsv = (edit_mode == 1); switch (edit_mode) @@ -7335,30 +8908,30 @@ bool ImGui::ColorEdit4(const char* label, float col[4], bool alpha) { // RGB/HSV 0..255 Sliders const float w_items_all = w_full - (square_sz + style.ItemInnerSpacing.x); - const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.FramePadding.x*2.0f + style.ItemInnerSpacing.x) * (components-1)) / (float)components)); - const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.FramePadding.x*2.0f + style.ItemInnerSpacing.x) * (components-1))); + const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); + const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); const bool hide_prefix = (w_item_one <= CalcTextSize("M:999").x); const char* ids[4] = { "##X", "##Y", "##Z", "##W" }; - const char* fmt_table[3][4] = + const char* fmt_table[3][4] = { - { "%3.0f", "%3.0f", "%3.0f", "%3.0f" }, + { "%3.0f", "%3.0f", "%3.0f", "%3.0f" }, { "R:%3.0f", "G:%3.0f", "B:%3.0f", "A:%3.0f" }, - { "H:%3.0f", "S:%3.0f", "V:%3.0f", "A:%3.0f" } + { "H:%3.0f", "S:%3.0f", "V:%3.0f", "A:%3.0f" } }; - const char** fmt = hide_prefix ? fmt_table[0] : hsv ? fmt_table[2] : fmt_table[1]; + const char** fmt = hide_prefix ? fmt_table[0] : hsv ? fmt_table[2] : fmt_table[1]; - ImGui::PushItemWidth(w_item_one); + PushItemWidth(w_item_one); for (int n = 0; n < components; n++) { if (n > 0) - ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); + SameLine(0, style.ItemInnerSpacing.x); if (n + 1 == components) - ImGui::PushItemWidth(w_item_last); - value_changed |= ImGui::DragInt(ids[n], &i[n], 1.0f, 0, 255, fmt[n]); + PushItemWidth(w_item_last); + value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, 255, fmt[n]); } - ImGui::PopItemWidth(); - ImGui::PopItemWidth(); + PopItemWidth(); + PopItemWidth(); } break; case ImGuiColorEditMode_HEX: @@ -7370,49 +8943,54 @@ bool ImGui::ColorEdit4(const char* label, float col[4], bool alpha) ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", i[0], i[1], i[2], i[3]); else ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", i[0], i[1], i[2]); - ImGui::PushItemWidth(w_slider_all - style.ItemInnerSpacing.x); - value_changed |= ImGui::InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); - ImGui::PopItemWidth(); - char* p = buf; - while (*p == '#' || ImCharIsSpace(*p)) - p++; - - // Treat at unsigned (%X is unsigned) - i[0] = i[1] = i[2] = i[3] = 0; - if (alpha) - sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); - else - sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]); + PushItemWidth(w_slider_all - style.ItemInnerSpacing.x); + if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase)) + { + value_changed |= true; + char* p = buf; + while (*p == '#' || ImCharIsSpace(*p)) + p++; + i[0] = i[1] = i[2] = i[3] = 0; + if (alpha) + sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); // Treat at unsigned (%X is unsigned) + else + sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]); + } + PopItemWidth(); } break; } - ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); + SameLine(0, style.ItemInnerSpacing.x); const ImVec4 col_display(col[0], col[1], col[2], 1.0f); - if (ImGui::ColorButton(col_display)) + if (ColorButton(col_display)) g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away! + // Recreate our own tooltip over's ColorButton() one because we want to display correct alpha here + if (IsItemHovered()) + SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col[0], col[1], col[2], col[3], IM_F32_TO_INT8(col[0]), IM_F32_TO_INT8(col[1]), IM_F32_TO_INT8(col[2]), IM_F32_TO_INT8(col[3])); + if (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton) { - ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); + SameLine(0, style.ItemInnerSpacing.x); const char* button_titles[3] = { "RGB", "HSV", "HEX" }; - if (ImGui::Button(button_titles[edit_mode])) + if (ButtonEx(button_titles[edit_mode], ImVec2(0,0), ImGuiButtonFlags_DontClosePopups)) g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away! - ImGui::SameLine(); - } - else - { - ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); } - ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); + const char* label_display_end = FindRenderedTextEnd(label); + if (label != label_display_end) + { + SameLine(0, (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton) ? -1.0f : style.ItemInnerSpacing.x); + TextUnformatted(label, label_display_end); + } // Convert back for (int n = 0; n < 4; n++) f[n] = i[n] / 255.0f; if (edit_mode == 1) - ImGui::ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); + ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); if (value_changed) { @@ -7423,8 +9001,8 @@ bool ImGui::ColorEdit4(const char* label, float col[4], bool alpha) col[3] = f[3]; } - ImGui::PopID(); - ImGui::EndGroup(); + PopID(); + EndGroup(); return value_changed; } @@ -7448,10 +9026,10 @@ void ImGui::Separator() float x1 = window->Pos.x; float x2 = window->Pos.x + window->Size.x; if (!window->DC.GroupStack.empty()) - x1 += window->DC.ColumnsStartX; + x1 += window->DC.IndentX; const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y)); - ItemSize(ImVec2(0.0f, bb.GetSize().y)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit + ItemSize(ImVec2(0.0f, 0.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit // FIXME: Height should be 1.0f not 0.0f ? if (!ItemAdd(bb, NULL)) { if (window->DC.ColumnsCount > 1) @@ -7459,11 +9037,11 @@ void ImGui::Separator() return; } - window->DrawList->AddLine(bb.Min, bb.Max, window->Color(ImGuiCol_Border)); + window->DrawList->AddLine(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border)); - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; if (g.LogEnabled) - ImGui::LogText(STR_NEWLINE "--------------------------------"); + LogText(IM_NEWLINE "--------------------------------"); if (window->DC.ColumnsCount > 1) { @@ -7472,110 +9050,47 @@ void ImGui::Separator() } } -// A little vertical spacing. void ImGui::Spacing() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; - ItemSize(ImVec2(0,0)); } -// Advance cursor given item size. -static void ItemSize(ImVec2 size, float text_offset_y) +void ImGui::Dummy(const ImVec2& size) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; - // Always align ourselves on pixel boundaries - const float line_height = ImMax(window->DC.CurrentLineHeight, size.y); - const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y); - window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y); - window->DC.CursorPos = ImVec2((float)(int)(window->Pos.x + window->DC.ColumnsStartX + window->DC.ColumnsOffsetX), (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y)); - window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x); - window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); - - //window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, 0xFF0000FF, 4); // Debug - - window->DC.PrevLineHeight = line_height; - window->DC.PrevLineTextBaseOffset = text_base_offset; - window->DC.CurrentLineHeight = window->DC.CurrentLineTextBaseOffset = 0.0f; + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + ItemSize(bb); + ItemAdd(bb, NULL); } -static inline void ItemSize(const ImRect& bb, float text_offset_y) -{ - ItemSize(bb.GetSize(), text_offset_y); -} - -static bool IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged) +bool ImGui::IsRectVisible(const ImVec2& size) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - - if (!bb.Overlaps(ImRect(window->ClipRectStack.back()))) - { - if (!id || *id != GImGui->ActiveId) - if (clip_even_when_logged || !g.LogEnabled) - return true; - } - return false; -} - -bool ImGui::IsRectClipped(const ImVec2& size) -{ - ImGuiWindow* window = GetCurrentWindow(); - return IsClippedEx(ImRect(window->DC.CursorPos, window->DC.CursorPos + size), NULL, true); -} - -static bool ItemAdd(const ImRect& bb, const ImGuiID* id) -{ - ImGuiWindow* window = GetCurrentWindow(); - window->DC.LastItemID = id ? *id : 0; - window->DC.LastItemRect = bb; - if (IsClippedEx(bb, id, false)) - { - window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = false; - return false; - } - - // This is a sensible default, but widgets are free to override it after calling ItemAdd() - ImGuiState& g = *GImGui; - if (IsMouseHoveringRect(bb)) - { - // Matching the behavior of IsHovered() but ignore if ActiveId==window->MoveID (we clicked on the window background) - // So that clicking on items with no active id such as Text() still returns true with IsItemHovered() - window->DC.LastItemHoveredRect = true; - window->DC.LastItemHoveredAndUsable = false; - if (g.HoveredRootWindow == window->RootWindow) - if (g.ActiveId == 0 || (id && g.ActiveId == *id) || g.ActiveIdIsFocusedOnly || (g.ActiveId == window->MoveID)) - if (IsWindowContentHoverable(window)) - window->DC.LastItemHoveredAndUsable = true; - } - else - { - window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = false; - } - - return true; + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size)); } +// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) void ImGui::BeginGroup() { ImGuiWindow* window = GetCurrentWindow(); - window->DC.GroupStack.resize(window->DC.GroupStack.size() + 1); + window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1); ImGuiGroupData& group_data = window->DC.GroupStack.back(); group_data.BackupCursorPos = window->DC.CursorPos; group_data.BackupCursorMaxPos = window->DC.CursorMaxPos; - group_data.BackupColumnsStartX = window->DC.ColumnsStartX; + group_data.BackupIndentX = window->DC.IndentX; group_data.BackupCurrentLineHeight = window->DC.CurrentLineHeight; group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset; group_data.BackupLogLinePosY = window->DC.LogLinePosY; + group_data.AdvanceCursor = true; - window->DC.ColumnsStartX = window->DC.CursorPos.x - window->Pos.x; + window->DC.IndentX = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffsetX; window->DC.CursorMaxPos = window->DC.CursorPos; window->DC.CurrentLineHeight = 0.0f; window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; @@ -7584,9 +9099,9 @@ void ImGui::BeginGroup() void ImGui::EndGroup() { ImGuiWindow* window = GetCurrentWindow(); - ImGuiStyle& style = ImGui::GetStyle(); + ImGuiStyle& style = GetStyle(); - IM_ASSERT(!window->DC.GroupStack.empty()); + IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls ImGuiGroupData& group_data = window->DC.GroupStack.back(); @@ -7597,12 +9112,16 @@ void ImGui::EndGroup() window->DC.CursorPos = group_data.BackupCursorPos; window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos); window->DC.CurrentLineHeight = group_data.BackupCurrentLineHeight; - window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset; // FIXME: Ideally we'll grab the base offset from the first line of the group. - window->DC.ColumnsStartX = group_data.BackupColumnsStartX; + window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset; + window->DC.IndentX = group_data.BackupIndentX; window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; - ItemSize(group_bb.GetSize(), group_data.BackupCurrentLineTextBaseOffset); - ItemAdd(group_bb, NULL); + if (group_data.AdvanceCursor) + { + window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrentLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now. + ItemSize(group_bb.GetSize(), group_data.BackupCurrentLineTextBaseOffset); + ItemAdd(group_bb, NULL); + } window->DC.GroupStack.pop_back(); @@ -7610,100 +9129,111 @@ void ImGui::EndGroup() } // Gets back to previous line and continue with horizontal layout -// column_x == 0 : follow on previous item -// columm_x != 0 : align to specified column +// pos_x == 0 : follow on previous item +// pos_x != 0 : align to specified column // spacing_w < 0 : use default spacing if column_x==0, no spacing if column_x!=0 // spacing_w >= 0 : enforce spacing -void ImGui::SameLine(int column_x, int spacing_w) +void ImGui::SameLine(float pos_x, float spacing_w) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; - - float x, y; - if (column_x != 0) + + ImGuiContext& g = *GImGui; + if (pos_x != 0.0f) { - if (spacing_w < 0) spacing_w = 0; - x = window->Pos.x + (float)column_x + (float)spacing_w; - y = window->DC.CursorPosPrevLine.y; + if (spacing_w < 0.0f) spacing_w = 0.0f; + window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + pos_x + spacing_w; + window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; } else { - if (spacing_w < 0) spacing_w = (int)g.Style.ItemSpacing.x; - x = window->DC.CursorPosPrevLine.x + (float)spacing_w; - y = window->DC.CursorPosPrevLine.y; + if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x; + window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w; + window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; } window->DC.CurrentLineHeight = window->DC.PrevLineHeight; window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset; - window->DC.CursorPos = ImVec2(x, y); +} + +void ImGui::NewLine() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + if (window->DC.CurrentLineHeight > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height. + ItemSize(ImVec2(0,0)); + else + ItemSize(ImVec2(0.0f, GImGui->FontSize)); } void ImGui::NextColumn() { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; + ImGuiContext& g = *GImGui; if (window->DC.ColumnsCount > 1) { - ImGui::PopItemWidth(); + PopItemWidth(); PopClipRect(); window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y); if (++window->DC.ColumnsCurrent < window->DC.ColumnsCount) { - window->DC.ColumnsOffsetX = ImGui::GetColumnOffset(window->DC.ColumnsCurrent) - window->DC.ColumnsStartX + g.Style.ItemSpacing.x; + // Columns 1+ cancel out IndentX + window->DC.ColumnsOffsetX = GetColumnOffset(window->DC.ColumnsCurrent) - window->DC.IndentX + g.Style.ItemSpacing.x; + window->DrawList->ChannelsSetCurrent(window->DC.ColumnsCurrent); } else { window->DC.ColumnsCurrent = 0; window->DC.ColumnsOffsetX = 0.0f; window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY; + window->DrawList->ChannelsSetCurrent(0); } - window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.ColumnsStartX + window->DC.ColumnsOffsetX); + window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX); window->DC.CursorPos.y = window->DC.ColumnsCellMinY; window->DC.CurrentLineHeight = 0.0f; window->DC.CurrentLineTextBaseOffset = 0.0f; PushColumnClipRect(); - ImGui::PushItemWidth(ImGui::GetColumnWidth() * 0.65f); // FIXME + PushItemWidth(GetColumnWidth() * 0.65f); // FIXME: Move on columns setup } } int ImGui::GetColumnIndex() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.ColumnsCurrent; } int ImGui::GetColumnsCount() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.ColumnsCount; } static float GetDraggedColumnOffset(int column_index) { // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing - // window creates a feedback loop because we store normalized positions/ So while dragging we enforce absolute positioning - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); + // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning. + ImGuiContext& g = *GImGui; + ImGuiWindow* window = ImGui::GetCurrentWindowRead(); IM_ASSERT(column_index > 0); // We cannot drag column 0. If you get this assert you may have a conflict between the ID of your columns and another widgets. IM_ASSERT(g.ActiveId == window->DC.ColumnsSetID + ImGuiID(column_index)); - float x = g.IO.MousePos.x + g.ActiveClickDeltaToCenter.x; - x -= window->Pos.x; + float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x - window->Pos.x; x = ImClamp(x, ImGui::GetColumnOffset(column_index-1)+g.Style.ColumnsMinSpacing, ImGui::GetColumnOffset(column_index+1)-g.Style.ColumnsMinSpacing); - return x; + return (float)(int)x; } float ImGui::GetColumnOffset(int column_index) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindowRead(); if (column_index < 0) column_index = window->DC.ColumnsCurrent; @@ -7714,65 +9244,60 @@ float ImGui::GetColumnOffset(int column_index) return GetDraggedColumnOffset(column_index); } - // Read from cache - IM_ASSERT(column_index < (int)window->DC.ColumnsOffsetsT.size()); - const float t = window->DC.ColumnsOffsetsT[column_index]; - - const float min_x = window->DC.ColumnsStartX; - const float max_x = window->Size.x - (g.Style.ScrollbarWidth);// - window->WindowPadding().x; - const float offset = min_x + t * (max_x - min_x); - return offset; + IM_ASSERT(column_index < window->DC.ColumnsData.Size); + const float t = window->DC.ColumnsData[column_index].OffsetNorm; + const float x_offset = window->DC.ColumnsMinX + t * (window->DC.ColumnsMaxX - window->DC.ColumnsMinX); + return (float)(int)x_offset; } void ImGui::SetColumnOffset(int column_index, float offset) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (column_index < 0) column_index = window->DC.ColumnsCurrent; - IM_ASSERT(column_index < (int)window->DC.ColumnsOffsetsT.size()); - const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(column_index); + IM_ASSERT(column_index < window->DC.ColumnsData.Size); + const float t = (offset - window->DC.ColumnsMinX) / (window->DC.ColumnsMaxX - window->DC.ColumnsMinX); + window->DC.ColumnsData[column_index].OffsetNorm = t; - const float min_x = window->DC.ColumnsStartX; - const float max_x = window->Size.x - (g.Style.ScrollbarWidth);// - window->WindowPadding().x; - const float t = (offset - min_x) / (max_x - min_x); + const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(column_index); window->DC.StateStorage->SetFloat(column_id, t); - window->DC.ColumnsOffsetsT[column_index] = t; } float ImGui::GetColumnWidth(int column_index) { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); if (column_index < 0) column_index = window->DC.ColumnsCurrent; - const float w = GetColumnOffset(column_index+1) - GetColumnOffset(column_index); + float w = GetColumnOffset(column_index+1) - GetColumnOffset(column_index); return w; } static void PushColumnClipRect(int column_index) { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = ImGui::GetCurrentWindow(); if (column_index < 0) column_index = window->DC.ColumnsCurrent; - const float x1 = window->Pos.x + ImGui::GetColumnOffset(column_index) - 1; - const float x2 = window->Pos.x + ImGui::GetColumnOffset(column_index+1) - 1; - PushClipRect(ImVec4(x1,-FLT_MAX,x2,+FLT_MAX)); + float x1 = ImFloor(0.5f + window->Pos.x + ImGui::GetColumnOffset(column_index) - 1.0f); + float x2 = ImFloor(0.5f + window->Pos.x + ImGui::GetColumnOffset(column_index+1) - 1.0f); + ImGui::PushClipRect(ImVec2(x1,-FLT_MAX), ImVec2(x2,+FLT_MAX), true); } void ImGui::Columns(int columns_count, const char* id, bool border) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); + IM_ASSERT(columns_count >= 1); if (window->DC.ColumnsCount != 1) { if (window->DC.ColumnsCurrent != 0) ItemSize(ImVec2(0,0)); // Advance to column 0 - ImGui::PopItemWidth(); + PopItemWidth(); PopClipRect(); + window->DrawList->ChannelsMerge(); window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y); window->DC.CursorPos.y = window->DC.ColumnsCellMaxY; @@ -7781,95 +9306,97 @@ void ImGui::Columns(int columns_count, const char* id, bool border) // Draw columns borders and handle resize at the time of "closing" a columns set if (window->DC.ColumnsCount != columns_count && window->DC.ColumnsCount != 1 && window->DC.ColumnsShowBorders && !window->SkipItems) { - const float y1 = window->DC.ColumnsStartPos.y; + const float y1 = window->DC.ColumnsStartPosY; const float y2 = window->DC.CursorPos.y; for (int i = 1; i < window->DC.ColumnsCount; i++) { float x = window->Pos.x + GetColumnOffset(i); - const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(i); const ImRect column_rect(ImVec2(x-4,y1),ImVec2(x+4,y2)); - if (IsClippedEx(column_rect, &column_id, false)) continue; bool hovered, held; - ButtonBehavior(column_rect, column_id, &hovered, &held, true); + ButtonBehavior(column_rect, column_id, &hovered, &held); if (hovered || held) g.MouseCursor = ImGuiMouseCursor_ResizeEW; // Draw before resize so our items positioning are in sync with the line being drawn - const ImU32 col = window->Color(held ? ImGuiCol_ColumnActive : hovered ? ImGuiCol_ColumnHovered : ImGuiCol_Column); + const ImU32 col = GetColorU32(held ? ImGuiCol_ColumnActive : hovered ? ImGuiCol_ColumnHovered : ImGuiCol_Column); const float xi = (float)(int)x; - window->DrawList->AddLine(ImVec2(xi, y1), ImVec2(xi, y2), col); + window->DrawList->AddLine(ImVec2(xi, y1+1.0f), ImVec2(xi, y2), col); if (held) { if (g.ActiveIdIsJustActivated) - g.ActiveClickDeltaToCenter.x = x - g.IO.MousePos.x; - + g.ActiveIdClickOffset.x -= 4; // Store from center of column line x = GetDraggedColumnOffset(i); SetColumnOffset(i, x); } } } + // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget. + // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer. + PushID(0x11223347 + (id ? 0 : columns_count)); + window->DC.ColumnsSetID = window->GetID(id ? id : "columns"); + PopID(); + // Set state for first column - ImGui::PushID(0x11223344); // Differentiate column ID with an arbitrary/random prefix for cases where users name their columns set the same as another non-scope widget - window->DC.ColumnsSetID = window->GetID(id ? id : ""); - ImGui::PopID(); window->DC.ColumnsCurrent = 0; window->DC.ColumnsCount = columns_count; window->DC.ColumnsShowBorders = border; - window->DC.ColumnsStartPos = window->DC.CursorPos; + + const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : window->Size.x; + window->DC.ColumnsMinX = window->DC.IndentX; // Lock our horizontal range + window->DC.ColumnsMaxX = content_region_width - window->Scroll.x - ((window->Flags & ImGuiWindowFlags_NoScrollbar) ? 0 : g.Style.ScrollbarSize);// - window->WindowPadding().x; + window->DC.ColumnsStartPosY = window->DC.CursorPos.y; window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.CursorPos.y; window->DC.ColumnsOffsetX = 0.0f; - window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.ColumnsStartX + window->DC.ColumnsOffsetX); + window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX); if (window->DC.ColumnsCount != 1) { // Cache column offsets - window->DC.ColumnsOffsetsT.resize((size_t)columns_count + 1); + window->DC.ColumnsData.resize(columns_count + 1); for (int column_index = 0; column_index < columns_count + 1; column_index++) { const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(column_index); - RegisterAliveId(column_id); + KeepAliveID(column_id); const float default_t = column_index / (float)window->DC.ColumnsCount; const float t = window->DC.StateStorage->GetFloat(column_id, default_t); // Cheaply store our floating point value inside the integer (could store an union into the map?) - window->DC.ColumnsOffsetsT[column_index] = t; + window->DC.ColumnsData[column_index].OffsetNorm = t; } - + window->DrawList->ChannelsSplit(window->DC.ColumnsCount); PushColumnClipRect(); - ImGui::PushItemWidth(ImGui::GetColumnWidth() * 0.65f); + PushItemWidth(GetColumnWidth() * 0.65f); } else { - window->DC.ColumnsOffsetsT.resize(2); - window->DC.ColumnsOffsetsT[0] = 0.0f; - window->DC.ColumnsOffsetsT[1] = 1.0f; + window->DC.ColumnsData.resize(0); } } -void ImGui::Indent() +void ImGui::Indent(float indent_w) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); - window->DC.ColumnsStartX += g.Style.IndentSpacing; - window->DC.CursorPos.x = window->Pos.x + window->DC.ColumnsStartX + window->DC.ColumnsOffsetX; + window->DC.IndentX += (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing; + window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX; } -void ImGui::Unindent() +void ImGui::Unindent(float indent_w) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); - window->DC.ColumnsStartX -= g.Style.IndentSpacing; - window->DC.CursorPos.x = window->Pos.x + window->DC.ColumnsStartX + window->DC.ColumnsOffsetX; + window->DC.IndentX -= (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing; + window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX; } void ImGui::TreePush(const char* str_id) { ImGuiWindow* window = GetCurrentWindow(); - ImGui::Indent(); + Indent(); window->DC.TreeDepth++; PushID(str_id ? str_id : "#TreePush"); } @@ -7877,32 +9404,40 @@ void ImGui::TreePush(const char* str_id) void ImGui::TreePush(const void* ptr_id) { ImGuiWindow* window = GetCurrentWindow(); - ImGui::Indent(); + Indent(); window->DC.TreeDepth++; PushID(ptr_id ? ptr_id : (const void*)"#TreePush"); } +void ImGui::TreePushRawID(ImGuiID id) +{ + ImGuiWindow* window = GetCurrentWindow(); + Indent(); + window->DC.TreeDepth++; + window->IDStack.push_back(id); +} + void ImGui::TreePop() { ImGuiWindow* window = GetCurrentWindow(); - ImGui::Unindent(); + Unindent(); window->DC.TreeDepth--; PopID(); } void ImGui::Value(const char* prefix, bool b) { - ImGui::Text("%s: %s", prefix, (b ? "true" : "false")); + Text("%s: %s", prefix, (b ? "true" : "false")); } void ImGui::Value(const char* prefix, int v) { - ImGui::Text("%s: %d", prefix, v); + Text("%s: %d", prefix, v); } void ImGui::Value(const char* prefix, unsigned int v) { - ImGui::Text("%s: %d", prefix, v); + Text("%s: %d", prefix, v); } void ImGui::Value(const char* prefix, float v, const char* float_format) @@ -7911,1612 +9446,52 @@ void ImGui::Value(const char* prefix, float v, const char* float_format) { char fmt[64]; ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format); - ImGui::Text(fmt, prefix, v); + Text(fmt, prefix, v); } else { - ImGui::Text("%s: %.3f", prefix, v); + Text("%s: %.3f", prefix, v); } } -void ImGui::Color(const char* prefix, const ImVec4& v) +// FIXME: May want to remove those helpers? +void ImGui::ValueColor(const char* prefix, const ImVec4& v) { - ImGui::Text("%s: (%.2f,%.2f,%.2f,%.2f)", prefix, v.x, v.y, v.z, v.w); - ImGui::SameLine(); - ImGui::ColorButton(v, true); + Text("%s: (%.2f,%.2f,%.2f,%.2f)", prefix, v.x, v.y, v.z, v.w); + SameLine(); + ColorButton(v, true); } -void ImGui::Color(const char* prefix, unsigned int v) +void ImGui::ValueColor(const char* prefix, unsigned int v) { - ImGui::Text("%s: %08X", prefix, v); - ImGui::SameLine(); + Text("%s: %08X", prefix, v); + SameLine(); ImVec4 col; col.x = (float)((v >> 0) & 0xFF) / 255.0f; col.y = (float)((v >> 8) & 0xFF) / 255.0f; col.z = (float)((v >> 16) & 0xFF) / 255.0f; col.w = (float)((v >> 24) & 0xFF) / 255.0f; - ImGui::ColorButton(col, true); -} - -//----------------------------------------------------------------------------- -// ImDrawList -//----------------------------------------------------------------------------- - -static ImVec4 GNullClipRect(-9999.0f,-9999.0f, +9999.0f, +9999.0f); - -void ImDrawList::Clear() -{ - commands.resize(0); - vtx_buffer.resize(0); - vtx_write = NULL; - clip_rect_stack.resize(0); - texture_id_stack.resize(0); -} - -void ImDrawList::ClearFreeMemory() -{ - commands.clear(); - vtx_buffer.clear(); - vtx_write = NULL; - clip_rect_stack.clear(); - texture_id_stack.clear(); -} - -void ImDrawList::AddDrawCmd() -{ - ImDrawCmd draw_cmd; - draw_cmd.vtx_count = 0; - draw_cmd.clip_rect = clip_rect_stack.empty() ? GNullClipRect : clip_rect_stack.back(); - draw_cmd.texture_id = texture_id_stack.empty() ? NULL : texture_id_stack.back(); - draw_cmd.user_callback = NULL; - draw_cmd.user_callback_data = NULL; - - IM_ASSERT(draw_cmd.clip_rect.x <= draw_cmd.clip_rect.z && draw_cmd.clip_rect.y <= draw_cmd.clip_rect.w); - commands.push_back(draw_cmd); -} - -void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) -{ - ImDrawCmd* current_cmd = commands.empty() ? NULL : &commands.back(); - if (!current_cmd || current_cmd->vtx_count != 0 || current_cmd->user_callback != NULL) - { - AddDrawCmd(); - current_cmd = &commands.back(); - } - current_cmd->user_callback = callback; - current_cmd->user_callback_data = callback_data; - - // Force a new command after us - // We function this way so that the most common calls (AddLine, AddRect..) always have a command to add to without doing any check. - AddDrawCmd(); -} - -void ImDrawList::UpdateClipRect() -{ - ImDrawCmd* current_cmd = commands.empty() ? NULL : &commands.back(); - if (!current_cmd || (current_cmd->vtx_count != 0) || current_cmd->user_callback != NULL) - { - AddDrawCmd(); - } - else - { - ImVec4 current_clip_rect = clip_rect_stack.empty() ? GNullClipRect : clip_rect_stack.back(); - if (commands.size() > 2 && ImLengthSqr(commands[commands.size()-2].clip_rect - current_clip_rect) < 0.00001f) - commands.pop_back(); - else - current_cmd->clip_rect = current_clip_rect; - } -} - -// Scissoring. The values in clip_rect are x1, y1, x2, y2. -void ImDrawList::PushClipRect(const ImVec4& clip_rect) -{ - clip_rect_stack.push_back(clip_rect); - UpdateClipRect(); -} - -void ImDrawList::PushClipRectFullScreen() -{ - PushClipRect(GNullClipRect); - - // This would be more correct but we're not supposed to access ImGuiState from here? - //ImGuiState& g = *GImGui; - //PushClipRect(GetVisibleRect()); -} - -void ImDrawList::PopClipRect() -{ - IM_ASSERT(clip_rect_stack.size() > 0); - clip_rect_stack.pop_back(); - UpdateClipRect(); -} - -void ImDrawList::UpdateTextureID() -{ - ImDrawCmd* current_cmd = commands.empty() ? NULL : &commands.back(); - const ImTextureID texture_id = texture_id_stack.empty() ? NULL : texture_id_stack.back(); - if (!current_cmd || (current_cmd->vtx_count != 0 && current_cmd->texture_id != texture_id) || current_cmd->user_callback != NULL) - { - AddDrawCmd(); - } - else - { - current_cmd->texture_id = texture_id; - } -} - -void ImDrawList::PushTextureID(const ImTextureID& texture_id) -{ - texture_id_stack.push_back(texture_id); - UpdateTextureID(); -} - -void ImDrawList::PopTextureID() -{ - IM_ASSERT(texture_id_stack.size() > 0); - texture_id_stack.pop_back(); - UpdateTextureID(); -} - -void ImDrawList::PrimReserve(unsigned int vtx_count) -{ - ImDrawCmd& draw_cmd = commands.back(); - draw_cmd.vtx_count += vtx_count; - - size_t vtx_buffer_size = vtx_buffer.size(); - vtx_buffer.resize(vtx_buffer_size + vtx_count); - vtx_write = &vtx_buffer[vtx_buffer_size]; -} - -void ImDrawList::PrimTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col) -{ - const ImVec2 uv = GImGui->FontTexUvWhitePixel; - vtx_write[0].pos = a; vtx_write[0].uv = uv; vtx_write[0].col = col; - vtx_write[1].pos = b; vtx_write[1].uv = uv; vtx_write[1].col = col; - vtx_write[2].pos = c; vtx_write[2].uv = uv; vtx_write[2].col = col; - vtx_write += 3; -} - -void ImDrawList::PrimRect(const ImVec2& a, const ImVec2& c, ImU32 col) -{ - const ImVec2 uv = GImGui->FontTexUvWhitePixel; - const ImVec2 b(c.x, a.y); - const ImVec2 d(a.x, c.y); - vtx_write[0].pos = a; vtx_write[0].uv = uv; vtx_write[0].col = col; - vtx_write[1].pos = b; vtx_write[1].uv = uv; vtx_write[1].col = col; - vtx_write[2].pos = c; vtx_write[2].uv = uv; vtx_write[2].col = col; - vtx_write[3].pos = a; vtx_write[3].uv = uv; vtx_write[3].col = col; - vtx_write[4].pos = c; vtx_write[4].uv = uv; vtx_write[4].col = col; - vtx_write[5].pos = d; vtx_write[5].uv = uv; vtx_write[5].col = col; - vtx_write += 6; -} - -void ImDrawList::PrimRectUV(const ImVec2& a, const ImVec2& c, const ImVec2& uv_a, const ImVec2& uv_c, ImU32 col) -{ - const ImVec2 b(c.x, a.y); - const ImVec2 d(a.x, c.y); - const ImVec2 uv_b(uv_c.x, uv_a.y); - const ImVec2 uv_d(uv_a.x, uv_c.y); - vtx_write[0].pos = a; vtx_write[0].uv = uv_a; vtx_write[0].col = col; - vtx_write[1].pos = b; vtx_write[1].uv = uv_b; vtx_write[1].col = col; - vtx_write[2].pos = c; vtx_write[2].uv = uv_c; vtx_write[2].col = col; - vtx_write[3].pos = a; vtx_write[3].uv = uv_a; vtx_write[3].col = col; - vtx_write[4].pos = c; vtx_write[4].uv = uv_c; vtx_write[4].col = col; - vtx_write[5].pos = d; vtx_write[5].uv = uv_d; vtx_write[5].col = col; - vtx_write += 6; -} - -void ImDrawList::PrimQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col) -{ - const ImVec2 uv = GImGui->FontTexUvWhitePixel; - vtx_write[0].pos = a; vtx_write[0].uv = uv; vtx_write[0].col = col; - vtx_write[1].pos = b; vtx_write[1].uv = uv; vtx_write[1].col = col; - vtx_write[2].pos = c; vtx_write[2].uv = uv; vtx_write[2].col = col; - vtx_write[3].pos = a; vtx_write[3].uv = uv; vtx_write[3].col = col; - vtx_write[4].pos = c; vtx_write[4].uv = uv; vtx_write[4].col = col; - vtx_write[5].pos = d; vtx_write[5].uv = uv; vtx_write[5].col = col; - vtx_write += 6; -} - -// FIXME-OPT: In many instances the caller could provide a normal. -void ImDrawList::PrimLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness) -{ - const float inv_length = 1.0f / sqrtf(ImLengthSqr(b - a)); - const float dx = (b.x - a.x) * (thickness * 0.5f * inv_length); // line direction, halved - const float dy = (b.y - a.y) * (thickness * 0.5f * inv_length); // line direction, halved - - const ImVec2 pa(a.x + dy, a.y - dx); - const ImVec2 pb(b.x + dy, b.y - dx); - const ImVec2 pc(b.x - dy, b.y + dx); - const ImVec2 pd(a.x - dy, a.y + dx); - PrimQuad(pa, pb, pc, pd, col); -} - -void ImDrawList::AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness) -{ - if ((col >> 24) == 0) - return; - - PrimReserve(6); - PrimLine(a, b, col, thickness); -} - -void ImDrawList::AddArcFast(const ImVec2& center, float radius, ImU32 col, int a_min, int a_max, bool filled, const ImVec2& third_point_offset) -{ - if ((col >> 24) == 0) - return; - - const int SAMPLES = 12; - static ImVec2 circle_vtx[SAMPLES]; - static bool circle_vtx_builds = false; - if (!circle_vtx_builds) - { - for (int i = 0; i < SAMPLES; i++) - { - const float a = ((float)i / (float)SAMPLES) * 2*PI; - circle_vtx[i].x = cosf(a + PI); - circle_vtx[i].y = sinf(a + PI); - } - circle_vtx_builds = true; - } - - const ImVec2 uv = GImGui->FontTexUvWhitePixel; - if (filled) - { - PrimReserve((unsigned int)(a_max-a_min) * 3); - for (int a0 = a_min; a0 < a_max; a0++) - { - int a1 = (a0 + 1 == SAMPLES) ? 0 : a0 + 1; - PrimVtx(center + circle_vtx[a0] * radius, uv, col); - PrimVtx(center + circle_vtx[a1] * radius, uv, col); - PrimVtx(center + third_point_offset, uv, col); - } - } - else - { - PrimReserve((unsigned int)(a_max-a_min) * 6); - for (int a0 = a_min; a0 < a_max; a0++) - { - int a1 = (a0 + 1 == SAMPLES) ? 0 : a0 + 1; - PrimLine(center + circle_vtx[a0] * radius, center + circle_vtx[a1] * radius, col); - } - } -} - -void ImDrawList::AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners) -{ - if ((col >> 24) == 0) - return; - - float r = rounding; - r = ImMin(r, fabsf(b.x-a.x) * ( ((rounding_corners&(1|2))==(1|2)) || ((rounding_corners&(4|8))==(4|8)) ? 0.5f : 1.0f )); - r = ImMin(r, fabsf(b.y-a.y) * ( ((rounding_corners&(1|8))==(1|8)) || ((rounding_corners&(2|4))==(2|4)) ? 0.5f : 1.0f )); - - if (r == 0.0f || rounding_corners == 0) - { - PrimReserve(4*6); - PrimLine(ImVec2(a.x,a.y), ImVec2(b.x,a.y), col); - PrimLine(ImVec2(b.x,a.y), ImVec2(b.x,b.y), col); - PrimLine(ImVec2(b.x,b.y), ImVec2(a.x,b.y), col); - PrimLine(ImVec2(a.x,b.y), ImVec2(a.x,a.y), col); - } - else - { - PrimReserve(4*6); - PrimLine(ImVec2(a.x + ((rounding_corners & 1)?r:0), a.y), ImVec2(b.x - ((rounding_corners & 2)?r:0), a.y), col); - PrimLine(ImVec2(b.x, a.y + ((rounding_corners & 2)?r:0)), ImVec2(b.x, b.y - ((rounding_corners & 4)?r:0)), col); - PrimLine(ImVec2(b.x - ((rounding_corners & 4)?r:0), b.y), ImVec2(a.x + ((rounding_corners & 8)?r:0), b.y), col); - PrimLine(ImVec2(a.x, b.y - ((rounding_corners & 8)?r:0)), ImVec2(a.x, a.y + ((rounding_corners & 1)?r:0)), col); - - if (rounding_corners & 1) AddArcFast(ImVec2(a.x+r,a.y+r), r, col, 0, 3); - if (rounding_corners & 2) AddArcFast(ImVec2(b.x-r,a.y+r), r, col, 3, 6); - if (rounding_corners & 4) AddArcFast(ImVec2(b.x-r,b.y-r), r, col, 6, 9); - if (rounding_corners & 8) AddArcFast(ImVec2(a.x+r,b.y-r), r, col, 9, 12); - } -} - -void ImDrawList::AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners) -{ - if ((col >> 24) == 0) - return; - - float r = rounding; - r = ImMin(r, fabsf(b.x-a.x) * ( ((rounding_corners&(1|2))==(1|2)) || ((rounding_corners&(4|8))==(4|8)) ? 0.5f : 1.0f )); - r = ImMin(r, fabsf(b.y-a.y) * ( ((rounding_corners&(1|8))==(1|8)) || ((rounding_corners&(2|4))==(2|4)) ? 0.5f : 1.0f )); - - if (r == 0.0f || rounding_corners == 0) - { - // Use triangle so we can merge more draw calls together (at the cost of extra vertices) - PrimReserve(6); - PrimRect(a, b, col); - } - else - { - PrimReserve(6+6*2); - PrimRect(ImVec2(a.x+r,a.y), ImVec2(b.x-r,b.y), col); - - float top_y = (rounding_corners & 1) ? a.y+r : a.y; - float bot_y = (rounding_corners & 8) ? b.y-r : b.y; - PrimRect(ImVec2(a.x,top_y), ImVec2(a.x+r,bot_y), col); - - top_y = (rounding_corners & 2) ? a.y+r : a.y; - bot_y = (rounding_corners & 4) ? b.y-r : b.y; - PrimRect(ImVec2(b.x-r,top_y), ImVec2(b.x,bot_y), col); - - if (rounding_corners & 1) AddArcFast(ImVec2(a.x+r,a.y+r), r, col, 0, 3, true); - if (rounding_corners & 2) AddArcFast(ImVec2(b.x-r,a.y+r), r, col, 3, 6, true); - if (rounding_corners & 4) AddArcFast(ImVec2(b.x-r,b.y-r), r, col, 6, 9, true); - if (rounding_corners & 8) AddArcFast(ImVec2(a.x+r,b.y-r), r, col, 9, 12, true); - } -} - -void ImDrawList::AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col) -{ - if ((col >> 24) == 0) - return; - - PrimReserve(3); - PrimTriangle(a, b, c, col); -} - -void ImDrawList::AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments) -{ - if ((col >> 24) == 0) - return; - - PrimReserve((unsigned int)num_segments*6); - const float a_step = 2*PI/(float)num_segments; - float a0 = 0.0f; - for (int i = 0; i < num_segments; i++) - { - const float a1 = (i + 1) == num_segments ? 0.0f : a0 + a_step; - PrimLine(centre + ImVec2(cosf(a0), sinf(a0))*radius, centre + ImVec2(cosf(a1), sinf(a1))*radius, col); - a0 = a1; - } -} - -void ImDrawList::AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments) -{ - if ((col >> 24) == 0) - return; - - const ImVec2 uv = GImGui->FontTexUvWhitePixel; - PrimReserve((unsigned int)num_segments*3); - const float a_step = 2*PI/(float)num_segments; - float a0 = 0.0f; - for (int i = 0; i < num_segments; i++) - { - const float a1 = (i + 1) == num_segments ? 0.0f : a0 + a_step; - PrimVtx(centre + ImVec2(cosf(a0), sinf(a0))*radius, uv, col); - PrimVtx(centre + ImVec2(cosf(a1), sinf(a1))*radius, uv, col); - PrimVtx(centre, uv, col); - a0 = a1; - } -} - -void ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end, float wrap_width, const ImVec2* cpu_clip_max) -{ - if ((col >> 24) == 0) - return; - - if (text_end == NULL) - text_end = text_begin + strlen(text_begin); - if (text_begin == text_end) - return; - - IM_ASSERT(font->ContainerAtlas->TexID == texture_id_stack.back()); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font. - - // reserve vertices for worse case - const unsigned int char_count = (unsigned int)(text_end - text_begin); - const unsigned int vtx_count_max = char_count * 6; - const size_t vtx_begin = vtx_buffer.size(); - PrimReserve(vtx_count_max); - - font->RenderText(font_size, pos, col, clip_rect_stack.back(), text_begin, text_end, this, wrap_width, cpu_clip_max); - - // give back unused vertices - vtx_buffer.resize((size_t)(vtx_write - &vtx_buffer.front())); - const size_t vtx_count = vtx_buffer.size() - vtx_begin; - commands.back().vtx_count -= (unsigned int)(vtx_count_max - vtx_count); - vtx_write -= (vtx_count_max - vtx_count); -} - -void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv0, const ImVec2& uv1, ImU32 col) -{ - if ((col >> 24) == 0) - return; - - // FIXME-OPT: This is wasting draw calls. - const bool push_texture_id = texture_id_stack.empty() || user_texture_id != texture_id_stack.back(); - if (push_texture_id) - PushTextureID(user_texture_id); - - PrimReserve(6); - PrimRectUV(a, b, uv0, uv1, col); - - if (push_texture_id) - PopTextureID(); -} - -//----------------------------------------------------------------------------- -// ImFontAtlias -//----------------------------------------------------------------------------- - -struct ImFontAtlas::ImFontAtlasData -{ - // Input - ImFont* OutFont; // Load into this font - void* TTFData; // TTF data, we own the memory - size_t TTFDataSize; // TTF data size, in bytes - float SizePixels; // Desired output size, in pixels - const ImWchar* GlyphRanges; // List of Unicode range (2 value per range, values are inclusive, zero-terminated list) - int FontNo; // Index of font within .TTF file (0) - - // Temporary Build Data - stbtt_fontinfo FontInfo; - stbrp_rect* Rects; - stbtt_pack_range* Ranges; - int RangesCount; -}; - -ImFontAtlas::ImFontAtlas() -{ - TexID = NULL; - TexPixelsAlpha8 = NULL; - TexPixelsRGBA32 = NULL; - TexWidth = TexHeight = 0; - TexUvWhitePixel = ImVec2(0, 0); -} - -ImFontAtlas::~ImFontAtlas() -{ - Clear(); -} - -void ImFontAtlas::ClearInputData() -{ - for (size_t i = 0; i < InputData.size(); i++) - { - if (InputData[i]->TTFData) - ImGui::MemFree(InputData[i]->TTFData); - ImGui::MemFree(InputData[i]); - } - InputData.clear(); -} - -void ImFontAtlas::ClearTexData() -{ - if (TexPixelsAlpha8) - ImGui::MemFree(TexPixelsAlpha8); - if (TexPixelsRGBA32) - ImGui::MemFree(TexPixelsRGBA32); - TexPixelsAlpha8 = NULL; - TexPixelsRGBA32 = NULL; -} - -void ImFontAtlas::ClearFonts() -{ - for (size_t i = 0; i < Fonts.size(); i++) - { - Fonts[i]->~ImFont(); - ImGui::MemFree(Fonts[i]); - } - Fonts.clear(); -} - -void ImFontAtlas::Clear() -{ - ClearInputData(); - ClearTexData(); - ClearFonts(); -} - -void ImGui::GetDefaultFontData(const void** fnt_data, unsigned int* fnt_size, const void** png_data, unsigned int* png_size) -{ - printf("GetDefaultFontData() is obsoleted in ImGui 1.30.\n"); - printf("Please use ImGui::GetIO().Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() functions to retrieve uncompressed texture data.\n"); - if (fnt_data) *fnt_data = NULL; - if (fnt_size) *fnt_size = 0; - if (png_data) *png_data = NULL; - if (png_size) *png_size = 0; - IM_ASSERT(false); -} - -void ImFontAtlas::GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) -{ - // Lazily build - if (TexPixelsAlpha8 == NULL) - { - if (InputData.empty()) - AddFontDefault(); - Build(); - } - - *out_pixels = TexPixelsAlpha8; - if (out_width) *out_width = TexWidth; - if (out_height) *out_height = TexHeight; - if (out_bytes_per_pixel) *out_bytes_per_pixel = 1; -} - -void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) -{ - // Lazily convert to RGBA32 format - // Although it is likely to be the most commonly used format, our font rendering is 8 bpp - if (!TexPixelsRGBA32) - { - unsigned char* pixels; - GetTexDataAsAlpha8(&pixels, NULL, NULL); - TexPixelsRGBA32 = (unsigned int*)ImGui::MemAlloc((size_t)(TexWidth * TexHeight * 4)); - const unsigned char* src = pixels; - unsigned int* dst = TexPixelsRGBA32; - for (int n = TexWidth * TexHeight; n > 0; n--) - *dst++ = ((unsigned int)(*src++) << 24) | 0x00FFFFFF; - } - - *out_pixels = (unsigned char*)TexPixelsRGBA32; - if (out_width) *out_width = TexWidth; - if (out_height) *out_height = TexHeight; - if (out_bytes_per_pixel) *out_bytes_per_pixel = 4; -} - -static void GetDefaultCompressedFontDataTTF(const void** ttf_compressed_data, unsigned int* ttf_compressed_size); -static unsigned int stb_decompress_length(unsigned char *input); -static unsigned int stb_decompress(unsigned char *output, unsigned char *i, unsigned int length); - -// Load embedded ProggyClean.ttf at size 13 -ImFont* ImFontAtlas::AddFontDefault() -{ - unsigned int ttf_compressed_size; - const void* ttf_compressed; - GetDefaultCompressedFontDataTTF(&ttf_compressed, &ttf_compressed_size); - ImFont* font = AddFontFromMemoryCompressedTTF(ttf_compressed, ttf_compressed_size, 13.0f, GetGlyphRangesDefault(), 0); - font->DisplayOffset.y += 1; - return font; -} - -ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, const ImWchar* glyph_ranges, int font_no) -{ - void* data = NULL; - size_t data_size = 0; - if (!ImLoadFileToMemory(filename, "rb", (void**)&data, &data_size)) - { - IM_ASSERT(0); // Could not load file. - return NULL; - } - - ImFont* font = AddFontFromMemoryTTF(data, (unsigned int)data_size, size_pixels, glyph_ranges, font_no); - return font; -} - -// Transfer ownership of 'ttf_data' to ImFontAtlas, will be deleted after Build() -ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float size_pixels, const ImWchar* glyph_ranges, int font_no) -{ - // Create new font - ImFont* font = (ImFont*)ImGui::MemAlloc(sizeof(ImFont)); - new (font) ImFont(); - Fonts.push_back(font); - - // Add to build list - ImFontAtlasData* data = (ImFontAtlasData*)ImGui::MemAlloc(sizeof(ImFontAtlasData)); - memset(data, 0, sizeof(ImFontAtlasData)); - data->OutFont = font; - data->TTFData = ttf_data; - data->TTFDataSize = (size_t)ttf_size; - data->SizePixels = size_pixels; - data->GlyphRanges = glyph_ranges; - data->FontNo = font_no; - InputData.push_back(data); - - // Invalidate texture - ClearTexData(); - - return font; -} - -ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImWchar* glyph_ranges, int font_no) -{ - // Decompress - const size_t buf_decompressed_size = stb_decompress_length((unsigned char*)compressed_ttf_data); - unsigned char* buf_decompressed_data = (unsigned char *)ImGui::MemAlloc(buf_decompressed_size); - stb_decompress(buf_decompressed_data, (unsigned char*)compressed_ttf_data, (unsigned int)compressed_ttf_size); - - // Add - ImFont* font = AddFontFromMemoryTTF(buf_decompressed_data, (int)buf_decompressed_size, size_pixels, glyph_ranges, font_no); - return font; -} - -bool ImFontAtlas::Build() -{ - IM_ASSERT(InputData.size() > 0); - - TexID = NULL; - TexWidth = TexHeight = 0; - TexUvWhitePixel = ImVec2(0, 0); - ClearTexData(); - - // Initialize font information early (so we can error without any cleanup) + count glyphs - int total_glyph_count = 0; - int total_glyph_range_count = 0; - for (size_t input_i = 0; input_i < InputData.size(); input_i++) - { - ImFontAtlasData& data = *InputData[input_i]; - IM_ASSERT(data.OutFont && (!data.OutFont->IsLoaded() || data.OutFont->ContainerAtlas == this)); - const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)data.TTFData, data.FontNo); - IM_ASSERT(font_offset >= 0); - if (!stbtt_InitFont(&data.FontInfo, (unsigned char*)data.TTFData, font_offset)) - return false; - - if (!data.GlyphRanges) - data.GlyphRanges = GetGlyphRangesDefault(); - for (const ImWchar* in_range = data.GlyphRanges; in_range[0] && in_range[1]; in_range += 2) - { - total_glyph_count += (in_range[1] - in_range[0]) + 1; - total_glyph_range_count++; - } - } - - // Start packing - TexWidth = (total_glyph_count > 1000) ? 1024 : 512; // Width doesn't actually matters. - TexHeight = 0; - const int max_tex_height = 1024*32; - stbtt_pack_context spc; - int ret = stbtt_PackBegin(&spc, NULL, TexWidth, max_tex_height, 0, 1, NULL); - IM_ASSERT(ret); - stbtt_PackSetOversampling(&spc, 1, 1); - - // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values). - ImVector extra_rects; - RenderCustomTexData(0, &extra_rects); - stbrp_pack_rects((stbrp_context*)spc.pack_info, &extra_rects[0], (int)extra_rects.size()); - for (size_t i = 0; i < extra_rects.size(); i++) - if (extra_rects[i].was_packed) - TexHeight = ImMax(TexHeight, extra_rects[i].y + extra_rects[i].h); - - // Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0) - int buf_packedchars_n = 0, buf_rects_n = 0, buf_ranges_n = 0; - stbtt_packedchar* buf_packedchars = (stbtt_packedchar*)ImGui::MemAlloc(total_glyph_count * sizeof(stbtt_packedchar)); - stbrp_rect* buf_rects = (stbrp_rect*)ImGui::MemAlloc(total_glyph_count * sizeof(stbrp_rect)); - stbtt_pack_range* buf_ranges = (stbtt_pack_range*)ImGui::MemAlloc(total_glyph_range_count * sizeof(stbtt_pack_range)); - memset(buf_packedchars, 0, total_glyph_count * sizeof(stbtt_packedchar)); - memset(buf_rects, 0, total_glyph_count * sizeof(stbrp_rect)); // Unnecessary but let's clear this for the sake of sanity. - memset(buf_ranges, 0, total_glyph_range_count * sizeof(stbtt_pack_range)); - - // First font pass: pack all glyphs (no rendering at this point, we are working with glyph sizes only) - for (size_t input_i = 0; input_i < InputData.size(); input_i++) - { - ImFontAtlasData& data = *InputData[input_i]; - - // Setup ranges - int glyph_count = 0; - int glyph_ranges_count = 0; - for (const ImWchar* in_range = data.GlyphRanges; in_range[0] && in_range[1]; in_range += 2) - { - glyph_count += (in_range[1] - in_range[0]) + 1; - glyph_ranges_count++; - } - data.Ranges = buf_ranges + buf_ranges_n; - data.RangesCount = glyph_ranges_count; - buf_ranges_n += glyph_ranges_count; - for (int i = 0; i < glyph_ranges_count; i++) - { - const ImWchar* in_range = &data.GlyphRanges[i * 2]; - stbtt_pack_range& range = data.Ranges[i]; - range.font_size = data.SizePixels; - range.first_unicode_char_in_range = in_range[0]; - range.num_chars_in_range = (in_range[1] - in_range[0]) + 1; - range.chardata_for_range = buf_packedchars + buf_packedchars_n; - buf_packedchars_n += range.num_chars_in_range; - } - - // Pack - data.Rects = buf_rects + buf_rects_n; - buf_rects_n += glyph_count; - const int n = stbtt_PackFontRangesGatherRects(&spc, &data.FontInfo, data.Ranges, data.RangesCount, data.Rects); - stbrp_pack_rects((stbrp_context*)spc.pack_info, data.Rects, n); - - // Extend texture height - for (int i = 0; i < n; i++) - if (data.Rects[i].was_packed) - TexHeight = ImMax(TexHeight, data.Rects[i].y + data.Rects[i].h); - } - IM_ASSERT(buf_rects_n == total_glyph_count); - IM_ASSERT(buf_packedchars_n == total_glyph_count); - IM_ASSERT(buf_ranges_n == total_glyph_range_count); - - // Create texture - TexHeight = ImUpperPowerOfTwo(TexHeight); - TexPixelsAlpha8 = (unsigned char*)ImGui::MemAlloc(TexWidth * TexHeight); - memset(TexPixelsAlpha8, 0, TexWidth * TexHeight); - spc.pixels = TexPixelsAlpha8; - spc.height = TexHeight; - - // Second pass: render characters - for (size_t input_i = 0; input_i < InputData.size(); input_i++) - { - ImFontAtlasData& data = *InputData[input_i]; - ret = stbtt_PackFontRangesRenderIntoRects(&spc, &data.FontInfo, data.Ranges, data.RangesCount, data.Rects); - data.Rects = NULL; - } - - // End packing - stbtt_PackEnd(&spc); - ImGui::MemFree(buf_rects); - buf_rects = NULL; - - // Third pass: setup ImFont and glyphs for runtime - for (size_t input_i = 0; input_i < InputData.size(); input_i++) - { - ImFontAtlasData& data = *InputData[input_i]; - data.OutFont->ContainerAtlas = this; - data.OutFont->FontSize = data.SizePixels; - - const float font_scale = stbtt_ScaleForPixelHeight(&data.FontInfo, data.SizePixels); - int font_ascent, font_descent, font_line_gap; - stbtt_GetFontVMetrics(&data.FontInfo, &font_ascent, &font_descent, &font_line_gap); - data.OutFont->BaseLine = (font_ascent * font_scale); - data.OutFont->Glyphs.resize(0); - - const float uv_scale_x = 1.0f / TexWidth; - const float uv_scale_y = 1.0f / TexHeight; - const int character_spacing_x = 1; - for (int i = 0; i < data.RangesCount; i++) - { - stbtt_pack_range& range = data.Ranges[i]; - for (int char_idx = 0; char_idx < range.num_chars_in_range; char_idx += 1) - { - const int codepoint = range.first_unicode_char_in_range + char_idx; - const stbtt_packedchar& pc = range.chardata_for_range[char_idx]; - if (!pc.x0 && !pc.x1 && !pc.y0 && !pc.y1) - continue; - - data.OutFont->Glyphs.resize(data.OutFont->Glyphs.size() + 1); - ImFont::Glyph& glyph = data.OutFont->Glyphs.back(); - glyph.Codepoint = (ImWchar)codepoint; - glyph.Width = (signed short)pc.x1 - pc.x0 + 1; - glyph.Height = (signed short)pc.y1 - pc.y0 + 1; - glyph.XOffset = (signed short)(pc.xoff); - glyph.YOffset = (signed short)(pc.yoff + (int)(font_ascent * font_scale)); - glyph.XAdvance = (signed short)(pc.xadvance + character_spacing_x); // Bake spacing into XAdvance - glyph.U0 = ((float)pc.x0 - 0.5f) * uv_scale_x; - glyph.V0 = ((float)pc.y0 - 0.5f) * uv_scale_y; - glyph.U1 = ((float)pc.x0 - 0.5f + glyph.Width) * uv_scale_x; - glyph.V1 = ((float)pc.y0 - 0.5f + glyph.Height) * uv_scale_y; - } - } - - data.OutFont->BuildLookupTable(); - } - - // Cleanup temporaries - ImGui::MemFree(buf_packedchars); - ImGui::MemFree(buf_ranges); - buf_packedchars = NULL; - buf_ranges = NULL; - - // Render into our custom data block - RenderCustomTexData(1, &extra_rects); - - return true; -} - -void ImFontAtlas::RenderCustomTexData(int pass, void* p_rects) -{ - // . = white layer, X = black layer, others are blank - const int TEX_DATA_W = 90; - const int TEX_DATA_H = 27; - const char texture_data[TEX_DATA_W*TEX_DATA_H+1] = - { - "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX" - "..- -X.....X- X.X - X.X -X.....X - X.....X" - "--- -XXX.XXX- X...X - X...X -X....X - X....X" - "X - X.X - X.....X - X.....X -X...X - X...X" - "XX - X.X -X.......X- X.......X -X..X.X - X.X..X" - "X.X - X.X -XXXX.XXXX- XXXX.XXXX -X.X X.X - X.X X.X" - "X..X - X.X - X.X - X.X -XX X.X - X.X XX" - "X...X - X.X - X.X - XX X.X XX - X.X - X.X " - "X....X - X.X - X.X - X.X X.X X.X - X.X - X.X " - "X.....X - X.X - X.X - X..X X.X X..X - X.X - X.X " - "X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-XX X.X " - "X.......X - X.X - X.X -X.....................X- X.X X.X-X.X X.X " - "X........X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X..X-X..X.X " - "X.........X -XXX.XXX- X.X - X..X X.X X..X - X...X-X...X " - "X..........X-X.....X- X.X - X.X X.X X.X - X....X-X....X " - "X......XXXXX-XXXXXXX- X.X - XX X.X XX - X.....X-X.....X " - "X...X..X --------- X.X - X.X - XXXXXXX-XXXXXXX " - "X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------" - "X.X X..X - -X.......X- X.......X - XX XX - " - "XX X..X - - X.....X - X.....X - X.X X.X - " - " X..X - X...X - X...X - X..X X..X - " - " XX - X.X - X.X - X...XXXXXXXXXXXXX...X - " - "------------ - X - X -X.....................X- " - " ----------------------------------- X...XXXXXXXXXXXXX...X - " - " - X..X X..X - " - " - X.X X.X - " - " - XX XX - " - }; - - ImVector& rects = *(ImVector*)p_rects; - if (pass == 0) - { - stbrp_rect r; - memset(&r, 0, sizeof(r)); - r.w = (TEX_DATA_W*2)+1; - r.h = TEX_DATA_H+1; - rects.push_back(r); - } - else if (pass == 1) - { - // Copy pixels - const stbrp_rect& r = rects[0]; - for (int y = 0, n = 0; y < TEX_DATA_H; y++) - for (int x = 0; x < TEX_DATA_W; x++, n++) - { - const int offset0 = (int)(r.x + x) + (int)(r.y + y) * TexWidth; - const int offset1 = offset0 + 1 + TEX_DATA_W; - TexPixelsAlpha8[offset0] = texture_data[n] == '.' ? 0xFF : 0x00; - TexPixelsAlpha8[offset1] = texture_data[n] == 'X' ? 0xFF : 0x00; - } - const ImVec2 tex_uv_scale(1.0f / TexWidth, 1.0f / TexHeight); - TexUvWhitePixel = ImVec2(r.x + 0.5f, r.y + 0.5f) * tex_uv_scale; - - const ImVec2 cursor_datas[ImGuiMouseCursor_Count_][3] = - { - // Pos ........ Size ......... Offset ...... - { ImVec2(0,3), ImVec2(12,19), ImVec2( 0, 0) }, // ImGuiMouseCursor_Arrow - { ImVec2(13,0), ImVec2(7,16), ImVec2( 4, 8) }, // ImGuiMouseCursor_TextInput - { ImVec2(31,0), ImVec2(23,23), ImVec2(11,11) }, // ImGuiMouseCursor_Move - { ImVec2(21,0), ImVec2( 9,23), ImVec2( 5,11) }, // ImGuiMouseCursor_ResizeNS - { ImVec2(55,18),ImVec2(23, 9), ImVec2(11, 5) }, // ImGuiMouseCursor_ResizeEW - { ImVec2(73,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNESW - { ImVec2(55,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNWSE - }; - - for (int type = 0; type < ImGuiMouseCursor_Count_; type++) - { - ImGuiMouseCursorData& cursor_data = GImGui->MouseCursorData[type]; - ImVec2 pos = cursor_datas[type][0] + ImVec2((float)r.x, (float)r.y); - const ImVec2 size = cursor_datas[type][1]; - cursor_data.Type = type; - cursor_data.Size = size; - cursor_data.Offset = cursor_datas[type][2]; - cursor_data.TexUvMin[0] = (pos) * tex_uv_scale; - cursor_data.TexUvMax[0] = (pos + size) * tex_uv_scale; - pos.x += TEX_DATA_W+1; - cursor_data.TexUvMin[1] = (pos) * tex_uv_scale; - cursor_data.TexUvMax[1] = (pos + size) * tex_uv_scale; - } - } -} - -//----------------------------------------------------------------------------- -// ImFont -//----------------------------------------------------------------------------- - -ImFont::ImFont() -{ - Scale = 1.0f; - FallbackChar = (ImWchar)'?'; - Clear(); -} - -ImFont::~ImFont() -{ - // Invalidate active font so that the user gets a clear crash instead of a dangling pointer. - // If you want to delete fonts you need to do it between Render() and NewFrame(). - ImGuiState& g = *GImGui; - if (g.Font == this) - g.Font = NULL; - Clear(); -} - -void ImFont::Clear() -{ - FontSize = 0.0f; - DisplayOffset = ImVec2(-0.5f, 0.5f); - BaseLine = 0.0f; - ContainerAtlas = NULL; - Glyphs.clear(); - FallbackGlyph = NULL; - FallbackXAdvance = 0.0f; - IndexXAdvance.clear(); - IndexLookup.clear(); -} - -// Retrieve list of range (2 int per range, values are inclusive) -const ImWchar* ImFontAtlas::GetGlyphRangesDefault() -{ - static const ImWchar ranges[] = - { - 0x0020, 0x00FF, // Basic Latin + Latin Supplement - 0, - }; - return &ranges[0]; -} - -const ImWchar* ImFontAtlas::GetGlyphRangesChinese() -{ - static const ImWchar ranges[] = - { - 0x0020, 0x00FF, // Basic Latin + Latin Supplement - 0x3000, 0x30FF, // Punctuations, Hiragana, Katakana - 0x31F0, 0x31FF, // Katakana Phonetic Extensions - 0xFF00, 0xFFEF, // Half-width characters - 0x4e00, 0x9FAF, // CJK Ideograms - 0, - }; - return &ranges[0]; -} - -const ImWchar* ImFontAtlas::GetGlyphRangesJapanese() -{ - // Store the 1946 ideograms code points as successive offsets from the initial unicode codepoint 0x4E00. Each offset has an implicit +1. - // This encoding helps us reduce the source code size. - static const short offsets_from_0x4E00[] = - { - -1,0,1,3,0,0,0,0,1,0,5,1,1,0,7,4,6,10,0,1,9,9,7,1,3,19,1,10,7,1,0,1,0,5,1,0,6,4,2,6,0,0,12,6,8,0,3,5,0,1,0,9,0,0,8,1,1,3,4,5,13,0,0,8,2,17, - 4,3,1,1,9,6,0,0,0,2,1,3,2,22,1,9,11,1,13,1,3,12,0,5,9,2,0,6,12,5,3,12,4,1,2,16,1,1,4,6,5,3,0,6,13,15,5,12,8,14,0,0,6,15,3,6,0,18,8,1,6,14,1, - 5,4,12,24,3,13,12,10,24,0,0,0,1,0,1,1,2,9,10,2,2,0,0,3,3,1,0,3,8,0,3,2,4,4,1,6,11,10,14,6,15,3,4,15,1,0,0,5,2,2,0,0,1,6,5,5,6,0,3,6,5,0,0,1,0, - 11,2,2,8,4,7,0,10,0,1,2,17,19,3,0,2,5,0,6,2,4,4,6,1,1,11,2,0,3,1,2,1,2,10,7,6,3,16,0,8,24,0,0,3,1,1,3,0,1,6,0,0,0,2,0,1,5,15,0,1,0,0,2,11,19, - 1,4,19,7,6,5,1,0,0,0,0,5,1,0,1,9,0,0,5,0,2,0,1,0,3,0,11,3,0,2,0,0,0,0,0,9,3,6,4,12,0,14,0,0,29,10,8,0,14,37,13,0,31,16,19,0,8,30,1,20,8,3,48, - 21,1,0,12,0,10,44,34,42,54,11,18,82,0,2,1,2,12,1,0,6,2,17,2,12,7,0,7,17,4,2,6,24,23,8,23,39,2,16,23,1,0,5,1,2,15,14,5,6,2,11,0,8,6,2,2,2,14, - 20,4,15,3,4,11,10,10,2,5,2,1,30,2,1,0,0,22,5,5,0,3,1,5,4,1,0,0,2,2,21,1,5,1,2,16,2,1,3,4,0,8,4,0,0,5,14,11,2,16,1,13,1,7,0,22,15,3,1,22,7,14, - 22,19,11,24,18,46,10,20,64,45,3,2,0,4,5,0,1,4,25,1,0,0,2,10,0,0,0,1,0,1,2,0,0,9,1,2,0,0,0,2,5,2,1,1,5,5,8,1,1,1,5,1,4,9,1,3,0,1,0,1,1,2,0,0, - 2,0,1,8,22,8,1,0,0,0,0,4,2,1,0,9,8,5,0,9,1,30,24,2,6,4,39,0,14,5,16,6,26,179,0,2,1,1,0,0,0,5,2,9,6,0,2,5,16,7,5,1,1,0,2,4,4,7,15,13,14,0,0, - 3,0,1,0,0,0,2,1,6,4,5,1,4,9,0,3,1,8,0,0,10,5,0,43,0,2,6,8,4,0,2,0,0,9,6,0,9,3,1,6,20,14,6,1,4,0,7,2,3,0,2,0,5,0,3,1,0,3,9,7,0,3,4,0,4,9,1,6,0, - 9,0,0,2,3,10,9,28,3,6,2,4,1,2,32,4,1,18,2,0,3,1,5,30,10,0,2,2,2,0,7,9,8,11,10,11,7,2,13,7,5,10,0,3,40,2,0,1,6,12,0,4,5,1,5,11,11,21,4,8,3,7, - 8,8,33,5,23,0,0,19,8,8,2,3,0,6,1,1,1,5,1,27,4,2,5,0,3,5,6,3,1,0,3,1,12,5,3,3,2,0,7,7,2,1,0,4,0,1,1,2,0,10,10,6,2,5,9,7,5,15,15,21,6,11,5,20, - 4,3,5,5,2,5,0,2,1,0,1,7,28,0,9,0,5,12,5,5,18,30,0,12,3,3,21,16,25,32,9,3,14,11,24,5,66,9,1,2,0,5,9,1,5,1,8,0,8,3,3,0,1,15,1,4,8,1,2,7,0,7,2, - 8,3,7,5,3,7,10,2,1,0,0,2,25,0,6,4,0,10,0,4,2,4,1,12,5,38,4,0,4,1,10,5,9,4,0,14,4,2,5,18,20,21,1,3,0,5,0,7,0,3,7,1,3,1,1,8,1,0,0,0,3,2,5,2,11, - 6,0,13,1,3,9,1,12,0,16,6,2,1,0,2,1,12,6,13,11,2,0,28,1,7,8,14,13,8,13,0,2,0,5,4,8,10,2,37,42,19,6,6,7,4,14,11,18,14,80,7,6,0,4,72,12,36,27, - 7,7,0,14,17,19,164,27,0,5,10,7,3,13,6,14,0,2,2,5,3,0,6,13,0,0,10,29,0,4,0,3,13,0,3,1,6,51,1,5,28,2,0,8,0,20,2,4,0,25,2,10,13,10,0,16,4,0,1,0, - 2,1,7,0,1,8,11,0,0,1,2,7,2,23,11,6,6,4,16,2,2,2,0,22,9,3,3,5,2,0,15,16,21,2,9,20,15,15,5,3,9,1,0,0,1,7,7,5,4,2,2,2,38,24,14,0,0,15,5,6,24,14, - 5,5,11,0,21,12,0,3,8,4,11,1,8,0,11,27,7,2,4,9,21,59,0,1,39,3,60,62,3,0,12,11,0,3,30,11,0,13,88,4,15,5,28,13,1,4,48,17,17,4,28,32,46,0,16,0, - 18,11,1,8,6,38,11,2,6,11,38,2,0,45,3,11,2,7,8,4,30,14,17,2,1,1,65,18,12,16,4,2,45,123,12,56,33,1,4,3,4,7,0,0,0,3,2,0,16,4,2,4,2,0,7,4,5,2,26, - 2,25,6,11,6,1,16,2,6,17,77,15,3,35,0,1,0,5,1,0,38,16,6,3,12,3,3,3,0,9,3,1,3,5,2,9,0,18,0,25,1,3,32,1,72,46,6,2,7,1,3,14,17,0,28,1,40,13,0,20, - 15,40,6,38,24,12,43,1,1,9,0,12,6,0,6,2,4,19,3,7,1,48,0,9,5,0,5,6,9,6,10,15,2,11,19,3,9,2,0,1,10,1,27,8,1,3,6,1,14,0,26,0,27,16,3,4,9,6,2,23, - 9,10,5,25,2,1,6,1,1,48,15,9,15,14,3,4,26,60,29,13,37,21,1,6,4,0,2,11,22,23,16,16,2,2,1,3,0,5,1,6,4,0,0,4,0,0,8,3,0,2,5,0,7,1,7,3,13,2,4,10, - 3,0,2,31,0,18,3,0,12,10,4,1,0,7,5,7,0,5,4,12,2,22,10,4,2,15,2,8,9,0,23,2,197,51,3,1,1,4,13,4,3,21,4,19,3,10,5,40,0,4,1,1,10,4,1,27,34,7,21, - 2,17,2,9,6,4,2,3,0,4,2,7,8,2,5,1,15,21,3,4,4,2,2,17,22,1,5,22,4,26,7,0,32,1,11,42,15,4,1,2,5,0,19,3,1,8,6,0,10,1,9,2,13,30,8,2,24,17,19,1,4, - 4,25,13,0,10,16,11,39,18,8,5,30,82,1,6,8,18,77,11,13,20,75,11,112,78,33,3,0,0,60,17,84,9,1,1,12,30,10,49,5,32,158,178,5,5,6,3,3,1,3,1,4,7,6, - 19,31,21,0,2,9,5,6,27,4,9,8,1,76,18,12,1,4,0,3,3,6,3,12,2,8,30,16,2,25,1,5,5,4,3,0,6,10,2,3,1,0,5,1,19,3,0,8,1,5,2,6,0,0,0,19,1,2,0,5,1,2,5, - 1,3,7,0,4,12,7,3,10,22,0,9,5,1,0,2,20,1,1,3,23,30,3,9,9,1,4,191,14,3,15,6,8,50,0,1,0,0,4,0,0,1,0,2,4,2,0,2,3,0,2,0,2,2,8,7,0,1,1,1,3,3,17,11, - 91,1,9,3,2,13,4,24,15,41,3,13,3,1,20,4,125,29,30,1,0,4,12,2,21,4,5,5,19,11,0,13,11,86,2,18,0,7,1,8,8,2,2,22,1,2,6,5,2,0,1,2,8,0,2,0,5,2,1,0, - 2,10,2,0,5,9,2,1,2,0,1,0,4,0,0,10,2,5,3,0,6,1,0,1,4,4,33,3,13,17,3,18,6,4,7,1,5,78,0,4,1,13,7,1,8,1,0,35,27,15,3,0,0,0,1,11,5,41,38,15,22,6, - 14,14,2,1,11,6,20,63,5,8,27,7,11,2,2,40,58,23,50,54,56,293,8,8,1,5,1,14,0,1,12,37,89,8,8,8,2,10,6,0,0,0,4,5,2,1,0,1,1,2,7,0,3,3,0,4,6,0,3,2, - 19,3,8,0,0,0,4,4,16,0,4,1,5,1,3,0,3,4,6,2,17,10,10,31,6,4,3,6,10,126,7,3,2,2,0,9,0,0,5,20,13,0,15,0,6,0,2,5,8,64,50,3,2,12,2,9,0,0,11,8,20, - 109,2,18,23,0,0,9,61,3,0,28,41,77,27,19,17,81,5,2,14,5,83,57,252,14,154,263,14,20,8,13,6,57,39,38, - }; - static int ranges_unpacked = false; - static ImWchar ranges[8 + IM_ARRAYSIZE(offsets_from_0x4E00)*2 + 1] = - { - 0x0020, 0x00FF, // Basic Latin + Latin Supplement - 0x3000, 0x30FF, // Punctuations, Hiragana, Katakana - 0x31F0, 0x31FF, // Katakana Phonetic Extensions - 0xFF00, 0xFFEF, // Half-width characters - }; - if (!ranges_unpacked) - { - // Unpack - int codepoint = 0x4e00; - ImWchar* dst = &ranges[8]; - for (int n = 0; n < IM_ARRAYSIZE(offsets_from_0x4E00); n++, dst += 2) - dst[0] = dst[1] = (ImWchar)(codepoint += (offsets_from_0x4E00[n] + 1)); - dst[0] = 0; - ranges_unpacked = true; - } - return &ranges[0]; -} - -void ImFont::BuildLookupTable() -{ - int max_codepoint = 0; - for (size_t i = 0; i != Glyphs.size(); i++) - max_codepoint = ImMax(max_codepoint, (int)Glyphs[i].Codepoint); - - IndexXAdvance.clear(); - IndexXAdvance.resize((size_t)max_codepoint + 1); - IndexLookup.clear(); - IndexLookup.resize((size_t)max_codepoint + 1); - for (size_t i = 0; i < (size_t)max_codepoint + 1; i++) - { - IndexXAdvance[i] = -1.0f; - IndexLookup[i] = -1; - } - for (size_t i = 0; i < Glyphs.size(); i++) - { - const size_t codepoint = (int)Glyphs[i].Codepoint; - IndexXAdvance[codepoint] = Glyphs[i].XAdvance; - IndexLookup[codepoint] = (int)i; - } - - // Create a glyph to handle TAB - // FIXME: Needs proper TAB handling but it needs to be contextualized (can arbitrary say that each string starts at "column 0" - if (FindGlyph((unsigned short)' ')) - { - if (Glyphs.back().Codepoint != '\t') // So we can call this function multiple times - Glyphs.resize(Glyphs.size() + 1); - ImFont::Glyph& tab_glyph = Glyphs.back(); - tab_glyph = *FindGlyph((unsigned short)' '); - tab_glyph.Codepoint = '\t'; - tab_glyph.XAdvance *= 4; - IndexXAdvance[(size_t)tab_glyph.Codepoint] = (float)tab_glyph.XAdvance; - IndexLookup[(size_t)tab_glyph.Codepoint] = (int)(Glyphs.size()-1); - } - - FallbackGlyph = NULL; - FallbackGlyph = FindGlyph(FallbackChar); - FallbackXAdvance = FallbackGlyph ? FallbackGlyph->XAdvance : 0.0f; - for (size_t i = 0; i < (size_t)max_codepoint + 1; i++) - if (IndexXAdvance[i] < 0.0f) - IndexXAdvance[i] = FallbackXAdvance; -} - -void ImFont::SetFallbackChar(ImWchar c) -{ - FallbackChar = c; - BuildLookupTable(); -} - -const ImFont::Glyph* ImFont::FindGlyph(unsigned short c) const -{ - if (c < (int)IndexLookup.size()) - { - const int i = IndexLookup[c]; - if (i != -1) - return &Glyphs[i]; - } - return FallbackGlyph; -} - -// Convert UTF-8 to 32-bits character, process single character input. -// Based on stb_from_utf8() from github.com/nothings/stb/ -// We handle UTF-8 decoding error by skipping forward. -static int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end) -{ - unsigned int c = (unsigned int)-1; - const unsigned char* str = (const unsigned char*)in_text; - if (!(*str & 0x80)) - { - c = (unsigned int)(*str++); - *out_char = c; - return 1; - } - if ((*str & 0xe0) == 0xc0) - { - *out_char = 0; - if (in_text_end && in_text_end - (const char*)str < 2) return 0; - if (*str < 0xc2) return 0; - c = (unsigned int)((*str++ & 0x1f) << 6); - if ((*str & 0xc0) != 0x80) return 0; - c += (*str++ & 0x3f); - *out_char = c; - return 2; - } - if ((*str & 0xf0) == 0xe0) - { - *out_char = 0; - if (in_text_end && in_text_end - (const char*)str < 3) return 0; - if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 0; - if (*str == 0xed && str[1] > 0x9f) return 0; // str[1] < 0x80 is checked below - c = (unsigned int)((*str++ & 0x0f) << 12); - if ((*str & 0xc0) != 0x80) return 0; - c += (unsigned int)((*str++ & 0x3f) << 6); - if ((*str & 0xc0) != 0x80) return 0; - c += (*str++ & 0x3f); - *out_char = c; - return 3; - } - if ((*str & 0xf8) == 0xf0) - { - *out_char = 0; - if (in_text_end && in_text_end - (const char*)str < 4) return 0; - if (*str > 0xf4) return 0; - if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 0; - if (*str == 0xf4 && str[1] > 0x8f) return 0; // str[1] < 0x80 is checked below - c = (unsigned int)((*str++ & 0x07) << 18); - if ((*str & 0xc0) != 0x80) return 0; - c += (unsigned int)((*str++ & 0x3f) << 12); - if ((*str & 0xc0) != 0x80) return 0; - c += (unsigned int)((*str++ & 0x3f) << 6); - if ((*str & 0xc0) != 0x80) return 0; - c += (*str++ & 0x3f); - // utf-8 encodings of values used in surrogate pairs are invalid - if ((c & 0xFFFFF800) == 0xD800) return 0; - *out_char = c; - return 4; - } - *out_char = 0; - return 0; -} - -static ptrdiff_t ImTextStrFromUtf8(ImWchar* buf, size_t buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining) -{ - ImWchar* buf_out = buf; - ImWchar* buf_end = buf + buf_size; - while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) - { - unsigned int c; - in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); - if (c == 0) - break; - if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes - *buf_out++ = (ImWchar)c; - } - *buf_out = 0; - if (in_text_remaining) - *in_text_remaining = in_text; - return buf_out - buf; -} - -static int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end) -{ - int char_count = 0; - while ((!in_text_end || in_text < in_text_end) && *in_text) - { - unsigned int c; - in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); - if (c == 0) - break; - if (c < 0x10000) - char_count++; - } - return char_count; -} - -// Based on stb_to_utf8() from github.com/nothings/stb/ -static int ImTextCharToUtf8(char* buf, size_t buf_size, unsigned int c) -{ - if (c) - { - size_t i = 0; - size_t n = buf_size; - if (c < 0x80) - { - if (i+1 > n) return 0; - buf[i++] = (char)c; - return 1; - } - else if (c < 0x800) - { - if (i+2 > n) return 0; - buf[i++] = (char)(0xc0 + (c >> 6)); - buf[i++] = (char)(0x80 + (c & 0x3f)); - return 2; - } - else if (c >= 0xdc00 && c < 0xe000) - { - return 0; - } - else if (c >= 0xd800 && c < 0xdc00) - { - if (i+4 > n) return 0; - buf[i++] = (char)(0xf0 + (c >> 18)); - buf[i++] = (char)(0x80 + ((c >> 12) & 0x3f)); - buf[i++] = (char)(0x80 + ((c >> 6) & 0x3f)); - buf[i++] = (char)(0x80 + ((c ) & 0x3f)); - return 4; - } - //else if (c < 0x10000) - { - if (i+3 > n) return 0; - buf[i++] = (char)(0xe0 + (c >> 12)); - buf[i++] = (char)(0x80 + ((c>> 6) & 0x3f)); - buf[i++] = (char)(0x80 + ((c ) & 0x3f)); - return 3; - } - } - return 0; -} - -static ptrdiff_t ImTextStrToUtf8(char* buf, size_t buf_size, const ImWchar* in_text, const ImWchar* in_text_end) -{ - char* buf_out = buf; - const char* buf_end = buf + buf_size; - while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) - { - buf_out += ImTextCharToUtf8(buf_out, (uintptr_t)(buf_end-buf_out-1), (unsigned int)*in_text); - in_text++; - } - *buf_out = 0; - return buf_out - buf; -} - -static int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end) -{ - int bytes_count = 0; - while ((!in_text_end || in_text < in_text_end) && *in_text) - { - char dummy[5]; // FIXME-OPT - bytes_count += ImTextCharToUtf8(dummy, 5, (unsigned int)*in_text); - in_text++; - } - return bytes_count; -} - -const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const -{ - // Simple word-wrapping for English, not full-featured. Please submit failing cases! - // FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.) - - // For references, possible wrap point marked with ^ - // "aaa bbb, ccc,ddd. eee fff. ggg!" - // ^ ^ ^ ^ ^__ ^ ^ - - // List of hardcoded separators: .,;!?'" - - // Skip extra blanks after a line returns (that includes not counting them in width computation) - // e.g. "Hello world" --> "Hello" "World" - - // Cut words that cannot possibly fit within one line. - // e.g.: "The tropical fish" with ~5 characters worth of width --> "The tr" "opical" "fish" - - float line_width = 0.0f; - float word_width = 0.0f; - float blank_width = 0.0f; - - const char* word_end = text; - const char* prev_word_end = NULL; - bool inside_word = true; - - const char* s = text; - while (s < text_end) - { - unsigned int c = (unsigned int)*s; - const char* next_s; - if (c < 0x80) - next_s = s + 1; - else - next_s = s + ImTextCharFromUtf8(&c, s, text_end); - if (c == 0) - break; - - if (c == '\n') - { - line_width = word_width = blank_width = 0.0f; - inside_word = true; - s = next_s; - continue; - } - - const float char_width = ((size_t)c < IndexXAdvance.size()) ? IndexXAdvance[(size_t)c] * scale : FallbackXAdvance; - if (ImCharIsSpace(c)) - { - if (inside_word) - { - line_width += blank_width; - blank_width = 0.0f; - } - blank_width += char_width; - inside_word = false; - } - else - { - word_width += char_width; - if (inside_word) - { - word_end = next_s; - } - else - { - prev_word_end = word_end; - line_width += word_width + blank_width; - word_width = blank_width = 0.0f; - } - - // Allow wrapping after punctuation. - inside_word = !(c == '.' || c == ',' || c == ';' || c == '!' || c == '?' || c == '\"'); - } - - // We ignore blank width at the end of the line (they can be skipped) - if (line_width + word_width >= wrap_width) - { - // Words that cannot possibly fit within an entire line will be cut anywhere. - if (word_width < wrap_width) - s = prev_word_end ? prev_word_end : word_end; - break; - } - - s = next_s; - } - - return s; -} - -ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** remaining) const -{ - if (!text_end) - text_end = text_begin + strlen(text_begin); // FIXME-OPT: Need to avoid this. - - const float scale = size / FontSize; - const float line_height = FontSize * scale; - - ImVec2 text_size = ImVec2(0,0); - float line_width = 0.0f; - - const bool word_wrap_enabled = (wrap_width > 0.0f); - const char* word_wrap_eol = NULL; - - const char* s = text_begin; - while (s < text_end) - { - if (word_wrap_enabled) - { - // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. - if (!word_wrap_eol) - { - word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - line_width); - if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. - word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below - } - - if (s >= word_wrap_eol) - { - if (text_size.x < line_width) - text_size.x = line_width; - text_size.y += line_height; - line_width = 0.0f; - word_wrap_eol = NULL; - - // Wrapping skips upcoming blanks - while (s < text_end) - { - const char c = *s; - if (ImCharIsSpace(c)) { s++; } else if (c == '\n') { s++; break; } else { break; } - } - continue; - } - } - - // Decode and advance source (handle unlikely UTF-8 decoding failure by skipping to the next byte) - const char* prev_s = s; - unsigned int c = (unsigned int)*s; - if (c < 0x80) - { - s += 1; - } - else - { - s += ImTextCharFromUtf8(&c, s, text_end); - if (c == 0) - break; - } - - if (c == '\n') - { - text_size.x = ImMax(text_size.x, line_width); - text_size.y += line_height; - line_width = 0.0f; - continue; - } - - const float char_width = ((size_t)c < IndexXAdvance.size()) ? IndexXAdvance[(size_t)c] * scale : FallbackXAdvance; - if (line_width + char_width >= max_width) - { - s = prev_s; - break; - } - - line_width += char_width; - } - - if (line_width > 0 || text_size.y == 0.0f) - { - if (text_size.x < line_width) - text_size.x = line_width; - text_size.y += line_height; - } - - if (remaining) - *remaining = s; - - return text_size; -} - -ImVec2 ImFont::CalcTextSizeW(float size, float max_width, const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining) const -{ - if (!text_end) - text_end = text_begin + ImStrlenW(text_begin); - - const float scale = size / FontSize; - const float line_height = FontSize * scale; - - ImVec2 text_size = ImVec2(0,0); - float line_width = 0.0f; - - const ImWchar* s = text_begin; - while (s < text_end) - { - const unsigned int c = (unsigned int)(*s++); - - if (c == '\n') - { - text_size.x = ImMax(text_size.x, line_width); - text_size.y += line_height; - line_width = 0.0f; - continue; - } - - const float char_width = ((size_t)c < IndexXAdvance.size()) ? IndexXAdvance[(size_t)c] * scale : FallbackXAdvance; - if (line_width + char_width >= max_width) - { - s--; - break; - } - - line_width += char_width; - } - - if (line_width > 0 || text_size.y == 0.0f) - { - if (text_size.x < line_width) - text_size.x = line_width; - text_size.y += line_height; - } - - if (remaining) - *remaining = s; - - return text_size; -} - -void ImFont::RenderText(float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect_ref, const char* text_begin, const char* text_end, ImDrawList* draw_list, float wrap_width, const ImVec2* cpu_clip_max) const -{ - if (!text_end) - text_end = text_begin + strlen(text_begin); - - const float scale = size / FontSize; - const float line_height = FontSize * scale; - - // Align to be pixel perfect - pos.x = (float)(int)pos.x + DisplayOffset.x; - pos.y = (float)(int)pos.y + DisplayOffset.y; - - const bool word_wrap_enabled = (wrap_width > 0.0f); - const char* word_wrap_eol = NULL; - - ImVec4 clip_rect = clip_rect_ref; - if (cpu_clip_max) - { - clip_rect.z = ImMin(clip_rect.z, cpu_clip_max->x); - clip_rect.w = ImMin(clip_rect.w, cpu_clip_max->y); - } - float x = pos.x; - float y = pos.y; - - ImDrawVert* out_vertices = draw_list->vtx_write; - - const char* s = text_begin; - while (s < text_end) - { - if (word_wrap_enabled) - { - // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. - if (!word_wrap_eol) - { - word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - (x - pos.x)); - if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. - word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below - } - - if (s >= word_wrap_eol) - { - x = pos.x; - y += line_height; - word_wrap_eol = NULL; - - // Wrapping skips upcoming blanks - while (s < text_end) - { - const char c = *s; - if (ImCharIsSpace(c)) { s++; } else if (c == '\n') { s++; break; } else { break; } - } - continue; - } - } - - // Decode and advance source (handle unlikely UTF-8 decoding failure by skipping to the next byte) - unsigned int c = (unsigned int)*s; - if (c < 0x80) - { - s += 1; - } - else - { - s += ImTextCharFromUtf8(&c, s, text_end); - if (c == 0) - break; - } - - if (c == '\n') - { - x = pos.x; - y += line_height; - continue; - } - - float char_width = 0.0f; - if (const Glyph* glyph = FindGlyph((unsigned short)c)) - { - char_width = glyph->XAdvance * scale; - if (c != ' ' && c != '\t') - { - // Clipping on Y is more likely - float y1 = (float)(y + glyph->YOffset * scale); - float y2 = (float)(y1 + glyph->Height * scale); - if (y1 <= clip_rect.w && y2 >= clip_rect.y) - { - float x1 = (float)(x + glyph->XOffset * scale); - float x2 = (float)(x1 + glyph->Width * scale); - if (x1 <= clip_rect.z && x2 >= clip_rect.x) - { - // Render a character - float u1 = glyph->U0; - float v1 = glyph->V0; - float u2 = glyph->U1; - float v2 = glyph->V1; - - // CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quad and in the "max" direction (bottom-right) - if (cpu_clip_max) - { - if (x2 > cpu_clip_max->x) - { - const float clip_tx = (cpu_clip_max->x - x1) / (x2 - x1); - x2 = cpu_clip_max->x; - u2 = u1 + clip_tx * (u2 - u1); - } - if (y2 > cpu_clip_max->y) - { - const float clip_ty = (cpu_clip_max->y - y1) / (y2 - y1); - y2 = cpu_clip_max->y; - v2 = v1 + clip_ty * (v2 - v1); - } - } - - // NB: we are not calling PrimRectUV() here because non-inlined causes too much overhead in a debug build. - out_vertices[0].pos = ImVec2(x1, y1); - out_vertices[0].uv = ImVec2(u1, v1); - out_vertices[0].col = col; - - out_vertices[1].pos = ImVec2(x2, y1); - out_vertices[1].uv = ImVec2(u2, v1); - out_vertices[1].col = col; - - out_vertices[2].pos = ImVec2(x2, y2); - out_vertices[2].uv = ImVec2(u2, v2); - out_vertices[2].col = col; - - out_vertices[3] = out_vertices[0]; - out_vertices[4] = out_vertices[2]; - - out_vertices[5].pos = ImVec2(x1, y2); - out_vertices[5].uv = ImVec2(u1, v2); - out_vertices[5].col = col; - - out_vertices += 6; - } - } - } - } - - x += char_width; - } - - draw_list->vtx_write = out_vertices; + ColorButton(col, true); } //----------------------------------------------------------------------------- // PLATFORM DEPENDANT HELPERS //----------------------------------------------------------------------------- -#if defined(_MSC_VER) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) - -#ifndef _WINDOWS_ +#if defined(_WIN32) && !defined(_WINDOWS_) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS)) +#undef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #include #endif // Win32 API clipboard implementation +#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) + +#ifdef _MSC_VER +#pragma comment(lib, "user32") +#endif + static const char* GetClipboardTextFn_DefaultImpl() { static char* buf_local = NULL; @@ -9525,9 +9500,9 @@ static const char* GetClipboardTextFn_DefaultImpl() ImGui::MemFree(buf_local); buf_local = NULL; } - if (!OpenClipboard(NULL)) + if (!OpenClipboard(NULL)) return NULL; - HANDLE wbuf_handle = GetClipboardData(CF_UNICODETEXT); + HANDLE wbuf_handle = GetClipboardData(CF_UNICODETEXT); if (wbuf_handle == NULL) return NULL; if (ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle)) @@ -9536,24 +9511,23 @@ static const char* GetClipboardTextFn_DefaultImpl() buf_local = (char*)ImGui::MemAlloc(buf_len * sizeof(char)); ImTextStrToUtf8(buf_local, buf_len, wbuf_global, NULL); } - GlobalUnlock(wbuf_handle); - CloseClipboard(); + GlobalUnlock(wbuf_handle); + CloseClipboard(); return buf_local; } -// Win32 API clipboard implementation static void SetClipboardTextFn_DefaultImpl(const char* text) { if (!OpenClipboard(NULL)) return; const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1; - HGLOBAL wbuf_handle = GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar)); + HGLOBAL wbuf_handle = GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar)); if (wbuf_handle == NULL) return; - ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle); + ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle); ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL); - GlobalUnlock(wbuf_handle); + GlobalUnlock(wbuf_handle); EmptyClipboard(); SetClipboardData(CF_UNICODETEXT, wbuf_handle); CloseClipboard(); @@ -9570,7 +9544,7 @@ static const char* GetClipboardTextFn_DefaultImpl() // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers static void SetClipboardTextFn_DefaultImpl(const char* text) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; if (g.PrivateClipboard) { ImGui::MemFree(g.PrivateClipboard); @@ -9579,19 +9553,18 @@ static void SetClipboardTextFn_DefaultImpl(const char* text) const char* text_end = text + strlen(text); g.PrivateClipboard = (char*)ImGui::MemAlloc((size_t)(text_end - text) + 1); memcpy(g.PrivateClipboard, text, (size_t)(text_end - text)); - g.PrivateClipboard[(size_t)(text_end - text)] = 0; + g.PrivateClipboard[(int)(text_end - text)] = 0; } #endif -#if defined(_MSC_VER) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS) +// Win32 API IME support (for Asian languages, etc.) +#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS) -#ifndef _WINDOWS_ -#define WIN32_LEAN_AND_MEAN -#include -#endif -#include +#include +#ifdef _MSC_VER #pragma comment(lib, "imm32") +#endif static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y) { @@ -9609,1244 +9582,91 @@ static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y) #else -static void ImeSetInputScreenPosFn_DefaultImpl(int, int) -{ -} +static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {} #endif -#ifdef IMGUI_DISABLE_TEST_WINDOWS - -void ImGui::ShowUserGuide() {} -void ImGui::ShowStyleEditor(ImGuiStyle*) {} -void ImGui::ShowTestWindow(bool*) {} -void ImGui::ShowMetricsWindow(bool*) {} - -#else - //----------------------------------------------------------------------------- // HELP //----------------------------------------------------------------------------- -void ImGui::ShowUserGuide() +void ImGui::ShowMetricsWindow(bool* p_open) { - ImGuiState& g = *GImGui; - - ImGui::BulletText("Double-click on title bar to collapse window."); - ImGui::BulletText("Click and drag on lower right corner to resize window."); - ImGui::BulletText("Click and drag on any empty space to move window."); - ImGui::BulletText("Mouse Wheel to scroll."); - if (g.IO.FontAllowUserScaling) - ImGui::BulletText("CTRL+Mouse Wheel to zoom window contents."); - ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields."); - ImGui::BulletText("CTRL+Click on a slider to input text."); - ImGui::BulletText( - "While editing text:\n" - "- Hold SHIFT or use mouse to select text\n" - "- CTRL+Left/Right to word jump\n" - "- CTRL+A select all\n" - "- CTRL+X,CTRL+C,CTRL+V clipboard\n" - "- CTRL+Z,CTRL+Y undo/redo\n" - "- ESCAPE to revert\n" - "- You can apply arithmetic operators +,*,/ on numerical values.\n" - " Use +- to subtract.\n"); -} - -void ImGui::ShowStyleEditor(ImGuiStyle* ref) -{ - ImGuiState& g = *GImGui; - ImGuiStyle& style = g.Style; - - const ImGuiStyle def; // Default style - - if (ImGui::Button("Revert Style")) - g.Style = ref ? *ref : def; - if (ref) - { - ImGui::SameLine(); - if (ImGui::Button("Save Style")) - *ref = g.Style; - } - - ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.55f); - - if (ImGui::TreeNode("Sizes")) - { - ImGui::SliderFloat("Alpha", &style.Alpha, 0.20f, 1.0f, "%.2f"); // Not exposing zero here so user doesn't "lose" the UI. But application code could have a toggle to switch between zero and non-zero. - ImGui::SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, 20.0f, "%.0f"); - ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 16.0f, "%.0f"); - ImGui::SliderFloat("ChildWindowRounding", &style.ChildWindowRounding, 0.0f, 16.0f, "%.0f"); - ImGui::SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f"); - ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 16.0f, "%.0f"); - ImGui::SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f"); - ImGui::SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f"); - ImGui::SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f"); - ImGui::SliderFloat("IndentSpacing", &style.IndentSpacing, 0.0f, 20.0f, "%.0f"); - ImGui::SliderFloat("ScrollbarWidth", &style.ScrollbarWidth, 1.0f, 20.0f, "%.0f"); - ImGui::SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 16.0f, "%.0f"); - ImGui::SliderFloat("GrabMinSize", &style.GrabMinSize, 1.0f, 20.0f, "%.0f"); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Colors")) - { - static int output_dest = 0; - static bool output_only_modified = false; - if (ImGui::Button("Output Colors")) - { - if (output_dest == 0) - ImGui::LogToClipboard(); - else - ImGui::LogToTTY(); - ImGui::LogText("ImGuiStyle& style = ImGui::GetStyle();" STR_NEWLINE); - for (int i = 0; i < ImGuiCol_COUNT; i++) - { - const ImVec4& col = style.Colors[i]; - const char* name = ImGui::GetStyleColName(i); - if (!output_only_modified || memcmp(&col, (ref ? &ref->Colors[i] : &def.Colors[i]), sizeof(ImVec4)) != 0) - ImGui::LogText("style.Colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" STR_NEWLINE, name, 22 - strlen(name), "", col.x, col.y, col.z, col.w); - } - ImGui::LogFinish(); - } - ImGui::SameLine(); ImGui::PushItemWidth(150); ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY"); ImGui::PopItemWidth(); - ImGui::SameLine(); ImGui::Checkbox("Only Modified Fields", &output_only_modified); - - static ImGuiColorEditMode edit_mode = ImGuiColorEditMode_RGB; - ImGui::RadioButton("RGB", &edit_mode, ImGuiColorEditMode_RGB); - ImGui::SameLine(); - ImGui::RadioButton("HSV", &edit_mode, ImGuiColorEditMode_HSV); - ImGui::SameLine(); - ImGui::RadioButton("HEX", &edit_mode, ImGuiColorEditMode_HEX); - //ImGui::Text("Tip: Click on colored square to change edit mode."); - - static ImGuiTextFilter filter; - filter.Draw("Filter colors", 200); - - ImGui::BeginChild("#colors", ImVec2(0, 300), true); - - ImGui::ColorEditMode(edit_mode); - for (int i = 0; i < ImGuiCol_COUNT; i++) - { - const char* name = ImGui::GetStyleColName(i); - if (!filter.PassFilter(name)) - continue; - ImGui::PushID(i); - ImGui::ColorEdit4(name, (float*)&style.Colors[i], true); - if (memcmp(&style.Colors[i], (ref ? &ref->Colors[i] : &def.Colors[i]), sizeof(ImVec4)) != 0) - { - ImGui::SameLine(); if (ImGui::Button("Revert")) style.Colors[i] = ref ? ref->Colors[i] : def.Colors[i]; - if (ref) { ImGui::SameLine(); if (ImGui::Button("Save")) ref->Colors[i] = style.Colors[i]; } - } - ImGui::PopID(); - } - ImGui::EndChild(); - - ImGui::TreePop(); - } - - ImGui::PopItemWidth(); -} - -//----------------------------------------------------------------------------- -// SAMPLE CODE -//----------------------------------------------------------------------------- - -static void ShowExampleAppConsole(bool* opened); -static void ShowExampleAppLongText(bool* opened); -static void ShowExampleAppAutoResize(bool* opened); -static void ShowExampleAppFixedOverlay(bool* opened); -static void ShowExampleAppManipulatingWindowTitle(bool* opened); -static void ShowExampleAppCustomRendering(bool* opened); - -// Demonstrate ImGui features (unfortunately this makes this function a little bloated!) -void ImGui::ShowTestWindow(bool* opened) -{ - // Examples apps - static bool show_app_metrics = false; - static bool show_app_console = false; - static bool show_app_long_text = false; - static bool show_app_auto_resize = false; - static bool show_app_fixed_overlay = false; - static bool show_app_custom_rendering = false; - static bool show_app_manipulating_window_title = false; - if (show_app_metrics) - ImGui::ShowMetricsWindow(&show_app_metrics); - if (show_app_console) - ShowExampleAppConsole(&show_app_console); - if (show_app_long_text) - ShowExampleAppLongText(&show_app_long_text); - if (show_app_auto_resize) - ShowExampleAppAutoResize(&show_app_auto_resize); - if (show_app_fixed_overlay) - ShowExampleAppFixedOverlay(&show_app_fixed_overlay); - if (show_app_manipulating_window_title) - ShowExampleAppManipulatingWindowTitle(&show_app_manipulating_window_title); - if (show_app_custom_rendering) - ShowExampleAppCustomRendering(&show_app_custom_rendering); - - static bool no_titlebar = false; - static bool no_border = true; - static bool no_resize = false; - static bool no_move = false; - static bool no_scrollbar = false; - static bool no_collapse = false; - static float bg_alpha = 0.65f; - - // Demonstrate the various window flags. Typically you would just use the default. - ImGuiWindowFlags window_flags = 0; - if (no_titlebar) window_flags |= ImGuiWindowFlags_NoTitleBar; - if (!no_border) window_flags |= ImGuiWindowFlags_ShowBorders; - if (no_resize) window_flags |= ImGuiWindowFlags_NoResize; - if (no_move) window_flags |= ImGuiWindowFlags_NoMove; - if (no_scrollbar) window_flags |= ImGuiWindowFlags_NoScrollbar; - if (no_collapse) window_flags |= ImGuiWindowFlags_NoCollapse; - if (!ImGui::Begin("ImGui Test", opened, ImVec2(550,680), bg_alpha, window_flags)) - { - // Early out if the window is collapsed, as an optimization. - ImGui::End(); - return; - } - - //ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.65f); // 2/3 of the space for widget and 1/3 for labels - ImGui::PushItemWidth(-140); // Right align, keep 140 pixels for labels - - ImGui::Text("ImGui says hello."); - //ImGui::Text("MousePos (%g, %g)", ImGui::GetIO().MousePos.x, ImGui::GetIO().MousePos.y); - //ImGui::Text("MouseWheel %d", ImGui::GetIO().MouseWheel); - //ImGui::Text("KeyMods %s%s%s", ImGui::GetIO().KeyCtrl ? "CTRL" : "", ImGui::GetIO().KeyShift ? "SHIFT" : "", ImGui::GetIO().KeyAlt? "ALT" : ""); - //ImGui::Text("WantCaptureMouse: %d", ImGui::GetIO().WantCaptureMouse); - //ImGui::Text("WantCaptureKeyboard: %d", ImGui::GetIO().WantCaptureKeyboard); - - ImGui::Spacing(); - if (ImGui::CollapsingHeader("Help")) - { - ImGui::TextWrapped("This window is being created by the ShowTestWindow() function. Please refer to the code for programming reference.\n\nUser Guide:"); - ImGui::ShowUserGuide(); - } - - if (ImGui::CollapsingHeader("Window options")) - { - ImGui::Checkbox("no titlebar", &no_titlebar); ImGui::SameLine(150); - ImGui::Checkbox("no border", &no_border); ImGui::SameLine(300); - ImGui::Checkbox("no resize", &no_resize); - ImGui::Checkbox("no move", &no_move); ImGui::SameLine(150); - ImGui::Checkbox("no scrollbar", &no_scrollbar); ImGui::SameLine(300); - ImGui::Checkbox("no collapse", &no_collapse); - ImGui::SliderFloat("bg alpha", &bg_alpha, 0.0f, 1.0f); - - if (ImGui::TreeNode("Style")) - { - ImGui::ShowStyleEditor(); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Fonts", "Fonts (%d)", (int)ImGui::GetIO().Fonts->Fonts.size())) - { - ImGui::TextWrapped("Tip: Load fonts with GetIO().Fonts->AddFontFromFileTTF()."); - for (size_t i = 0; i < ImGui::GetIO().Fonts->Fonts.size(); i++) - { - ImFont* font = ImGui::GetIO().Fonts->Fonts[i]; - ImGui::BulletText("Font %d: %.2f pixels, %d glyphs", i, font->FontSize, font->Glyphs.size()); - ImGui::TreePush((void*)i); - ImGui::PushFont(font); - ImGui::Text("The quick brown fox jumps over the lazy dog"); - ImGui::PopFont(); - if (i > 0 && ImGui::Button("Set as default")) - { - ImGui::GetIO().Fonts->Fonts[i] = ImGui::GetIO().Fonts->Fonts[0]; - ImGui::GetIO().Fonts->Fonts[0] = font; - } - ImGui::SliderFloat("font scale", &font->Scale, 0.3f, 2.0f, "%.1f"); // scale only this font - ImGui::TreePop(); - } - static float window_scale = 1.0f; - ImGui::SliderFloat("this window scale", &window_scale, 0.3f, 2.0f, "%.1f"); // scale only this window - ImGui::SliderFloat("global scale", &ImGui::GetIO().FontGlobalScale, 0.3f, 2.0f, "%.1f"); // scale everything - ImGui::SetWindowFontScale(window_scale); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Logging")) - { - ImGui::LogButtons(); - ImGui::TreePop(); - } - } - - if (ImGui::CollapsingHeader("Widgets")) - { - static bool a=false; - if (ImGui::Button("Button")) { printf("Clicked\n"); a ^= 1; } - if (a) - { - ImGui::SameLine(); - ImGui::Text("Thanks for clicking me!"); - } - - if (ImGui::TreeNode("Tree")) - { - for (size_t i = 0; i < 5; i++) - { - if (ImGui::TreeNode((void*)i, "Child %d", i)) - { - ImGui::Text("blah blah"); - ImGui::SameLine(); - if (ImGui::SmallButton("print")) - printf("Child %d pressed", (int)i); - ImGui::TreePop(); - } - } - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Bullets")) - { - ImGui::BulletText("Bullet point 1"); - ImGui::BulletText("Bullet point 2\nOn multiple lines"); - ImGui::Bullet(); ImGui::Text("Bullet point 3 (two calls)"); - ImGui::Bullet(); ImGui::SmallButton("Button 1"); - ImGui::Bullet(); ImGui::SmallButton("Button 2"); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Colored Text")) - { - // Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility. - ImGui::TextColored(ImVec4(1.0f,0.0f,1.0f,1.0f), "Pink"); - ImGui::TextColored(ImVec4(1.0f,1.0f,0.0f,1.0f), "Yellow"); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Word Wrapping")) - { - // Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility. - ImGui::TextWrapped("This text should automatically wrap on the edge of the window. The current implementation for text wrapping follows simple rules that works for English and possibly other languages."); - ImGui::Spacing(); - - static float wrap_width = 200.0f; - ImGui::SliderFloat("Wrap width", &wrap_width, -20, 600, "%.0f"); - - ImGui::Text("Test paragraph 1:"); - ImGui::GetWindowDrawList()->AddRectFilled(ImGui::GetCursorScreenPos() + ImVec2(wrap_width, 0.0f), ImGui::GetCursorScreenPos() + ImVec2(wrap_width+10, ImGui::GetTextLineHeight()), 0xFFFF00FF); - ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); - ImGui::Text("lazy dog. This paragraph is made to fit within %.0f pixels. The quick brown fox jumps over the lazy dog.", wrap_width); - ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), 0xFF00FFFF); - ImGui::PopTextWrapPos(); - - ImGui::Text("Test paragraph 2:"); - ImGui::GetWindowDrawList()->AddRectFilled(ImGui::GetCursorScreenPos() + ImVec2(wrap_width, 0.0f), ImGui::GetCursorScreenPos() + ImVec2(wrap_width+10, ImGui::GetTextLineHeight()), 0xFFFF00FF); - ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); - ImGui::Text("aaaaaaaa bbbbbbbb, cccccccc,dddddddd. eeeeeeee ffffffff. gggggggg!hhhhhhhh"); - ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), 0xFF00FFFF); - ImGui::PopTextWrapPos(); - - ImGui::TreePop(); - } - - if (ImGui::TreeNode("UTF-8 Text")) - { - // UTF-8 test with Japanese characters - // (needs a suitable font, try Arial Unicode or M+ fonts http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html) - // Most compiler appears to support UTF-8 in source code (with Visual Studio you need to save your file as 'UTF-8 without signature') - // However for the sake for maximum portability here we are *not* including raw UTF-8 character in this source file, instead we encode the string with hexadecimal constants. - // In your own application be reasonable and use UTF-8 in source or retrieve the data from file system! - // Note that characters values are preserved even if the font cannot be displayed, so you can safely copy & paste garbled characters into another application. - ImGui::TextWrapped("CJK text will only appears if the font was loaded with the appropriate CJK character ranges. Call io.Font->LoadFromFileTTF() manually to load extra character ranges."); - ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)"); - ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)"); - static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"; - ImGui::InputText("UTF-8 input", buf, IM_ARRAYSIZE(buf)); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Clipping")) - { - static ImVec2 size(80, 20); - ImGui::TextWrapped("On a per-widget basis we are occasionally clipping text if it won't fit in its frame."); - ImGui::SliderFloat2("size", (float*)&size, 5.0f, 200.0f); - ImGui::Button("Line 1 hello\nLine 2 clip me!", size); - ImGui::TextWrapped("Otherwise we are doing coarser clipping + passing a scissor rectangle to the renderer. The system is designed to try minimizing both execution and rendering cost."); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Images")) - { - ImGui::TextWrapped("Below we are displaying the font texture (which is the only texture we have access to in this demo). Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. Hover the texture for a zoomed view!"); - ImVec2 tex_screen_pos = ImGui::GetCursorScreenPos(); - float tex_w = (float)ImGui::GetIO().Fonts->TexWidth; - float tex_h = (float)ImGui::GetIO().Fonts->TexHeight; - ImTextureID tex_id = ImGui::GetIO().Fonts->TexID; - ImGui::Image(tex_id, ImVec2(tex_w, tex_h), ImVec2(0,0), ImVec2(1,1), ImColor(255,255,255,255), ImColor(255,255,255,128)); - if (ImGui::IsItemHovered()) - { - ImGui::BeginTooltip(); - float focus_sz = 32.0f; - float focus_x = ImClamp(ImGui::GetMousePos().x - tex_screen_pos.x - focus_sz * 0.5f, 0.0f, tex_w - focus_sz); - float focus_y = ImClamp(ImGui::GetMousePos().y - tex_screen_pos.y - focus_sz * 0.5f, 0.0f, tex_h - focus_sz); - ImGui::Text("Min: (%.2f, %.2f)", focus_x, focus_y); - ImGui::Text("Max: (%.2f, %.2f)", focus_x + focus_sz, focus_y + focus_sz); - ImVec2 uv0 = ImVec2((focus_x) / tex_w, (focus_y) / tex_h); - ImVec2 uv1 = ImVec2((focus_x + focus_sz) / tex_w, (focus_y + focus_sz) / tex_h); - ImGui::Image(tex_id, ImVec2(128,128), uv0, uv1, ImColor(255,255,255,255), ImColor(255,255,255,128)); - ImGui::EndTooltip(); - } - ImGui::TextWrapped("And now some textured buttons.."); - static int pressed_count = 0; - for (int i = 0; i < 8; i++) - { - if (i > 0) - ImGui::SameLine(); - ImGui::PushID(i); - int frame_padding = -1 + i; // -1 padding uses default padding - if (ImGui::ImageButton(tex_id, ImVec2(32,32), ImVec2(0,0), ImVec2(32.0f/tex_w,32/tex_h), frame_padding)) - pressed_count += 1; - ImGui::PopID(); - } - ImGui::Text("Pressed %d times.", pressed_count); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Selectables")) - { - if (ImGui::TreeNode("Basic")) - { - static bool selected[3] = { false, true, false }; - ImGui::Selectable("1. I am selectable", &selected[0]); - ImGui::Selectable("2. I am selectable", &selected[1]); - ImGui::Text("3. I am not selectable"); - ImGui::Selectable("4. I am selectable", &selected[2]); - ImGui::TreePop(); - } - if (ImGui::TreeNode("Rendering more text into the same block")) - { - static bool selected[3] = { false, false, false }; - ImGui::Selectable("main.c", &selected[0]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes"); - ImGui::Selectable("Hello.cpp", &selected[1]); ImGui::SameLine(300); ImGui::Text("12,345 bytes"); - ImGui::Selectable("Hello.h", &selected[2]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes"); - ImGui::TreePop(); - } - if (ImGui::TreeNode("Grid")) - { - static bool selected[16] = { true, false, false, false, false, true, false, false, false, false, true, false, false, false, false, true }; - for (int i = 0; i < 16; i++) - { - ImGui::PushID(i); - if (ImGui::Selectable("Me", &selected[i], ImVec2(50,50))) - { - int x = i % 4, y = i / 4; - if (x > 0) selected[i - 1] ^= 1; - if (x < 3) selected[i + 1] ^= 1; - if (y > 0) selected[i - 4] ^= 1; - if (y < 3) selected[i + 4] ^= 1; - } - if ((i % 4) < 3) ImGui::SameLine(); - ImGui::PopID(); - } - ImGui::TreePop(); - } - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Popup, Menus")) - { - static int selected_fish = -1; - const char* names[] = { "Bream", "Haddock", "Mackerel", "Pollock", "Tilefish" }; - static bool toggles[] = { true, false, false, false, false }; - - { - static bool popup_open = false; - if (ImGui::Button("Select..")) - popup_open = true; - ImGui::SameLine(); - ImGui::Text(selected_fish == -1 ? "" : names[selected_fish]); - if (popup_open) - { - ImGui::BeginPopup(&popup_open); - ImGui::Text("Aquarium"); - ImGui::Separator(); - for (int i = 0; i < IM_ARRAYSIZE(names); i++) - { - if (ImGui::Selectable(names[i])) - { - selected_fish = i; - popup_open = false; - } - } - ImGui::EndPopup(); - } - } - { - static bool popup_open = false; - if (ImGui::Button("Toggle..")) - popup_open = true; - if (popup_open) - { - ImGui::BeginPopup(&popup_open); - for (int i = 0; i < IM_ARRAYSIZE(names); i++) - if (ImGui::MenuItem(names[i], "", &toggles[i])) - popup_open = false; - - ImGui::Separator(); - ImGui::Text("Tooltip here"); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("I am a tooltip over a popup"); - - ImGui::EndPopup(); - } - } - - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Filtered Text Input")) - { - static char buf1[64] = ""; ImGui::InputText("default", buf1, 64); - static char buf2[64] = ""; ImGui::InputText("decimal", buf2, 64, ImGuiInputTextFlags_CharsDecimal); - static char buf3[64] = ""; ImGui::InputText("hexadecimal", buf3, 64, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); - static char buf4[64] = ""; ImGui::InputText("uppercase", buf4, 64, ImGuiInputTextFlags_CharsUppercase); - static char buf5[64] = ""; ImGui::InputText("no blank", buf5, 64, ImGuiInputTextFlags_CharsNoBlank); - struct TextFilters { static int FilterImGuiLetters(ImGuiTextEditCallbackData* data) { if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar)) return 0; return 1; } }; - static char buf6[64] = ""; ImGui::InputText("\"imgui\" letters", buf6, 64, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); - ImGui::TreePop(); - } - - static bool check = true; - ImGui::Checkbox("checkbox", &check); - - static int e = 0; - ImGui::RadioButton("radio a", &e, 0); ImGui::SameLine(); - ImGui::RadioButton("radio b", &e, 1); ImGui::SameLine(); - ImGui::RadioButton("radio c", &e, 2); - - // Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style. - for (int i = 0; i < 7; i++) - { - if (i > 0) ImGui::SameLine(); - ImGui::PushID(i); - ImGui::PushStyleColor(ImGuiCol_Button, ImColor::HSV(i/7.0f, 0.6f, 0.6f)); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImColor::HSV(i/7.0f, 0.7f, 0.7f)); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImColor::HSV(i/7.0f, 0.8f, 0.8f)); - ImGui::Button("Click"); - ImGui::PopStyleColor(3); - ImGui::PopID(); - } - - ImGui::Text("Hover over me"); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("I am a tooltip"); - - ImGui::SameLine(); - ImGui::Text("- or me"); - if (ImGui::IsItemHovered()) - { - ImGui::BeginTooltip(); - ImGui::Text("I am a fancy tooltip"); - static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; - ImGui::PlotLines("Curve", arr, IM_ARRAYSIZE(arr)); - ImGui::EndTooltip(); - } - - // Testing IMGUI_ONCE_UPON_A_FRAME macro - //for (int i = 0; i < 5; i++) - //{ - // IMGUI_ONCE_UPON_A_FRAME - // { - // ImGui::Text("This will be displayed only once."); - // } - //} - - ImGui::Separator(); - - ImGui::LabelText("label", "Value"); - - static int item = 1; - ImGui::Combo("combo", &item, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); - - const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK" }; - static int item2 = -1; - ImGui::Combo("combo scroll", &item2, items, IM_ARRAYSIZE(items)); - - { - static char str0[128] = "Hello, world!"; - static int i0=123; - static float f0=0.001f; - ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0)); - ImGui::InputInt("input int", &i0); - ImGui::InputFloat("input float", &f0, 0.01f, 1.0f); - - static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; - ImGui::InputFloat3("input float3", vec4a); - } - - { - static int i1=50; - static int i2=42; - ImGui::DragInt("drag int", &i1, 1); - ImGui::SameLine(); - ImGui::TextColored(ImColor(170,170,170,255), "(?)"); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("Click and drag to edit value.\nHold SHIFT/ALT for faster/slower edit.\nDouble-click or CTRL+click to input text"); - - ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%.0f%%"); - - static float f1=1.00f; - static float f2=0.0067f; - ImGui::DragFloat("drag float", &f1, 1.0f); - ImGui::DragFloat("drag small float", &f2, 0.0001f, 0.0f, 0.0f, "%.06f ns"); - } - - { - static int i1=0; - //static int i2=42; - ImGui::SliderInt("slider int 0..3", &i1, 0, 3); - //ImGui::SliderInt("slider int -100..100", &i2, -100, 100); - - static float f1=0.123f; - static float f2=0.0f; - ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f"); - ImGui::SliderFloat("slider log float", &f2, -10.0f, 10.0f, "%.4f", 3.0f); - static float angle = 0.0f; - ImGui::SliderAngle("slider angle", &angle); - } - - static float col1[3] = { 1.0f,0.0f,0.2f }; - static float col2[4] = { 0.4f,0.7f,0.0f,0.5f }; - ImGui::ColorEdit3("color 1", col1); - ImGui::ColorEdit4("color 2", col2); - - const char* listbox_items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; - static int listbox_item_current = 1; - ImGui::ListBox("listbox\n(single select)", &listbox_item_current, listbox_items, IM_ARRAYSIZE(listbox_items), 4); - - //static int listbox_item_current2 = 2; - //ImGui::PushItemWidth(-1); - //ImGui::ListBox("##listbox2", &listbox_item_current2, listbox_items, IM_ARRAYSIZE(listbox_items), 4); - //ImGui::PopItemWidth(); - - if (ImGui::TreeNode("Multi-component Widgets")) - { - ImGui::Unindent(); - - static float vec4f[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; - static int vec4i[4] = { 1, 5, 100, 255 }; - - ImGui::InputFloat2("input float2", vec4f); - ImGui::DragFloat2("drag float2", vec4f, 0.01f, 0.0f, 1.0f); - ImGui::SliderFloat2("slider float2", vec4f, 0.0f, 1.0f); - ImGui::DragInt2("drag int2", vec4i, 1, 0, 255); - ImGui::InputInt2("input int2", vec4i); - ImGui::SliderInt2("slider int2", vec4i, 0, 255); - - ImGui::InputFloat3("input float3", vec4f); - ImGui::DragFloat3("drag float3", vec4f, 0.01f, 0.0f, 1.0f); - ImGui::SliderFloat3("slider float3", vec4f, 0.0f, 1.0f); - ImGui::DragInt3("drag int3", vec4i, 1, 0, 255); - ImGui::InputInt3("input int3", vec4i); - ImGui::SliderInt3("slider int3", vec4i, 0, 255); - - ImGui::InputFloat4("input float4", vec4f); - ImGui::DragFloat4("drag float4", vec4f, 0.01f, 0.0f, 1.0f); - ImGui::SliderFloat4("slider float4", vec4f, 0.0f, 1.0f); - ImGui::InputInt4("input int4", vec4i); - ImGui::DragInt4("drag int4", vec4i, 1, 0, 255); - ImGui::SliderInt4("slider int4", vec4i, 0, 255); - - ImGui::Indent(); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Vertical Sliders")) - { - ImGui::Unindent(); - const float spacing = 4; - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing)); - - static int int_value = 0; - ImGui::VSliderInt("##int", ImVec2(18,160), &int_value, 0, 5); - ImGui::SameLine(); - - static float values[7] = { 0.0f, 0.60f, 0.35f, 0.9f, 0.70f, 0.20f, 0.0f }; - ImGui::PushID("set1"); - for (int i = 0; i < 7; i++) - { - if (i > 0) ImGui::SameLine(); - ImGui::PushID(i); - ImGui::PushStyleColor(ImGuiCol_FrameBg, ImColor::HSV(i/7.0f, 0.5f, 0.5f)); - ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, ImColor::HSV(i/7.0f, 0.6f, 0.5f)); - ImGui::PushStyleColor(ImGuiCol_FrameBgActive, ImColor::HSV(i/7.0f, 0.7f, 0.5f)); - ImGui::PushStyleColor(ImGuiCol_SliderGrab, ImColor::HSV(i/7.0f, 0.9f, 0.9f)); - ImGui::VSliderFloat("##v", ImVec2(18,160), &values[i], 0.0f, 1.0f, ""); - if (ImGui::IsItemActive() || ImGui::IsItemHovered()) - ImGui::SetTooltip("%.3f", values[i]); - ImGui::PopStyleColor(4); - ImGui::PopID(); - } - ImGui::PopID(); - - ImGui::SameLine(); - ImGui::PushID("set2"); - static float values2[4] = { 0.20f, 0.80f, 0.40f, 0.25f }; - const int rows = 3; - const ImVec2 small_slider_size(18, (160.0f-(rows-1)*spacing)/rows); - for (int nx = 0; nx < 4; nx++) - { - if (nx > 0) ImGui::SameLine(); - ImGui::BeginGroup(); - for (int ny = 0; ny < rows; ny++) - { - ImGui::PushID(nx*rows+ny); - ImGui::VSliderFloat("##v", small_slider_size, &values2[nx], 0.0f, 1.0f, ""); - if (ImGui::IsItemActive() || ImGui::IsItemHovered()) - ImGui::SetTooltip("%.3f", values2[nx]); - ImGui::PopID(); - } - ImGui::EndGroup(); - } - ImGui::PopID(); - - ImGui::SameLine(); - ImGui::PushID("set3"); - for (int i = 0; i < 4; i++) - { - if (i > 0) ImGui::SameLine(); - ImGui::PushID(i); - ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 40); - ImGui::VSliderFloat("##v", ImVec2(40,160), &values[i], 0.0f, 1.0f, "%.2f"); - ImGui::PopStyleVar(); - ImGui::PopID(); - } - ImGui::PopID(); - ImGui::PopStyleVar(); - - ImGui::Indent(); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Dragging")) - { - // You can use ImGui::GetItemActiveDragDelta() to query for the dragged amount on any widget. - static ImVec2 value_raw(0.0f, 0.0f); - static ImVec2 value_with_lock_threshold(0.0f, 0.0f); - ImGui::Button("Drag Me"); - if (ImGui::IsItemActive()) - { - value_raw = ImGui::GetMouseDragDelta(0, 0.0f); - value_with_lock_threshold = ImGui::GetMouseDragDelta(0); - //ImGui::SetTooltip("Delta: %.1f, %.1f", value.x, value.y); - - // Draw a line between the button and the mouse cursor - ImDrawList* draw_list = ImGui::GetWindowDrawList(); - draw_list->PushClipRectFullScreen(); - draw_list->AddLine(ImGui::CalcItemRectClosestPoint(ImGui::GetIO().MousePos, true, -2.0f), ImGui::GetIO().MousePos, ImColor(ImGui::GetStyle().Colors[ImGuiCol_Button]), 4.0f); - draw_list->PopClipRect(); - } - ImGui::SameLine(); ImGui::Text("Raw (%.1f, %.1f), WithLockThresold (%.1f, %.1f)", value_raw.x, value_raw.y, value_with_lock_threshold.x, value_with_lock_threshold.y); - ImGui::TreePop(); - } - } - - if (ImGui::CollapsingHeader("Graphs widgets")) - { - static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; - ImGui::PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr)); - - static bool pause; - static ImVector values; if (values.empty()) { values.resize(90); memset(&values.front(), 0, values.size()*sizeof(float)); } - static size_t values_offset = 0; - if (!pause) - { - // create dummy data at fixed 60 hz rate - static float refresh_time = -1.0f; - if (ImGui::GetTime() > refresh_time + 1.0f/60.0f) - { - refresh_time = ImGui::GetTime(); - static float phase = 0.0f; - values[values_offset] = cosf(phase); - values_offset = (values_offset+1)%values.size(); - phase += 0.10f*values_offset; - } - } - ImGui::PlotLines("##Graph", &values.front(), (int)values.size(), (int)values_offset, "avg 0.0", -1.0f, 1.0f, ImVec2(0,80)); - ImGui::SameLine(0, (int)ImGui::GetStyle().ItemInnerSpacing.x); - ImGui::BeginGroup(); - ImGui::Text("Graph"); - ImGui::Checkbox("pause", &pause); - ImGui::EndGroup(); - ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0,80)); - } - - if (ImGui::CollapsingHeader("Layout")) - { - if (ImGui::TreeNode("Widgets Alignment")) - { - static float f = 0.0f; - ImGui::Text("Fixed: 100 pixels"); - ImGui::PushItemWidth(100); - ImGui::InputFloat("float##1", &f); - ImGui::PopItemWidth(); - - ImGui::Text("Proportional: 50%% of window width"); - ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f); - ImGui::InputFloat("float##2", &f); - ImGui::PopItemWidth(); - - ImGui::Text("Right-aligned: Leave 100 pixels for label"); - ImGui::PushItemWidth(-100); - ImGui::InputFloat("float##3", &f); - ImGui::PopItemWidth(); - - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Basic Horizontal Layout")) - { - ImGui::TextWrapped("(Use ImGui::SameLine() to keep adding items to the right of the preceeding item)"); - - // Text - ImGui::Text("Two items: Hello"); - ImGui::SameLine(); - ImGui::TextColored(ImVec4(1,1,0,1), "Sailor"); - - // Adjust spacing - ImGui::Text("More spacing: Hello"); - ImGui::SameLine(0, 20); - ImGui::TextColored(ImVec4(1,1,0,1), "Sailor"); - - // Button - ImGui::AlignFirstTextHeightToWidgets(); - ImGui::Text("Normal buttons"); ImGui::SameLine(); - ImGui::Button("Banana"); ImGui::SameLine(); - ImGui::Button("Apple"); ImGui::SameLine(); - ImGui::Button("Corniflower"); - - // Button - ImGui::Text("Small buttons"); ImGui::SameLine(); - ImGui::SmallButton("Like this one"); ImGui::SameLine(); - ImGui::Text("can fit within a text block."); - - // Aligned to arbitrary position. Easy/cheap column. - ImGui::Text("Aligned"); - ImGui::SameLine(150); ImGui::Text("x=150"); - ImGui::SameLine(300); ImGui::Text("x=300"); - ImGui::Text("Aligned"); - ImGui::SameLine(150); ImGui::SmallButton("x=150"); - ImGui::SameLine(300); ImGui::SmallButton("x=300"); - - // Checkbox - static bool c1=false,c2=false,c3=false,c4=false; - ImGui::Checkbox("My", &c1); ImGui::SameLine(); - ImGui::Checkbox("Tailor", &c2); ImGui::SameLine(); - ImGui::Checkbox("Is", &c3); ImGui::SameLine(); - ImGui::Checkbox("Rich", &c4); - - // Various - static float f0=1.0f, f1=2.0f, f2=3.0f; - ImGui::PushItemWidth(80); - const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD" }; - static int item = -1; - ImGui::Combo("Combo", &item, items, IM_ARRAYSIZE(items)); ImGui::SameLine(); - ImGui::SliderFloat("X", &f0, 0.0f,5.0f); ImGui::SameLine(); - ImGui::SliderFloat("Y", &f1, 0.0f,5.0f); ImGui::SameLine(); - ImGui::SliderFloat("Z", &f2, 0.0f,5.0f); - ImGui::PopItemWidth(); - - ImGui::PushItemWidth(80); - ImGui::Text("Lists:"); - static int selection[4] = { 0, 1, 2, 3 }; - for (int i = 0; i < 4; i++) - { - if (i > 0) ImGui::SameLine(); - ImGui::PushID(i); - ImGui::ListBox("", &selection[i], items, IM_ARRAYSIZE(items)); - ImGui::PopID(); - //if (ImGui::IsItemHovered()) ImGui::SetTooltip("ListBox %d hovered", i); - } - ImGui::PopItemWidth(); - - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Groups")) - { - ImGui::TextWrapped("(Using ImGui::BeginGroup()/EndGroup() to layout items)"); - - ImVec2 size; - ImGui::BeginGroup(); - { - ImGui::BeginGroup(); - ImGui::Button("AAA"); - ImGui::SameLine(); - ImGui::Button("BBB"); - ImGui::SameLine(); - ImGui::BeginGroup(); - ImGui::Button("CCC"); - ImGui::Button("DDD"); - ImGui::EndGroup(); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("Group hovered"); - ImGui::SameLine(); - ImGui::Button("EEE"); - ImGui::EndGroup(); - - // Capture the group size and create widgets using the same size - size = ImGui::GetItemRectSize(); - const float values[5] = { 0.5f, 0.20f, 0.80f, 0.60f, 0.25f }; - ImGui::PlotHistogram("##values", values, IM_ARRAYSIZE(values), 0, NULL, 0.0f, 1.0f, size); - } - ImGui::Button("ACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f,size.y)); - ImGui::SameLine(); - ImGui::Button("REACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f,size.y)); - ImGui::EndGroup(); - ImGui::SameLine(); - - ImGui::Button("LEVERAGE\nBUZZWORD", size); - ImGui::SameLine(); - - ImGui::ListBoxHeader("List", size); - ImGui::Selectable("Selected", true); - ImGui::Selectable("Not Selected", false); - ImGui::ListBoxFooter(); - - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Text Baseline Alignment")) - { - ImGui::TextWrapped("(This is testing the vertical alignment that occurs on text to keep it at the same baseline as widgets. Lines only composed of text or \"small\" widgets fit in less vertical spaces than lines with normal widgets)"); - - ImGui::Text("One\nTwo\nThree"); ImGui::SameLine(); - ImGui::Text("Hello\nWorld"); ImGui::SameLine(); - ImGui::Text("Banana"); - - ImGui::Text("Banana"); ImGui::SameLine(); - ImGui::Text("Hello\nWorld"); ImGui::SameLine(); - ImGui::Text("One\nTwo\nThree"); - - ImGui::Button("HOP"); ImGui::SameLine(); - ImGui::Text("Banana"); ImGui::SameLine(); - ImGui::Text("Hello\nWorld"); ImGui::SameLine(); - ImGui::Text("Banana"); - - ImGui::Button("HOP"); ImGui::SameLine(); - ImGui::Text("Hello\nWorld"); ImGui::SameLine(); - ImGui::Text("Banana"); - - ImGui::Button("TEST"); ImGui::SameLine(); - ImGui::Text("TEST"); ImGui::SameLine(); - ImGui::SmallButton("TEST"); - - ImGui::AlignFirstTextHeightToWidgets(); // If your line starts with text, call this to align it to upcoming widgets. - ImGui::Text("Text aligned to Widget"); ImGui::SameLine(); - ImGui::Button("Widget"); ImGui::SameLine(); - ImGui::Text("Widget"); ImGui::SameLine(); - ImGui::SmallButton("Widget"); - - ImGui::TreePop(); - } - } - - if (ImGui::CollapsingHeader("Child regions")) - { - ImGui::Text("Without border"); - static int line = 50; - bool goto_line = ImGui::Button("Goto"); - ImGui::SameLine(); - ImGui::PushItemWidth(100); - goto_line |= ImGui::InputInt("##Line", &line, 0, 0, ImGuiInputTextFlags_EnterReturnsTrue); - ImGui::PopItemWidth(); - ImGui::BeginChild("Sub1", ImVec2(ImGui::GetWindowWidth() * 0.5f,300)); - for (int i = 0; i < 100; i++) - { - ImGui::Text("%04d: scrollable region", i); - if (goto_line && line == i) - ImGui::SetScrollPosHere(); - } - if (goto_line && line >= 100) - ImGui::SetScrollPosHere(); - ImGui::EndChild(); - - ImGui::SameLine(); - - ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, 5.0f); - ImGui::BeginChild("Sub2", ImVec2(0,300), true); - ImGui::Text("With border"); - ImGui::Columns(2); - for (int i = 0; i < 100; i++) - { - if (i == 50) - ImGui::NextColumn(); - char buf[32]; - ImFormatString(buf, IM_ARRAYSIZE(buf), "%08x", i*5731); - ImGui::Button(buf); - } - ImGui::EndChild(); - ImGui::PopStyleVar(); - } - - if (ImGui::CollapsingHeader("Columns")) - { - // Basic columns - ImGui::Text("Basic:"); - ImGui::Columns(4, "mycolumns"); - ImGui::Separator(); - ImGui::Text("ID"); ImGui::NextColumn(); - ImGui::Text("Name"); ImGui::NextColumn(); - ImGui::Text("Path"); ImGui::NextColumn(); - ImGui::Text("Flags"); ImGui::NextColumn(); - ImGui::Separator(); - const char* names[3] = { "Robert", "Stephanie", "C64" }; - const char* paths[3] = { "/path/robert", "/path/stephanie", "/path/computer" }; - for (int i = 0; i < 3; i++) - { - ImGui::Text("%04d", i); ImGui::NextColumn(); - ImGui::Text(names[i]); ImGui::NextColumn(); - ImGui::Text(paths[i]); ImGui::NextColumn(); - ImGui::Text("...."); ImGui::NextColumn(); - } - ImGui::Columns(1); - - ImGui::Separator(); - ImGui::Spacing(); - - // Scrolling columns - /* - ImGui::Text("Scrolling:"); - ImGui::BeginChild("##header", ImVec2(0, ImGui::GetTextLineHeightWithSpacing()+ImGui::GetStyle().ItemSpacing.y)); - ImGui::Columns(3); - ImGui::Text("ID"); ImGui::NextColumn(); - ImGui::Text("Name"); ImGui::NextColumn(); - ImGui::Text("Path"); ImGui::NextColumn(); - ImGui::Columns(1); - ImGui::Separator(); - ImGui::EndChild(); - ImGui::BeginChild("##scrollingregion", ImVec2(0, 60)); - ImGui::Columns(3); - for (int i = 0; i < 10; i++) - { - ImGui::Text("%04d", i); ImGui::NextColumn(); - ImGui::Text("Foobar"); ImGui::NextColumn(); - ImGui::Text("/path/foobar/%04d/", i); ImGui::NextColumn(); - } - ImGui::Columns(1); - ImGui::EndChild(); - - ImGui::Separator(); - ImGui::Spacing(); - */ - - // Create multiple items in a same cell before switching to next column - ImGui::Text("Mixed items:"); - ImGui::Columns(3, "mixed"); - ImGui::Separator(); - - static int e = 0; - ImGui::Text("Hello"); - ImGui::Button("Banana"); - ImGui::RadioButton("radio a", &e, 0); - ImGui::NextColumn(); - - ImGui::Text("ImGui"); - ImGui::Button("Apple"); - ImGui::RadioButton("radio b", &e, 1); - static float foo = 1.0f; - ImGui::InputFloat("red", &foo, 0.05f, 0, 3); - ImGui::Text("An extra line here."); - ImGui::NextColumn(); - - ImGui::Text("Sailor"); - ImGui::Button("Corniflower"); - ImGui::RadioButton("radio c", &e, 2); - static float bar = 1.0f; - ImGui::InputFloat("blue", &bar, 0.05f, 0, 3); - ImGui::NextColumn(); - - if (ImGui::CollapsingHeader("Category A")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); - if (ImGui::CollapsingHeader("Category B")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); - if (ImGui::CollapsingHeader("Category C")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); - ImGui::Columns(1); - - ImGui::Separator(); - ImGui::Spacing(); - - // Tree items - ImGui::Text("Tree items:"); - ImGui::Columns(2, "tree items"); - ImGui::Separator(); - if (ImGui::TreeNode("Hello")) { ImGui::BulletText("Sailor"); ImGui::TreePop(); } ImGui::NextColumn(); - if (ImGui::TreeNode("Bonjour")) { ImGui::BulletText("Marin"); ImGui::TreePop(); } ImGui::NextColumn(); - ImGui::Columns(1); - - ImGui::Separator(); - ImGui::Spacing(); - - // Word-wrapping - ImGui::Text("Word-wrapping:"); - ImGui::Columns(2, "word-wrapping"); - ImGui::Separator(); - ImGui::TextWrapped("The quick brown fox jumps over the lazy dog."); - ImGui::Text("Hello Left"); - ImGui::NextColumn(); - ImGui::TextWrapped("The quick brown fox jumps over the lazy dog."); - ImGui::Text("Hello Right"); - ImGui::Columns(1); - - ImGui::Separator(); - ImGui::Spacing(); - - if (ImGui::TreeNode("Inside a tree..")) - { - if (ImGui::TreeNode("node 1 (with borders)")) - { - ImGui::Columns(4); - for (int i = 0; i < 8; i++) - { - ImGui::Text("%c%c%c", 'a'+i, 'a'+i, 'a'+i); - ImGui::NextColumn(); - } - ImGui::Columns(1); - ImGui::TreePop(); - } - if (ImGui::TreeNode("node 2 (without borders)")) - { - ImGui::Columns(4, NULL, false); - for (int i = 0; i < 8; i++) - { - ImGui::Text("%c%c%c", 'a'+i, 'a'+i, 'a'+i); - ImGui::NextColumn(); - } - ImGui::Columns(1); - ImGui::TreePop(); - } - ImGui::TreePop(); - } - } - - if (ImGui::CollapsingHeader("Filtering")) - { - static ImGuiTextFilter filter; - ImGui::Text("Filter usage:\n" - " \"\" display all lines\n" - " \"xxx\" display lines containing \"xxx\"\n" - " \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n" - " \"-xxx\" hide lines containing \"xxx\""); - filter.Draw(); - const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" }; - for (size_t i = 0; i < IM_ARRAYSIZE(lines); i++) - if (filter.PassFilter(lines[i])) - ImGui::BulletText("%s", lines[i]); - } - - if (ImGui::CollapsingHeader("Keyboard, Mouse & Focus")) - { - if (ImGui::TreeNode("Tabbing")) - { - ImGui::Text("Use TAB/SHIFT+TAB to cycle thru keyboard editable fields."); - static char buf[32] = "dummy"; - ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); - ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); - ImGui::InputText("3", buf, IM_ARRAYSIZE(buf)); - ImGui::PushAllowKeyboardFocus(false); - ImGui::InputText("4 (tab skip)", buf, IM_ARRAYSIZE(buf)); - //ImGui::SameLine(); ImGui::Text("(?)"); if (ImGui::IsHovered()) ImGui::SetTooltip("Use ImGui::PushAllowKeyboardFocus(bool)\nto disable tabbing through certain widgets."); - ImGui::PopAllowKeyboardFocus(); - ImGui::InputText("5", buf, IM_ARRAYSIZE(buf)); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Focus from code")) - { - bool focus_1 = ImGui::Button("Focus on 1"); ImGui::SameLine(); - bool focus_2 = ImGui::Button("Focus on 2"); ImGui::SameLine(); - bool focus_3 = ImGui::Button("Focus on 3"); - int has_focus = 0; - static char buf[128] = "click on a button to set focus"; - - if (focus_1) ImGui::SetKeyboardFocusHere(); - ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); - if (ImGui::IsItemActive()) has_focus = 1; - - if (focus_2) ImGui::SetKeyboardFocusHere(); - ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); - if (ImGui::IsItemActive()) has_focus = 2; - - ImGui::PushAllowKeyboardFocus(false); - if (focus_3) ImGui::SetKeyboardFocusHere(); - ImGui::InputText("3 (tab skip)", buf, IM_ARRAYSIZE(buf)); - if (ImGui::IsItemActive()) has_focus = 3; - ImGui::PopAllowKeyboardFocus(); - if (has_focus) - ImGui::Text("Item with focus: %d", has_focus); - else - ImGui::Text("Item with focus: "); - ImGui::TextWrapped("Cursor & selection are preserved when refocusing last used item in code."); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Mouse cursors")) - { - ImGui::TextWrapped("(Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. You can also set io.MouseDrawCursor to ask ImGui to render the cursor for you in software)"); - ImGui::Checkbox("io.MouseDrawCursor", &ImGui::GetIO().MouseDrawCursor); - ImGui::Text("Hover to see mouse cursors:"); - for (int i = 0; i < ImGuiMouseCursor_Count_; i++) - { - char label[32]; - sprintf(label, "Mouse cursor %d", i); - ImGui::Bullet(); ImGui::Selectable(label, false); - if (ImGui::IsItemHovered()) - ImGui::SetMouseCursor(i); - } - ImGui::TreePop(); - } - } - - if (ImGui::CollapsingHeader("App Examples")) - { - ImGui::Checkbox("Metrics", &show_app_metrics); - ImGui::Checkbox("Console", &show_app_console); - ImGui::Checkbox("Long text display", &show_app_long_text); - ImGui::Checkbox("Auto-resizing window", &show_app_auto_resize); - ImGui::Checkbox("Simple overlay", &show_app_fixed_overlay); - ImGui::Checkbox("Manipulating window title", &show_app_manipulating_window_title); - ImGui::Checkbox("Custom rendering", &show_app_custom_rendering); - } - - ImGui::End(); -} - -void ImGui::ShowMetricsWindow(bool* opened) -{ - if (ImGui::Begin("ImGui Metrics", opened)) + if (ImGui::Begin("ImGui Metrics", p_open)) { ImGui::Text("ImGui %s", ImGui::GetVersion()); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); - ImGui::Text("%d vertices", ImGui::GetIO().MetricsRenderVertices); + ImGui::Text("%d vertices, %d indices (%d triangles)", ImGui::GetIO().MetricsRenderVertices, ImGui::GetIO().MetricsRenderIndices, ImGui::GetIO().MetricsRenderIndices / 3); + ImGui::Text("%d allocations", ImGui::GetIO().MetricsAllocs); + static bool show_clip_rects = true; + ImGui::Checkbox("Show clipping rectangles when hovering a ImDrawCmd", &show_clip_rects); ImGui::Separator(); struct Funcs { static void NodeDrawList(ImDrawList* draw_list, const char* label) { - bool node_opened = ImGui::TreeNode(draw_list, "%s: %d vtx, %d cmds", label, draw_list->vtx_buffer.size(), draw_list->commands.size()); + bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size); if (draw_list == ImGui::GetWindowDrawList()) { ImGui::SameLine(); ImGui::TextColored(ImColor(255,100,100), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered) - } - if (!node_opened) + if (node_open) ImGui::TreePop(); return; - for (const ImDrawCmd* pcmd = draw_list->commands.begin(); pcmd < draw_list->commands.end(); pcmd++) - if (pcmd->user_callback) - ImGui::BulletText("Callback %p, user_data %p", pcmd->user_callback, pcmd->user_callback_data); - else - ImGui::BulletText("Draw %d vtx, tex = %p", pcmd->vtx_count, pcmd->texture_id); + } + if (!node_open) + return; + + ImDrawList* overlay_draw_list = &GImGui->OverlayDrawList; // Render additional visuals into the top-most draw list + overlay_draw_list->PushClipRectFullScreen(); + int elem_offset = 0; + for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++) + { + if (pcmd->UserCallback) + { + ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData); + continue; + } + ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; + bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "Draw %-4d %s vtx, tex = %p, clip_rect = (%.0f,%.0f)..(%.0f,%.0f)", pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); + if (show_clip_rects && ImGui::IsItemHovered()) + { + ImRect clip_rect = pcmd->ClipRect; + ImRect vtxs_rect; + for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++) + vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos); + clip_rect.Floor(); overlay_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,255,0,255)); + vtxs_rect.Floor(); overlay_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,0,255,255)); + } + if (!pcmd_node_open) + continue; + ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. + while (clipper.Step()) + for (int prim = clipper.DisplayStart, vtx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++) + { + char buf[300], *buf_p = buf; + ImVec2 triangles_pos[3]; + for (int n = 0; n < 3; n++, vtx_i++) + { + ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[vtx_i] : vtx_i]; + triangles_pos[n] = v.pos; + buf_p += sprintf(buf_p, "%s %04d { pos = (%8.2f,%8.2f), uv = (%.6f,%.6f), col = %08X }\n", (n == 0) ? "vtx" : " ", vtx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col); + } + ImGui::Selectable(buf, false); + if (ImGui::IsItemHovered()) + overlay_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f, false); // Add triangle without AA, more readable for large-thin triangle + } + ImGui::TreePop(); + } + overlay_draw_list->PopClipRect(); ImGui::TreePop(); } static void NodeWindows(ImVector& windows, const char* label) { - if (!ImGui::TreeNode(label, "%s (%d)", label, (int)windows.size())) + if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size)) return; - for (int i = 0; i < (int)windows.size(); i++) + for (int i = 0; i < windows.Size; i++) Funcs::NodeWindow(windows[i], "Window"); ImGui::TreePop(); } @@ -10857,807 +9677,46 @@ void ImGui::ShowMetricsWindow(bool* opened) return; NodeDrawList(window->DrawList, "DrawList"); if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow"); - if (window->DC.ChildWindows.size() > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows"); + if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows"); + ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair)); ImGui::TreePop(); } }; - ImGuiState& g = *GImGui; // Access private state - g.DisableHideTextAfterDoubleHash++; // Not exposed (yet). Disable processing that hides text after '##' markers. + ImGuiContext& g = *GImGui; // Access private state Funcs::NodeWindows(g.Windows, "Windows"); - if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", (int)g.RenderDrawLists[0].size())) + if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.RenderDrawLists[0].Size)) { - for (int i = 0; i < (int)g.RenderDrawLists[0].size(); i++) + for (int i = 0; i < g.RenderDrawLists[0].Size; i++) Funcs::NodeDrawList(g.RenderDrawLists[0][i], "DrawList"); ImGui::TreePop(); } - g.DisableHideTextAfterDoubleHash--; - } - ImGui::End(); -} - -static void ShowExampleAppAutoResize(bool* opened) -{ - if (!ImGui::Begin("Example: Auto-Resizing Window", opened, ImGuiWindowFlags_AlwaysAutoResize)) - { - ImGui::End(); - return; - } - - static int lines = 10; - ImGui::Text("Window will resize every-frame to the size of its content.\nNote that you probably don't want to query the window size to\noutput your content because that would create a feedback loop."); - ImGui::SliderInt("Number of lines", &lines, 1, 20); - for (int i = 0; i < lines; i++) - ImGui::Text("%*sThis is line %d", i*4, "", i); // Pad with space to extend size horizontally - - ImGui::End(); -} - -static void ShowExampleAppFixedOverlay(bool* opened) -{ - ImGui::SetNextWindowPos(ImVec2(10,10)); - if (!ImGui::Begin("Example: Fixed Overlay", opened, ImVec2(0,0), 0.3f, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings)) - { - ImGui::End(); - return; - } - - ImGui::Text("Simple overlay\non the top-left side of the screen."); - ImGui::Separator(); - ImGui::Text("Mouse Position: (%.1f,%.1f)", ImGui::GetIO().MousePos.x, ImGui::GetIO().MousePos.y); - - ImGui::End(); -} - -static void ShowExampleAppManipulatingWindowTitle(bool* opened) -{ - (void)opened; - - // By default, Windows are uniquely identified by their title. - // You can use the "##" and "###" markers to manipulate the display/ID. Read FAQ at the top of this file! - - // Using "##" to display same title but have unique identifier. - ImGui::SetNextWindowPos(ImVec2(100,100), ImGuiSetCond_FirstUseEver); - ImGui::Begin("Same title as another window##1"); - ImGui::Text("This is window 1.\nMy title is the same as window 2, but my identifier is unique."); - ImGui::End(); - - ImGui::SetNextWindowPos(ImVec2(100,200), ImGuiSetCond_FirstUseEver); - ImGui::Begin("Same title as another window##2"); - ImGui::Text("This is window 2.\nMy title is the same as window 1, but my identifier is unique."); - ImGui::End(); - - // Using "###" to display a changing title but keep a static identifier "AnimatedTitle" - char buf[128]; - ImFormatString(buf, IM_ARRAYSIZE(buf), "Animated title %c %d###AnimatedTitle", "|/-\\"[(int)(ImGui::GetTime()/0.25f)&3], rand()); - ImGui::SetNextWindowPos(ImVec2(100,300), ImGuiSetCond_FirstUseEver); - ImGui::Begin(buf); - ImGui::Text("This window has a changing title."); - ImGui::End(); -} - -static void ShowExampleAppCustomRendering(bool* opened) -{ - ImGui::SetNextWindowSize(ImVec2(300,350), ImGuiSetCond_FirstUseEver); - if (!ImGui::Begin("Example: Custom Rendering", opened)) - { - ImGui::End(); - return; - } - - // Tip: If you do a lot of custom rendering, you probably want to use your own geometrical types and benefit of overloaded operators, etc. - // Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your types and ImVec2/ImVec4. - // ImGui defines overloaded operators but they are internal to imgui.cpp and not exposed outside (to avoid messing with your types) - // In this example we aren't using the operators. - - static ImVector points; - static bool adding_line = false; - if (ImGui::Button("Clear")) points.clear(); - if (points.size() >= 2) { ImGui::SameLine(); if (ImGui::Button("Undo")) { points.pop_back(); points.pop_back(); } } - ImGui::Text("Left-click and drag to add lines"); - ImGui::Text("Right-click to undo"); - - ImDrawList* draw_list = ImGui::GetWindowDrawList(); - - // Here we are using InvisibleButton() as a convenience to 1) advance the cursor and 2) allows us to use IsItemHovered() - // However you can draw directly and poll mouse/keyboard by yourself. You can manipulate the cursor using GetCursorPos() and SetCursorPos(). - // If you only use the ImDrawList API, you can notify the owner window of its extends by using SetCursorPos(max). - ImVec2 canvas_pos = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates! - ImVec2 canvas_size = ImVec2(ImMax(50.0f,ImGui::GetWindowContentRegionMax().x-ImGui::GetCursorPos().x), ImMax(50.0f,ImGui::GetWindowContentRegionMax().y-ImGui::GetCursorPos().y)); // Resize canvas what's available - draw_list->AddRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), 0xFFFFFFFF); - bool adding_preview = false; - ImGui::InvisibleButton("canvas", canvas_size); - if (ImGui::IsItemHovered()) - { - ImVec2 mouse_pos_in_canvas = ImVec2(ImGui::GetIO().MousePos.x - canvas_pos.x, ImGui::GetIO().MousePos.y - canvas_pos.y); - if (!adding_line && ImGui::GetIO().MouseClicked[0]) + if (ImGui::TreeNode("Popups", "Open Popups Stack (%d)", g.OpenPopupStack.Size)) { - points.push_back(mouse_pos_in_canvas); - adding_line = true; - } - if (adding_line) - { - adding_preview = true; - points.push_back(mouse_pos_in_canvas); - if (!ImGui::GetIO().MouseDown[0]) - adding_line = adding_preview = false; - } - if (ImGui::GetIO().MouseClicked[1] && !points.empty()) - { - adding_line = false; - points.pop_back(); - points.pop_back(); - } - } - draw_list->PushClipRect(ImVec4(canvas_pos.x, canvas_pos.y, canvas_pos.x+canvas_size.x, canvas_pos.y+canvas_size.y)); // clip lines within the canvas (if we resize it, etc.) - for (int i = 0; i < (int)points.size() - 1; i += 2) - draw_list->AddLine(ImVec2(canvas_pos.x + points[i].x, canvas_pos.y + points[i].y), ImVec2(canvas_pos.x + points[i+1].x, canvas_pos.y + points[i+1].y), 0xFF00FFFF); - draw_list->PopClipRect(); - if (adding_preview) - points.pop_back(); - ImGui::End(); -} - -struct ExampleAppConsole -{ - char InputBuf[256]; - ImVector Items; - bool ScrollToBottom; - ImVector History; - int HistoryPos; // -1: new line, 0..History.size()-1 browsing history. - ImVector Commands; - - ExampleAppConsole() - { - ClearLog(); - HistoryPos = -1; - Commands.push_back("HELP"); - Commands.push_back("HISTORY"); - Commands.push_back("CLEAR"); - Commands.push_back("CLASSIFY"); // "classify" is here to provide an example of "C"+[tab] completing to "CL" and displaying matches. - } - ~ExampleAppConsole() - { - ClearLog(); - for (size_t i = 0; i < Items.size(); i++) - ImGui::MemFree(History[i]); - } - - void ClearLog() - { - for (size_t i = 0; i < Items.size(); i++) - ImGui::MemFree(Items[i]); - Items.clear(); - ScrollToBottom = true; - } - - void AddLog(const char* fmt, ...) - { - char buf[1024]; - va_list args; - va_start(args, fmt); - ImFormatStringV(buf, IM_ARRAYSIZE(buf), fmt, args); - va_end(args); - Items.push_back(ImStrdup(buf)); - ScrollToBottom = true; - } - - void Run(const char* title, bool* opened) - { - ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiSetCond_FirstUseEver); - if (!ImGui::Begin(title, opened)) - { - ImGui::End(); - return; - } - - ImGui::TextWrapped("This example implements a console with basic coloring, completion and history. A more elaborate implementation may want to store entries along with extra data such as timestamp, emitter, etc."); - ImGui::TextWrapped("Enter 'HELP' for help, press TAB to use text completion."); - - // TODO: display from bottom - // TODO: clip manually - - if (ImGui::SmallButton("Add Dummy Text")) { AddLog("%d some text", Items.size()); AddLog("some more text"); AddLog("display very important message here!"); } ImGui::SameLine(); - if (ImGui::SmallButton("Add Dummy Error")) AddLog("[error] something went wrong"); ImGui::SameLine(); - if (ImGui::SmallButton("Clear")) ClearLog(); - //static float t = 0.0f; if (ImGui::GetTime() - t > 0.02f) { t = ImGui::GetTime(); AddLog("Spam %f", t); } - - ImGui::Separator(); - - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0)); - static ImGuiTextFilter filter; - filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180); - //if (ImGui::IsItemHovered()) ImGui::SetKeyboardFocusHere(-1); // Auto focus on hover - ImGui::PopStyleVar(); - ImGui::Separator(); - - // Display every line as a separate entry so we can change their color or add custom widgets. If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end()); - // NB- if you have thousands of entries this approach may be too inefficient. You can seek and display only the lines that are visible - CalcListClipping() is a helper to compute this information. - // If your items are of variable size you may want to implement code similar to what CalcListClipping() does. Or split your data into fixed height items to allow random-seeking into your list. - ImGui::BeginChild("ScrollingRegion", ImVec2(0,-ImGui::GetTextLineHeightWithSpacing()*2)); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4,1)); // Tighten spacing - for (size_t i = 0; i < Items.size(); i++) - { - const char* item = Items[i]; - if (!filter.PassFilter(item)) - continue; - ImVec4 col(1,1,1,1); // A better implement may store a type per-item. For the sample let's just parse the text. - if (strstr(item, "[error]")) col = ImVec4(1.0f,0.4f,0.4f,1.0f); - else if (strncmp(item, "# ", 2) == 0) col = ImVec4(1.0f,0.8f,0.6f,1.0f); - ImGui::PushStyleColor(ImGuiCol_Text, col); - ImGui::TextUnformatted(item); - ImGui::PopStyleColor(); - } - if (ScrollToBottom) - ImGui::SetScrollPosHere(); - ScrollToBottom = false; - ImGui::PopStyleVar(); - ImGui::EndChild(); - ImGui::Separator(); - - // Command-line - if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), ImGuiInputTextFlags_EnterReturnsTrue|ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_CallbackHistory, &TextEditCallbackStub, (void*)this)) - { - char* input_end = InputBuf+strlen(InputBuf); - while (input_end > InputBuf && input_end[-1] == ' ') input_end--; *input_end = 0; - if (InputBuf[0]) - ExecCommand(InputBuf); - strcpy(InputBuf, ""); - } - - // Demonstrate keeping auto focus on the input box - if (ImGui::IsItemHovered() || (ImGui::IsRootWindowOrAnyChildFocused() && !ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0))) - ImGui::SetKeyboardFocusHere(-1); // Auto focus - - ImGui::End(); - } - - void ExecCommand(const char* command_line) - { - AddLog("# %s\n", command_line); - - // Insert into history. First find match and delete it so it can be pushed to the back. This isn't trying to be smart or optimal. - HistoryPos = -1; - for (int i = (int)History.size()-1; i >= 0; i--) - if (ImStricmp(History[i], command_line) == 0) + for (int i = 0; i < g.OpenPopupStack.Size; i++) { - ImGui::MemFree(History[i]); - History.erase(History.begin() + i); - break; + ImGuiWindow* window = g.OpenPopupStack[i].Window; + ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupID, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : ""); } - History.push_back(ImStrdup(command_line)); - - // Process command - if (ImStricmp(command_line, "CLEAR") == 0) - { - ClearLog(); + ImGui::TreePop(); } - else if (ImStricmp(command_line, "HELP") == 0) + if (ImGui::TreeNode("Basic state")) { - AddLog("Commands:"); - for (size_t i = 0; i < Commands.size(); i++) - AddLog("- %s", Commands[i]); - } - else if (ImStricmp(command_line, "HISTORY") == 0) - { - for (size_t i = History.size() >= 10 ? History.size() - 10 : 0; i < History.size(); i++) - AddLog("%3d: %s\n", i, History[i]); - } - else - { - AddLog("Unknown command: '%s'\n", command_line); + ImGui::Text("FocusedWindow: '%s'", g.FocusedWindow ? g.FocusedWindow->Name : "NULL"); + ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); + ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL"); + ImGui::Text("HoveredID: 0x%08X/0x%08X", g.HoveredId, g.HoveredIdPreviousFrame); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not + ImGui::Text("ActiveID: 0x%08X/0x%08X", g.ActiveId, g.ActiveIdPreviousFrame); + ImGui::TreePop(); } } - - static int TextEditCallbackStub(ImGuiTextEditCallbackData* data) - { - ExampleAppConsole* console = (ExampleAppConsole*)data->UserData; - return console->TextEditCallback(data); - } - - int TextEditCallback(ImGuiTextEditCallbackData* data) - { - //AddLog("cursor: %d, selection: %d-%d", data->CursorPos, data->SelectionStart, data->SelectionEnd); - switch (data->EventFlag) - { - case ImGuiInputTextFlags_CallbackCompletion: - { - // Example of TEXT COMPLETION - - // Locate beginning of current word - const char* word_end = data->Buf + data->CursorPos; - const char* word_start = word_end; - while (word_start > data->Buf) - { - const char c = word_start[-1]; - if (ImCharIsSpace(c) || c == ',' || c == ';') - break; - word_start--; - } - - // Build a list of candidates - ImVector candidates; - for (size_t i = 0; i < Commands.size(); i++) - if (ImStrnicmp(Commands[i], word_start, (int)(word_end-word_start)) == 0) - candidates.push_back(Commands[i]); - - if (candidates.size() == 0) - { - // No match - AddLog("No match for \"%.*s\"!\n", word_end-word_start, word_start); - } - else if (candidates.size() == 1) - { - // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing - data->DeleteChars((int)(word_start-data->Buf), (int)(word_end-word_start)); - data->InsertChars(data->CursorPos, candidates[0]); - data->InsertChars(data->CursorPos, " "); - } - else - { - // Multiple matches. Complete as much as we can, so inputing "C" will complete to "CL" and display "CLEAR" and "CLASSIFY" - int match_len = (int)(word_end - word_start); - for (;;) - { - int c = 0; - bool all_candidates_matches = true; - for (size_t i = 0; i < candidates.size() && all_candidates_matches; i++) - if (i == 0) - c = toupper(candidates[i][match_len]); - else if (c != toupper(candidates[i][match_len])) - all_candidates_matches = false; - if (!all_candidates_matches) - break; - match_len++; - } - - if (match_len > 0) - { - data->DeleteChars((int)(word_start - data->Buf), (int)(word_end-word_start)); - data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len); - } - - // List matches - AddLog("Possible matches:\n"); - for (size_t i = 0; i < candidates.size(); i++) - AddLog("- %s\n", candidates[i]); - } - - break; - } - case ImGuiInputTextFlags_CallbackHistory: - { - // Example of HISTORY - const int prev_history_pos = HistoryPos; - if (data->EventKey == ImGuiKey_UpArrow) - { - if (HistoryPos == -1) - HistoryPos = (int)(History.size() - 1); - else if (HistoryPos > 0) - HistoryPos--; - } - else if (data->EventKey == ImGuiKey_DownArrow) - { - if (HistoryPos != -1) - if (++HistoryPos >= (int)History.size()) - HistoryPos = -1; - } - - // A better implementation would preserve the data on the current input line along with cursor position. - if (prev_history_pos != HistoryPos) - { - ImFormatString(data->Buf, data->BufSize, "%s", (HistoryPos >= 0) ? History[HistoryPos] : ""); - data->BufDirty = true; - data->CursorPos = data->SelectionStart = data->SelectionEnd = (int)strlen(data->Buf); - } - } - } - return 0; - } -}; - -static void ShowExampleAppConsole(bool* opened) -{ - static ExampleAppConsole console; - console.Run("Example: Console", opened); -} - -static void ShowExampleAppLongText(bool* opened) -{ - ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiSetCond_FirstUseEver); - if (!ImGui::Begin("Example: Long text display", opened)) - { - ImGui::End(); - return; - } - - static int test_type = 0; - static ImGuiTextBuffer log; - static int lines = 0; - ImGui::Text("Printing unusually long amount of text."); - ImGui::Combo("Test type", &test_type, "Single call to TextUnformatted()\0Multiple calls to Text(), clipped manually\0Multiple calls to Text(), not clipped"); - ImGui::Text("Buffer contents: %d lines, %d bytes", lines, log.size()); - if (ImGui::Button("Clear")) { log.clear(); lines = 0; } - ImGui::SameLine(); - if (ImGui::Button("Add 1000 lines")) - { - for (int i = 0; i < 1000; i++) - log.append("%i The quick brown fox jumps over the lazy dog\n", lines+i); - lines += 1000; - } - ImGui::BeginChild("Log"); - switch (test_type) - { - case 0: - // Single call to TextUnformatted() with a big buffer - ImGui::TextUnformatted(log.begin(), log.end()); - break; - case 1: - // Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the CalcListClipping() helper. - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); - int display_start, display_end; - ImGui::CalcListClipping(lines, ImGui::GetTextLineHeight(), &display_start, &display_end); - ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (display_start) * ImGui::GetTextLineHeight()); - for (int i = display_start; i < display_end; i++) - ImGui::Text("%i The quick brown fox jumps over the lazy dog\n", i); - ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (lines - display_end) * ImGui::GetTextLineHeight()); - ImGui::PopStyleVar(); - break; - case 2: - // Multiple calls to Text(), not clipped - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); - for (int i = 0; i < lines; i++) - ImGui::Text("%i The quick brown fox jumps over the lazy dog\n", i); - ImGui::PopStyleVar(); - break; - } - ImGui::EndChild(); ImGui::End(); } -// End of Sample code -#endif - -//----------------------------------------------------------------------------- -// FONT DATA -//----------------------------------------------------------------------------- -// Compressed with stb_compress() then converted to a C array. -// Use the program in extra_fonts/binary_to_compressed_c.cpp to create the array from a TTF file. -// Decompressor from stb.h (public domain) by Sean Barrett https://github.com/nothings/stb/blob/master/stb.h //----------------------------------------------------------------------------- -static unsigned int stb_decompress_length(unsigned char *input) -{ - return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11]; -} - -static unsigned char *stb__barrier, *stb__barrier2, *stb__barrier3, *stb__barrier4; -static unsigned char *stb__dout; -static void stb__match(unsigned char *data, unsigned int length) -{ - // INVERSE of memmove... write each byte before copying the next... - IM_ASSERT (stb__dout + length <= stb__barrier); - if (stb__dout + length > stb__barrier) { stb__dout += length; return; } - if (data < stb__barrier4) { stb__dout = stb__barrier+1; return; } - while (length--) *stb__dout++ = *data++; -} - -static void stb__lit(unsigned char *data, unsigned int length) -{ - IM_ASSERT (stb__dout + length <= stb__barrier); - if (stb__dout + length > stb__barrier) { stb__dout += length; return; } - if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; } - memcpy(stb__dout, data, length); - stb__dout += length; -} - -#define stb__in2(x) ((i[x] << 8) + i[(x)+1]) -#define stb__in3(x) ((i[x] << 16) + stb__in2((x)+1)) -#define stb__in4(x) ((i[x] << 24) + stb__in3((x)+1)) - -static unsigned char *stb_decompress_token(unsigned char *i) -{ - if (*i >= 0x20) { // use fewer if's for cases that expand small - if (*i >= 0x80) stb__match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2; - else if (*i >= 0x40) stb__match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3; - else /* *i >= 0x20 */ stb__lit(i+1, i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1); - } else { // more ifs for cases that expand large, since overhead is amortized - if (*i >= 0x18) stb__match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4; - else if (*i >= 0x10) stb__match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5; - else if (*i >= 0x08) stb__lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2 + (stb__in2(0) - 0x0800 + 1); - else if (*i == 0x07) stb__lit(i+3, stb__in2(1) + 1), i += 3 + (stb__in2(1) + 1); - else if (*i == 0x06) stb__match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5; - else if (*i == 0x04) stb__match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6; - } - return i; -} - -static unsigned int stb_adler32(unsigned int adler32, unsigned char *buffer, unsigned int buflen) -{ - const unsigned long ADLER_MOD = 65521; - unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16; - unsigned long blocklen, i; - - blocklen = buflen % 5552; - while (buflen) { - for (i=0; i + 7 < blocklen; i += 8) { - s1 += buffer[0], s2 += s1; - s1 += buffer[1], s2 += s1; - s1 += buffer[2], s2 += s1; - s1 += buffer[3], s2 += s1; - s1 += buffer[4], s2 += s1; - s1 += buffer[5], s2 += s1; - s1 += buffer[6], s2 += s1; - s1 += buffer[7], s2 += s1; - - buffer += 8; - } - - for (; i < blocklen; ++i) - s1 += *buffer++, s2 += s1; - - s1 %= ADLER_MOD, s2 %= ADLER_MOD; - buflen -= blocklen; - blocklen = 5552; - } - return (unsigned int)(s2 << 16) + (unsigned int)s1; -} - -static unsigned int stb_decompress(unsigned char *output, unsigned char *i, unsigned int length) -{ - unsigned int olen; - if (stb__in4(0) != 0x57bC0000) return 0; - if (stb__in4(4) != 0) return 0; // error! stream is > 4GB - olen = stb_decompress_length(i); - stb__barrier2 = i; - stb__barrier3 = i+length; - stb__barrier = output + olen; - stb__barrier4 = output; - i += 16; - - stb__dout = output; - for (;;) { - unsigned char *old_i = i; - i = stb_decompress_token(i); - if (i == old_i) { - if (*i == 0x05 && i[1] == 0xfa) { - IM_ASSERT(stb__dout == output + olen); - if (stb__dout != output + olen) return 0; - if (stb_adler32(1, output, olen) != (unsigned int) stb__in4(2)) - return 0; - return olen; - } else { - IM_ASSERT(0); /* NOTREACHED */ - return 0; - } - } - IM_ASSERT(stb__dout <= output + olen); - if (stb__dout > output + olen) - return 0; - } -} - -//----------------------------------------------------------------------------- -// ProggyClean.ttf -// Copyright (c) 2004, 2005 Tristan Grimmer -// MIT license (see License.txt in http://www.upperbounds.net/download/ProggyClean.ttf.zip) -// Download and more information at http://upperbounds.net -//----------------------------------------------------------------------------- -static const unsigned int proggy_clean_ttf_compressed_size = 9583; -static const unsigned int proggy_clean_ttf_compressed_data[9584/4] = -{ - 0x0000bc57, 0x00000000, 0xf8a00000, 0x00000400, 0x00010037, 0x000c0000, 0x00030080, 0x2f534f40, 0x74eb8832, 0x01000090, 0x2c158248, 0x616d634e, - 0x23120270, 0x03000075, 0x241382a0, 0x74766352, 0x82178220, 0xfc042102, 0x02380482, 0x66796c67, 0x5689af12, 0x04070000, 0x80920000, 0x64616568, - 0xd36691d7, 0xcc201b82, 0x36210382, 0x27108268, 0xc3014208, 0x04010000, 0x243b0f82, 0x78746d68, 0x807e008a, 0x98010000, 0x06020000, 0x61636f6c, - 0xd8b0738c, 0x82050000, 0x0402291e, 0x7078616d, 0xda00ae01, 0x28201f82, 0x202c1082, 0x656d616e, 0x96bb5925, 0x84990000, 0x9e2c1382, 0x74736f70, - 0xef83aca6, 0x249b0000, 0xd22c3382, 0x70657270, 0x12010269, 0xf4040000, 0x08202f82, 0x012ecb84, 0x553c0000, 0x0f5fd5e9, 0x0300f53c, 0x00830008, - 0x7767b722, 0x002b3f82, 0xa692bd00, 0xfe0000d7, 0x83800380, 0x21f1826f, 0x00850002, 0x41820120, 0x40fec026, 0x80030000, 0x05821083, 0x07830120, - 0x0221038a, 0x24118200, 0x90000101, 0x82798200, 0x00022617, 0x00400008, 0x2009820a, 0x82098276, 0x82002006, 0x9001213b, 0x0223c883, 0x828a02bc, - 0x858f2010, 0xc5012507, 0x00023200, 0x04210083, 0x91058309, 0x6c412b03, 0x40007374, 0xac200000, 0x00830008, 0x01000523, 0x834d8380, 0x80032103, - 0x012101bf, 0x23b88280, 0x00800000, 0x0b830382, 0x07820120, 0x83800021, 0x88012001, 0x84002009, 0x2005870f, 0x870d8301, 0x2023901b, 0x83199501, - 0x82002015, 0x84802000, 0x84238267, 0x88002027, 0x8561882d, 0x21058211, 0x13880000, 0x01800022, 0x05850d85, 0x0f828020, 0x03208384, 0x03200582, - 0x47901b84, 0x1b850020, 0x1f821d82, 0x3f831d88, 0x3f410383, 0x84058405, 0x210982cd, 0x09830000, 0x03207789, 0xf38a1384, 0x01203782, 0x13872384, - 0x0b88c983, 0x0d898f84, 0x00202982, 0x23900383, 0x87008021, 0x83df8301, 0x86118d03, 0x863f880d, 0x8f35880f, 0x2160820f, 0x04830300, 0x1c220382, - 0x05820100, 0x4c000022, 0x09831182, 0x04001c24, 0x11823000, 0x0800082e, 0x00000200, 0xff007f00, 0xffffac20, 0x00220982, 0x09848100, 0xdf216682, - 0x843586d5, 0x06012116, 0x04400684, 0xa58120d7, 0x00b127d8, 0x01b88d01, 0x2d8685ff, 0xc100c621, 0xf4be0801, 0x9e011c01, 0x88021402, 0x1403fc02, - 0x9c035803, 0x1404de03, 0x50043204, 0xa2046204, 0x66051605, 0x1206bc05, 0xd6067406, 0x7e073807, 0x4e08ec07, 0x96086c08, 0x1009d008, 0x88094a09, - 0x800a160a, 0x560b040b, 0x2e0cc80b, 0xea0c820c, 0xa40d5e0d, 0x500eea0d, 0x280f960e, 0x1210b00f, 0xe0107410, 0xb6115211, 0x6e120412, 0x4c13c412, - 0xf613ac13, 0xae145814, 0x4015ea14, 0xa6158015, 0x1216b815, 0xc6167e16, 0x8e173417, 0x5618e017, 0xee18ba18, 0x96193619, 0x481ad419, 0xf01a9c1a, - 0xc81b5c1b, 0x4c1c041c, 0xea1c961c, 0x921d2a1d, 0x401ed21d, 0xe01e8e1e, 0x761f241f, 0xa61fa61f, 0x01821020, 0x8a202e34, 0xc820b220, 0x74211421, - 0xee219821, 0x86226222, 0x01820c23, 0x83238021, 0x23983c01, 0x24d823b0, 0x244a2400, 0x24902468, 0x250625ae, 0x25822560, 0x26f825f8, 0x82aa2658, - 0xd8be0801, 0x9a274027, 0x68280a28, 0x0e29a828, 0xb8292029, 0x362af829, 0x602a602a, 0x2a2b022b, 0xac2b5e2b, 0x202ce62b, 0x9a2c342c, 0x5c2d282d, - 0xaa2d782d, 0x262ee82d, 0x262fa62e, 0xf42fb62f, 0xc8305e30, 0xb4313e31, 0x9e321e32, 0x82331e33, 0x5c34ee33, 0x3a35ce34, 0xd4358635, 0x72362636, - 0x7637e636, 0x3a38d837, 0x1239a638, 0xae397439, 0x9a3a2e3a, 0x7c3b063b, 0x3a3ce83b, 0x223d963c, 0xec3d863d, 0xc63e563e, 0x9a3f2a3f, 0x6a401240, - 0x3641d040, 0x0842a241, 0x7a424042, 0xf042b842, 0xcc436243, 0x8a442a44, 0x5845ee44, 0xe245b645, 0xb4465446, 0x7a471447, 0x5448da47, 0x4049c648, - 0x15462400, 0x034d0808, 0x0b000700, 0x13000f00, 0x1b001700, 0x23001f00, 0x2b002700, 0x33002f00, 0x3b003700, 0x43003f00, 0x4b004700, 0x53004f00, - 0x5b005700, 0x63005f00, 0x6b006700, 0x73006f00, 0x7b007700, 0x83007f00, 0x8b008700, 0x00008f00, 0x15333511, 0x20039631, 0x20178205, 0xd3038221, - 0x20739707, 0x25008580, 0x028080fc, 0x05be8080, 0x04204a85, 0x05ce0685, 0x0107002a, 0x02000080, 0x00000400, 0x250d8b41, 0x33350100, 0x03920715, - 0x13820320, 0x858d0120, 0x0e8d0320, 0xff260d83, 0x00808000, 0x54820106, 0x04800223, 0x845b8c80, 0x41332059, 0x078b068f, 0x82000121, 0x82fe2039, - 0x84802003, 0x83042004, 0x23598a0e, 0x00180000, 0x03210082, 0x42ab9080, 0x73942137, 0x2013bb41, 0x8f978205, 0x2027a39b, 0x20b68801, 0x84b286fd, - 0x91c88407, 0x41032011, 0x11a51130, 0x15000027, 0x80ff8000, 0x11af4103, 0x841b0341, 0x8bd983fd, 0x9be99bc9, 0x8343831b, 0x21f1821f, 0xb58300ff, - 0x0f84e889, 0xf78a0484, 0x8000ff22, 0x0020eeb3, 0x14200082, 0x2130ef41, 0xeb431300, 0x4133200a, 0xd7410ecb, 0x9a07200b, 0x2027871b, 0x21238221, - 0xe7828080, 0xe784fd20, 0xe8848020, 0xfe808022, 0x08880d85, 0xba41fd20, 0x82248205, 0x85eab02a, 0x008022e7, 0x2cd74200, 0x44010021, 0xd34406eb, - 0x44312013, 0xcf8b0eef, 0x0d422f8b, 0x82332007, 0x0001212f, 0x8023cf82, 0x83000180, 0x820583de, 0x830682d4, 0x820020d4, 0x82dc850a, 0x20e282e9, - 0xb2ff85fe, 0x010327e9, 0x02000380, 0x0f440400, 0x0c634407, 0x68825982, 0x85048021, 0x260a825d, 0x010b0000, 0x4400ff00, 0x2746103f, 0x08d74209, - 0x4d440720, 0x0eaf4406, 0xc3441d20, 0x23078406, 0xff800002, 0x04845b83, 0x8d05b241, 0x1781436f, 0x6b8c87a5, 0x1521878e, 0x06474505, 0x01210783, - 0x84688c00, 0x8904828e, 0x441e8cf7, 0x0b270cff, 0x80008000, 0x45030003, 0xfb430fab, 0x080f4107, 0x410bf942, 0xd34307e5, 0x070d4207, 0x80800123, - 0x205d85fe, 0x849183fe, 0x20128404, 0x82809702, 0x00002217, 0x41839a09, 0x6b4408cf, 0x0733440f, 0x3b460720, 0x82798707, 0x97802052, 0x0000296f, - 0xff800004, 0x01800100, 0x0021ef89, 0x0a914625, 0x410a4d41, 0x00250ed4, 0x00050000, 0x056d4280, 0x210a7b46, 0x21481300, 0x46ed8512, 0x00210bd1, - 0x89718202, 0x21738877, 0x2b850001, 0x00220582, 0x87450a00, 0x0ddb4606, 0x41079b42, 0x9d420c09, 0x0b09420b, 0x8d820720, 0x9742fc84, 0x42098909, - 0x00241e0f, 0x00800014, 0x0b47da82, 0x0833442a, 0x49078d41, 0x2f450f13, 0x42278f17, 0x01200751, 0x22063742, 0x44808001, 0x20450519, 0x88068906, - 0x83fe2019, 0x4203202a, 0x1a941a58, 0x00820020, 0xe7a40e20, 0x420ce146, 0x854307e9, 0x0fcb4713, 0xff20a182, 0xfe209b82, 0x0c867f8b, 0x0021aea4, - 0x219fa40f, 0x7d41003b, 0x07194214, 0xbf440520, 0x071d4206, 0x6941a590, 0x80802309, 0x028900ff, 0xa9a4b685, 0xc5808021, 0x449b82ab, 0x152007eb, - 0x42134d46, 0x61440a15, 0x051e4208, 0x222b0442, 0x47001100, 0xfd412913, 0x17194714, 0x410f5b41, 0x02220773, 0x09428080, 0x21a98208, 0xd4420001, - 0x481c840d, 0x00232bc9, 0x42120000, 0xe74c261b, 0x149d4405, 0x07209d87, 0x410db944, 0x14421c81, 0x42fd2005, 0x80410bd2, 0x203d8531, 0x06874100, - 0x48256f4a, 0xcb420c95, 0x13934113, 0x44075d44, 0x044c0855, 0x00ff2105, 0xfe228185, 0x45448000, 0x22c5b508, 0x410c0000, 0x7b412087, 0x1bb74514, - 0x32429c85, 0x0a574805, 0x21208943, 0x8ba01300, 0x440dfb4e, 0x77431437, 0x245b4113, 0x200fb145, 0x41108ffe, 0x80203562, 0x00200082, 0x46362b42, - 0x1742178d, 0x4527830f, 0x0f830b2f, 0x4a138146, 0x802409a1, 0xfe8000ff, 0x94419982, 0x09294320, 0x04000022, 0x49050f4f, 0xcb470a63, 0x48032008, - 0x2b48067b, 0x85022008, 0x82638338, 0x00002209, 0x05af4806, 0x900e9f49, 0x84c5873f, 0x214285bd, 0x064900ff, 0x0c894607, 0x00000023, 0x4903820a, - 0x714319f3, 0x0749410c, 0x8a07a145, 0x02152507, 0xfe808000, 0x74490386, 0x8080211b, 0x0c276f82, 0x00018000, 0x48028003, 0x2b2315db, 0x43002f00, - 0x6f82142f, 0x44011521, 0x93510da7, 0x20e68508, 0x06494d80, 0x8e838020, 0x06821286, 0x124bff20, 0x25f3830c, 0x03800080, 0xe74a0380, 0x207b8715, - 0x876b861d, 0x4a152007, 0x07870775, 0xf6876086, 0x8417674a, 0x0a0021f2, 0x431c9743, 0x8d421485, 0x200b830b, 0x06474d03, 0x71828020, 0x04510120, - 0x42da8606, 0x1f831882, 0x001a0022, 0xff4d0082, 0x0b0f532c, 0x0d449b94, 0x4e312007, 0x074f12e7, 0x0bf3490b, 0xbb412120, 0x413f820a, 0xef490857, - 0x80002313, 0xe2830001, 0x6441fc20, 0x8b802006, 0x00012108, 0xfd201582, 0x492c9b48, 0x802014ff, 0x51084347, 0x0f4327f3, 0x17bf4a14, 0x201b7944, - 0x06964201, 0x134ffe20, 0x20d6830b, 0x25d78280, 0xfd800002, 0x05888000, 0x9318dc41, 0x21d282d4, 0xdb481800, 0x0dff542a, 0x45107743, 0xe14813f5, - 0x0f034113, 0x83135d45, 0x47b28437, 0xe4510e73, 0x21f58e06, 0x2b8400fd, 0x1041fcac, 0x08db4b0b, 0x421fdb41, 0xdf4b18df, 0x011d210a, 0x420af350, - 0x6e8308af, 0xac85cb86, 0x1e461082, 0x82b7a407, 0x411420a3, 0xa34130ab, 0x178f4124, 0x41139741, 0x86410d93, 0x82118511, 0x057243d8, 0x8941d9a4, - 0x3093480c, 0x4a13474f, 0xfb5016a9, 0x07ad4108, 0x4a0f9d42, 0xfe200fad, 0x4708aa41, 0x83482dba, 0x288f4d06, 0xb398c3bb, 0x44267b41, 0xb34439d7, - 0x0755410f, 0x200ebb45, 0x0f5f4215, 0x20191343, 0x06df5301, 0xf04c0220, 0x2ba64d07, 0x82050841, 0x430020ce, 0xa78f3627, 0x5213ff42, 0x2f970bc1, - 0x4305ab55, 0xa084111b, 0x450bac45, 0x5f4238b8, 0x010c2106, 0x0220ed82, 0x441bb344, 0x875010af, 0x0737480f, 0x490c5747, 0x0c840c03, 0x4c204b42, - 0x8ba905d7, 0x8b948793, 0x510c0c51, 0xfb4b24b9, 0x1b174107, 0x5709d74c, 0xd1410ca5, 0x079d480f, 0x201ff541, 0x06804780, 0x7d520120, 0x80002205, - 0x20a983fe, 0x47bb83fe, 0x1b8409b4, 0x81580220, 0x4e00202c, 0x4f41282f, 0x0eab4f17, 0x57471520, 0x0e0f4808, 0x8221e041, 0x3e1b4a8b, 0x4407175d, - 0x1b4b071f, 0x4a0f8b07, 0x174a0703, 0x0ba5411b, 0x430fb141, 0x0120057b, 0xfc20dd82, 0x4a056047, 0xf4850c0c, 0x01221982, 0x02828000, 0x1a5d088b, - 0x20094108, 0x8c0e3941, 0x4900200e, 0x7744434f, 0x200b870b, 0x0e4b5a33, 0x2b41f78b, 0x8b138307, 0x0b9f450b, 0x2406f741, 0xfd808001, 0x09475a00, - 0x84000121, 0x5980200e, 0x85450e5d, 0x832c8206, 0x4106831e, 0x00213814, 0x28b34810, 0x410c2f4b, 0x5f4a13d7, 0x0b2b4113, 0x6e43a883, 0x11174b05, - 0x4b066a45, 0xcc470541, 0x5000202b, 0xcb472f4b, 0x44b59f0f, 0xc5430b5b, 0x0d654907, 0x21065544, 0xd6828080, 0xfe201982, 0x8230ec4a, 0x120025c2, - 0x80ff8000, 0x4128d74d, 0x3320408b, 0x410a9f50, 0xdb822793, 0x822bd454, 0x61134b2e, 0x410b214a, 0xad4117c9, 0x0001211f, 0x4206854f, 0x4b430596, - 0x06bb5530, 0x2025cf46, 0x0ddd5747, 0x500ea349, 0x0f840fa7, 0x5213c153, 0x634e08d1, 0x0bbe4809, 0x59316e4d, 0x5b50053f, 0x203f6323, 0x5117eb46, - 0x94450a63, 0x246e410a, 0x63410020, 0x0bdb5f2f, 0x4233ab44, 0x39480757, 0x112d4a07, 0x7241118f, 0x000e2132, 0x9f286f41, 0x0f8762c3, 0x33350723, - 0x094e6415, 0x2010925f, 0x067252fe, 0xd0438020, 0x63a68225, 0x11203a4f, 0x480e6360, 0x5748131f, 0x079b521f, 0x200e2f43, 0x864b8315, 0x113348e7, - 0x85084e48, 0x06855008, 0x5880fd21, 0x7c420925, 0x0c414824, 0x37470c86, 0x1b8b422b, 0x5b0a8755, 0x23410c21, 0x0b83420b, 0x5a082047, 0xf482067f, - 0xa80b4c47, 0x0c0021cf, 0x20207b42, 0x0fb74100, 0x420b8744, 0xeb43076f, 0x0f6f420b, 0x4261fe20, 0x439aa00c, 0x215034e3, 0x0ff9570f, 0x4b1f2d5d, - 0x2d5d0c6f, 0x09634d0b, 0x1f51b8a0, 0x620f200c, 0xaf681e87, 0x24f94d07, 0x4e0f4945, 0xfe200c05, 0x22139742, 0x57048080, 0x23950c20, 0x97601585, - 0x4813201f, 0xad620523, 0x200f8f0f, 0x9e638f15, 0x00002181, 0x41342341, 0x0f930f0b, 0x210b4b62, 0x978f0001, 0xfe200f84, 0x8425c863, 0x2704822b, - 0x80000a00, 0x00038001, 0x610e9768, 0x834514bb, 0x0bc3430f, 0x2107e357, 0x80848080, 0x4400fe21, 0x2e410983, 0x00002a1a, 0x00000700, 0x800380ff, - 0x0fdf5800, 0x59150021, 0xd142163d, 0x0c02410c, 0x01020025, 0x65800300, 0x00240853, 0x1d333501, 0x15220382, 0x35420001, 0x44002008, 0x376406d7, - 0x096f6b19, 0x480bc142, 0x8f4908a7, 0x211f8b1f, 0x9e830001, 0x0584fe20, 0x4180fd21, 0x11850910, 0x8d198259, 0x000021d4, 0x5a08275d, 0x275d1983, - 0x06d9420e, 0x9f08b36a, 0x0f7d47b5, 0x8d8a2f8b, 0x4c0e0b57, 0xe7410e17, 0x42d18c1a, 0xb351087a, 0x1ac36505, 0x4b4a2f20, 0x0b9f450d, 0x430beb53, - 0xa7881015, 0xa5826a83, 0x80200f82, 0x86185a65, 0x4100208e, 0x176c3367, 0x0fe7650b, 0x4a17ad4b, 0x0f4217ed, 0x112e4206, 0x41113a42, 0xf7423169, - 0x0cb34737, 0x560f8b46, 0xa75407e5, 0x5f01200f, 0x31590c48, 0x80802106, 0x42268841, 0x0020091e, 0x4207ef64, 0x69461df7, 0x138d4114, 0x820f5145, - 0x53802090, 0xff200529, 0xb944b183, 0x417e8505, 0x00202561, 0x15210082, 0x42378200, 0x9b431cc3, 0x004f220d, 0x0dd54253, 0x4213f149, 0x7d41133b, - 0x42c9870b, 0x802010f9, 0x420b2c42, 0x8f441138, 0x267c4408, 0x600cb743, 0x8f4109d3, 0x05ab701d, 0x83440020, 0x3521223f, 0x0b794733, 0xfb62fe20, - 0x4afd2010, 0xaf410ae7, 0x25ce8525, 0x01080000, 0x7b6b0000, 0x0973710b, 0x82010021, 0x49038375, 0x33420767, 0x052c4212, 0x58464b85, 0x41fe2005, - 0x50440c27, 0x000c2209, 0x1cb36b80, 0x9b06df44, 0x0f93566f, 0x52830220, 0xfe216e8d, 0x200f8200, 0x0fb86704, 0xb057238d, 0x050b5305, 0x7217eb47, - 0xbd410b6b, 0x0f214610, 0x871f9956, 0x1e91567e, 0x2029b741, 0x20008200, 0x18b7410a, 0x27002322, 0x41095543, 0x0f8f0fb3, 0x41000121, 0x889d111c, - 0x14207b82, 0x00200382, 0x73188761, 0x475013a7, 0x6e33200c, 0x234e0ea3, 0x9b138313, 0x08e54d17, 0x9711094e, 0x2ee74311, 0x4908875e, 0xd75d1f1f, - 0x19ab5238, 0xa2084d48, 0x63a7a9b3, 0x55450b83, 0x0fd74213, 0x440d814c, 0x4f481673, 0x05714323, 0x13000022, 0x412e1f46, 0xdf493459, 0x21c7550f, - 0x8408215f, 0x201d49cb, 0xb1103043, 0x0f0d65d7, 0x452b8d41, 0x594b0f8d, 0x0b004605, 0xb215eb46, 0x000a24d7, 0x47000080, 0x002118cf, 0x06436413, - 0x420bd750, 0x2b500743, 0x076a470c, 0x4105c050, 0xd942053f, 0x0d00211a, 0x5f44779c, 0x0ce94805, 0x51558186, 0x14a54c0b, 0x49082b41, 0x0a4b0888, - 0x8080261f, 0x0d000000, 0x20048201, 0x1deb6a03, 0x420cb372, 0x07201783, 0x4306854d, 0x8b830c59, 0x59093c74, 0x0020250f, 0x67070f4a, 0x2341160b, - 0x00372105, 0x431c515d, 0x554e17ef, 0x0e5d6b05, 0x41115442, 0xb74a1ac1, 0x2243420a, 0x5b4f878f, 0x7507200f, 0x384b086f, 0x09d45409, 0x0020869a, - 0x12200082, 0xab460382, 0x10075329, 0x54138346, 0xaf540fbf, 0x1ea75413, 0x9a0c9e54, 0x0f6b44c1, 0x41000021, 0x47412a4f, 0x07374907, 0x5310bf76, - 0xff2009b4, 0x9a09a64c, 0x8200208d, 0x34c34500, 0x970fe141, 0x1fd74b0f, 0x440a3850, 0x206411f0, 0x27934609, 0x470c5d41, 0x555c2947, 0x1787540f, - 0x6e0f234e, 0x7d540a1b, 0x1d736b08, 0x0026a088, 0x80000e00, 0x9b5200ff, 0x08ef4318, 0x450bff77, 0x1d4d0b83, 0x081f7006, 0xcb691b86, 0x4b022008, - 0xc34b0b33, 0x1d0d4a0c, 0x8025a188, 0x0b000000, 0x52a38201, 0xbf7d0873, 0x0c234511, 0x8f0f894a, 0x4101200f, 0x0c880c9d, 0x2b418ea1, 0x06c74128, - 0x66181341, 0x7b4c0bb9, 0x0c06630b, 0xfe200c87, 0x9ba10882, 0x27091765, 0x01000008, 0x02800380, 0x48113f4e, 0x29430cf5, 0x09a75a0b, 0x31618020, - 0x6d802009, 0x61840e33, 0x8208bf51, 0x0c637d61, 0x7f092379, 0x4f470f4b, 0x1797510c, 0x46076157, 0xf5500fdf, 0x0f616910, 0x1171fe20, 0x82802006, - 0x08696908, 0x41127a4c, 0x3f4a15f3, 0x01042607, 0x0200ff00, 0x1cf77700, 0xff204185, 0x00235b8d, 0x43100000, 0x3b22243f, 0x3b4d3f00, 0x0b937709, - 0xad42f18f, 0x0b1f420f, 0x51084b43, 0x8020104a, 0xb557ff83, 0x052b7f2a, 0x0280ff22, 0x250beb78, 0x00170013, 0xbf6d2500, 0x07db760e, 0x410e2b7f, - 0x00230e4f, 0x49030000, 0x0582055b, 0x07000326, 0x00000b00, 0x580bcd46, 0x00200cdd, 0x57078749, 0x8749160f, 0x0f994f0a, 0x41134761, 0x01200b31, - 0xeb796883, 0x0b41500b, 0x0e90b38e, 0x202e7b51, 0x05d95801, 0x41080570, 0x1d530fc9, 0x0b937a0f, 0xaf8eb387, 0xf743b98f, 0x07c74227, 0x80000523, - 0x0fcb4503, 0x430ca37b, 0x7782077f, 0x8d0a9947, 0x08af4666, 0xeb798020, 0x6459881e, 0xc3740bbf, 0x0feb6f0b, 0x20072748, 0x052b6102, 0x435e0584, - 0x7d088308, 0x03200afd, 0x92109e41, 0x28aa8210, 0x80001500, 0x80030000, 0x0fdb5805, 0x209f4018, 0xa7418d87, 0x0aa3440f, 0x20314961, 0x073a52ff, - 0x6108505d, 0x43181051, 0x00223457, 0xe7820500, 0x50028021, 0x81410d33, 0x063d7108, 0xdb41af84, 0x4d888205, 0x00201198, 0x463d835f, 0x152106d7, - 0x0a355a33, 0x6917614e, 0x75411f4d, 0x184b8b07, 0x1809c344, 0x21091640, 0x0b828000, 0x42808021, 0x26790519, 0x86058605, 0x2428422d, 0x22123b42, - 0x42000080, 0xf587513b, 0x7813677b, 0xaf4d139f, 0x00ff210c, 0x5e0a1d57, 0x3b421546, 0x01032736, 0x02000380, 0x41180480, 0x2f420f07, 0x0c624807, - 0x00000025, 0x18000103, 0x83153741, 0x430120c3, 0x042106b2, 0x088d4d00, 0x2f830620, 0x1810434a, 0x18140345, 0x8507fb41, 0x5ee582ea, 0x0023116c, - 0x8d000600, 0x053b56af, 0xa6554fa2, 0x0d704608, 0x40180d20, 0x47181a43, 0xd37b07ff, 0x0b79500c, 0x420fd745, 0x47450bd9, 0x8471830a, 0x095a777e, - 0x84137542, 0x82002013, 0x2f401800, 0x0007213b, 0x4405e349, 0x0d550ff3, 0x16254c0c, 0x820ffe4a, 0x0400218a, 0x89066f41, 0x106b414f, 0xc84d0120, - 0x80802206, 0x0c9a4b03, 0x00100025, 0x68000200, 0x9d8c2473, 0x44134344, 0xf36a0f33, 0x4678860f, 0x1b440a25, 0x41988c0a, 0x80201879, 0x43079b5e, - 0x4a18080b, 0x0341190b, 0x1259530c, 0x43251552, 0x908205c8, 0x0cac4018, 0x86000421, 0x0e504aa2, 0x0020b891, 0xfb450082, 0x51132014, 0x8f5205f3, - 0x35052108, 0x8505cb59, 0x0f6d4f70, 0x82150021, 0x29af5047, 0x4f004b24, 0x75795300, 0x1b595709, 0x460b6742, 0xbf4b0f0d, 0x5743870b, 0xcb6d1461, - 0x08f64505, 0x4e05ab6c, 0x334126c3, 0x0bcb6b0d, 0x1811034d, 0x4111ef4b, 0x814f1ce5, 0x20af8227, 0x07fd7b80, 0x41188e84, 0xef410f33, 0x80802429, - 0x410d0000, 0xa34205ab, 0x76b7881c, 0xff500b89, 0x0741430f, 0x20086f4a, 0x209d8200, 0x234c18fd, 0x05d4670a, 0x4509af51, 0x9642078d, 0x189e831d, - 0x7c1cc74b, 0xcd4c07b9, 0x0e7c440f, 0x8b7b0320, 0x21108210, 0xc76c8080, 0x03002106, 0x6b23bf41, 0xc549060b, 0x7946180b, 0x0ff7530f, 0x17ad4618, - 0x200ecd45, 0x208c83fd, 0x5e0488fe, 0x032009c6, 0x420d044e, 0x0d8f0d7f, 0x00820020, 0x18001021, 0x6d273b45, 0xfd4c0c93, 0xcf451813, 0x0fe5450f, - 0x5a47c382, 0x820a8b0a, 0x282b4998, 0x410a8b5b, 0x4b232583, 0x54004f00, 0x978f0ce3, 0x500f1944, 0xa95f1709, 0x0280220b, 0x05ba7080, 0xa1530682, - 0x06324c13, 0x91412582, 0x05536e2c, 0x63431020, 0x0f434706, 0x8c11374c, 0x176143d7, 0x4d0f454c, 0xd3680bed, 0x0bee4d17, 0x212b9a41, 0x0f530a00, - 0x140d531c, 0x43139143, 0x95610e8d, 0x0f094415, 0x4205fb56, 0x1b4205cf, 0x17015225, 0x5e0c477f, 0xaf6e0aeb, 0x0ff36218, 0x04849a84, 0x0a454218, - 0x9c430420, 0x23c6822b, 0x04000102, 0x45091b4b, 0xf05f0955, 0x82802007, 0x421c2023, 0x5218282b, 0x7b53173f, 0x0fe7480c, 0x74173b7f, 0x47751317, - 0x634d1807, 0x0f6f430f, 0x24086547, 0xfc808002, 0x0b3c7f80, 0x10840120, 0x188d1282, 0x20096b43, 0x0fc24403, 0x00260faf, 0x0180000b, 0x3f500280, - 0x18002019, 0x450b4941, 0xf3530fb9, 0x18002010, 0x8208a551, 0x06234d56, 0xcb58a39b, 0xc3421805, 0x1313461e, 0x0f855018, 0xd34b0120, 0x6cfe2008, - 0x574f0885, 0x09204114, 0x07000029, 0x00008000, 0x44028002, 0x01420f57, 0x10c95c10, 0x11184c18, 0x80221185, 0x7f421e00, 0x00732240, 0x09cd4977, - 0x6d0b2b42, 0x4f180f8f, 0x8f5a0bcb, 0x9b0f830f, 0x0fb9411f, 0x230b5756, 0x00fd8080, 0x82060745, 0x000121d5, 0x8e0fb277, 0x4a8d4211, 0x24061c53, - 0x04000007, 0x12275280, 0x430c954c, 0x80201545, 0x200f764f, 0x20008200, 0x20ce8308, 0x09534f02, 0x660edf64, 0x73731771, 0xe7411807, 0x20a2820c, - 0x13b64404, 0x8f5d6682, 0x1d6b4508, 0x0cff4d18, 0x3348c58f, 0x0fc34c07, 0x31558b84, 0x8398820f, 0x17514712, 0x240b0e46, 0x80000a00, 0x093b4502, - 0x420f9759, 0xa54c0bf1, 0x0f2b470c, 0x410d314b, 0x2584170c, 0x73b30020, 0xb55fe782, 0x204d8410, 0x08e043fe, 0x4f147e41, 0x022008ab, 0x4b055159, - 0x2950068f, 0x00022208, 0x48511880, 0x82002009, 0x00112300, 0x634dff00, 0x24415f27, 0x180f6d43, 0x4d0b5d45, 0x4d5f05ef, 0x01802317, 0x56188000, - 0xa7840807, 0xc6450220, 0x21ca8229, 0x4b781a00, 0x3359182c, 0x0cf3470f, 0x180bef46, 0x420b0354, 0xff470b07, 0x4515200a, 0x9758239b, 0x4a80200c, - 0xd2410a26, 0x05fb4a08, 0x4b05e241, 0x03200dc9, 0x92290941, 0x00002829, 0x00010900, 0x5b020001, 0x23201363, 0x460d776a, 0xef530fdb, 0x209a890c, - 0x13fc4302, 0x00008024, 0xc4820104, 0x08820220, 0x20086b5b, 0x18518700, 0x8408d349, 0x0da449a1, 0x00080024, 0x7b690280, 0x4c438b1a, 0x01220f63, - 0x4c878000, 0x5c149c53, 0xfb430868, 0x2f56181e, 0x0ccf7b1b, 0x0f075618, 0x2008e347, 0x14144104, 0x00207f83, 0x00207b82, 0x201adf47, 0x16c35a13, - 0x540fdf47, 0x802006c8, 0x5418f185, 0x29430995, 0x00002419, 0x58001600, 0x5720316f, 0x4d051542, 0x4b7b1b03, 0x138f4707, 0xb747b787, 0x4aab8213, - 0x058305fc, 0x20115759, 0x82128401, 0x0a0b44e8, 0x46800121, 0xe64210d0, 0x82129312, 0x4bffdffe, 0x3b41171b, 0x9b27870f, 0x808022ff, 0x085c68fe, - 0x41800021, 0x01410b20, 0x001a213a, 0x47480082, 0x11374e12, 0x56130b4c, 0xdf4b0c65, 0x0b0f590b, 0x0f574c18, 0x830feb4b, 0x075f480f, 0x480b4755, - 0x40490b73, 0x80012206, 0x09d74280, 0x80fe8022, 0x80210e86, 0x056643ff, 0x10820020, 0x420b2646, 0x0b58391a, 0xd74c1808, 0x078b4e22, 0x2007f55f, - 0x4b491807, 0x83802017, 0x65aa82a7, 0x3152099e, 0x068b7616, 0x9b431220, 0x09bb742c, 0x500e376c, 0x8342179b, 0x0a4d5d0f, 0x8020a883, 0x180cd349, - 0x2016bb4b, 0x14476004, 0x84136c43, 0x08cf7813, 0x4f4c0520, 0x156f420f, 0x20085f42, 0x6fd3be03, 0xd4d30803, 0xa7411420, 0x004b222c, 0x0d3b614f, - 0x3f702120, 0x1393410a, 0x8f132745, 0x47421827, 0x41e08209, 0xb05e2bb9, 0x18b7410c, 0x18082647, 0x4107a748, 0xeb8826bf, 0x0ca76018, 0x733ecb41, - 0xd0410d83, 0x43ebaf2a, 0x0420067f, 0x721dab4c, 0x472005bb, 0x4105d341, 0x334844cb, 0x20dba408, 0x47d6ac00, 0x034e3aef, 0x0f8f421b, 0x930f134d, - 0x3521231f, 0xb7421533, 0x42f5ad0a, 0x1e961eaa, 0x17000022, 0x4c367b50, 0x7d491001, 0x0bf5520f, 0x4c18fda7, 0xb8460c55, 0x83fe2005, 0x00fe25b9, - 0x80000180, 0x9e751085, 0x261b5c12, 0x82110341, 0x001123fb, 0x4518fe80, 0xf38c2753, 0x6d134979, 0x295107a7, 0xaf5f180f, 0x0fe3660c, 0x180b6079, - 0x2007bd5f, 0x9aab9103, 0x2f4d1811, 0x05002109, 0x44254746, 0x1d200787, 0x450bab75, 0x4f180f57, 0x4f181361, 0x3b831795, 0xeb4b0120, 0x0b734805, - 0x84078f48, 0x2e1b47bc, 0x00203383, 0xaf065f45, 0x831520d7, 0x130f51a7, 0x1797bf97, 0x2b47d783, 0x18fe2005, 0x4a18a44f, 0xa64d086d, 0x1ab0410d, - 0x6205a258, 0xdbab069f, 0x4f06f778, 0xa963081d, 0x133b670a, 0x8323d141, 0x13195b23, 0x530f5e70, 0xe5ad0824, 0x58001421, 0x1f472b4b, 0x47bf410c, - 0x82000121, 0x83fe20cb, 0x07424404, 0x68068243, 0xd7ad0d3d, 0x00010d26, 0x80020000, 0x4a1c6f43, 0x23681081, 0x10a14f13, 0x8a070e57, 0x430a848f, - 0x7372243e, 0x4397a205, 0xb56c1021, 0x43978f0f, 0x64180505, 0x99aa0ff2, 0x0e000022, 0x20223341, 0x094b4f37, 0x074a3320, 0x2639410a, 0xfe208e84, - 0x8b0e0048, 0x508020a3, 0x9e4308fe, 0x073f4115, 0xe3480420, 0x0c9b5f1b, 0x7c137743, 0x9a95185b, 0x6122b148, 0x979b08df, 0x0fe36c18, 0x48109358, - 0x23441375, 0x0ffd5c0b, 0x180fc746, 0x2011d157, 0x07e95702, 0x58180120, 0x18770ac3, 0x51032008, 0x7d4118e3, 0x80802315, 0x3b4c1900, 0xbb5a1830, - 0x0ceb6109, 0x5b0b3d42, 0x4f181369, 0x4f180b8d, 0x4f180f75, 0x355a1b81, 0x200d820d, 0x18e483fd, 0x4528854f, 0x89420846, 0x1321411f, 0x44086b60, - 0x07421d77, 0x107d4405, 0x4113fd41, 0x5a181bf1, 0x4f180db3, 0x8021128f, 0x20f68280, 0x44a882fe, 0x334d249a, 0x052f6109, 0x1520c3a7, 0xef4eb783, - 0x4ec39b1b, 0xc4c90ee7, 0x20060b4d, 0x256f4905, 0x4d0cf761, 0xcf9b1f13, 0xa213d74e, 0x0e1145d4, 0x50135b42, 0xcb4e398f, 0x20d79f27, 0x08865d80, - 0x186d5018, 0xa90f7142, 0x067342d7, 0x3f450420, 0x65002021, 0xe3560771, 0x24d38f23, 0x15333531, 0x0eb94d01, 0x451c9f41, 0x384322fb, 0x00092108, - 0x19af6b18, 0x6e0c6f5a, 0xbd770bfb, 0x22bb7718, 0x20090f57, 0x25e74204, 0x4207275a, 0xdb5408ef, 0x1769450f, 0x1b1b5518, 0x210b1f57, 0x5e4c8001, - 0x55012006, 0x802107f1, 0x0a306a80, 0x45808021, 0x0d850b88, 0x31744f18, 0x1808ec54, 0x2009575b, 0x45ffa505, 0x1b420c73, 0x180f9f0f, 0x4a0cf748, - 0x501805b2, 0x00210f40, 0x4d118f80, 0xd6823359, 0x072b5118, 0x314ad7aa, 0x8fc79f08, 0x45d78b1f, 0xfe20058f, 0x23325118, 0x7b54d9b5, 0x9fc38f46, - 0x10bb410f, 0x41077b42, 0xc1410faf, 0x27cf441d, 0x46051b4f, 0x04200683, 0x2121d344, 0x8f530043, 0x8fcf9f0e, 0x21df8c1f, 0x50188000, 0x5d180e52, - 0xfd201710, 0x4405c341, 0xd68528e3, 0x20071f6b, 0x1b734305, 0x6b080957, 0x7d422b1f, 0x67002006, 0x7f8317b1, 0x2024cb48, 0x08676e00, 0x8749a39b, - 0x18132006, 0x410a6370, 0x8f490b47, 0x7e1f8f13, 0x551805c3, 0x4c180915, 0xfe200e2f, 0x244d5d18, 0x270bcf44, 0xff000019, 0x04800380, 0x5f253342, - 0xff520df7, 0x13274c18, 0x5542dd93, 0x0776181b, 0xf94a1808, 0x084a4c0c, 0x4308ea5b, 0xde831150, 0x7900fd21, 0x00492c1e, 0x060f4510, 0x17410020, - 0x0ce74526, 0x6206b341, 0x1f561083, 0x9d6c181b, 0x08a0500e, 0x112e4118, 0x60000421, 0xbf901202, 0x4408e241, 0xc7ab0513, 0xb40f0950, 0x055943c7, - 0x4f18ff20, 0xc9ae1cad, 0x32b34f18, 0x7a180120, 0x3d520a05, 0x53d1b40a, 0x80200813, 0x1b815018, 0x832bf86f, 0x67731847, 0x297f4308, 0x6418d54e, - 0x734213f7, 0x056b4b27, 0xdba5fe20, 0x1828aa4e, 0x2031a370, 0x06cb6101, 0x2040ad41, 0x07365300, 0x2558d985, 0x83fe200c, 0x0380211c, 0x542c4743, - 0x052006b7, 0x6021df45, 0x897b0707, 0x18d3c010, 0x20090e70, 0x1d5843ff, 0x540a0e44, 0x002126c5, 0x322f7416, 0x636a5720, 0x0f317409, 0x610fe159, - 0x294617e7, 0x08555213, 0x2006a75d, 0x6cec84fd, 0xfb5907be, 0x3a317405, 0x83808021, 0x180f20ea, 0x4626434a, 0x531818e3, 0xdb59172d, 0x0cbb460c, - 0x2013d859, 0x18b94502, 0x8f46188d, 0x77521842, 0x0a184e38, 0x9585fd20, 0x6a180684, 0xc64507e9, 0x51cbb230, 0xd3440cf3, 0x17ff6a0f, 0x450f5b42, - 0x276407c1, 0x4853180a, 0x21ccb010, 0xcf580013, 0x0c15442d, 0x410a1144, 0x1144359d, 0x5cfe2006, 0xa1410a43, 0x2bb64519, 0x2f5b7618, 0xb512b745, - 0x0cfd6fd1, 0x42089f59, 0xb8450c70, 0x0000232d, 0x50180900, 0xb9491ae3, 0x0fc37610, 0x01210f83, 0x0f3b4100, 0xa01b2742, 0x0ccd426f, 0x6e8f6f94, - 0x9c808021, 0xc7511870, 0x17c74b08, 0x9b147542, 0x44fe2079, 0xd5480c7e, 0x95ef861d, 0x101b597b, 0xf5417594, 0x9f471808, 0x86868d0e, 0x3733491c, - 0x690f4d6d, 0x43440b83, 0x1ba94c0b, 0x660cd16b, 0x802008ae, 0x74126448, 0xcb4f38a3, 0x2cb74b0b, 0x47137755, 0xe3971777, 0x1b5d0120, 0x057a4108, - 0x6e08664d, 0x17421478, 0x11af4208, 0x850c3f42, 0x08234f0c, 0x4321eb4a, 0xf3451095, 0x0f394e0f, 0x4310eb45, 0xc09707b1, 0x54431782, 0xaec08d1d, - 0x0f434dbb, 0x9f0c0b45, 0x0a3b4dbb, 0x4618bdc7, 0x536032eb, 0x17354213, 0x4d134169, 0xc7a30c2f, 0x4e254342, 0x174332cf, 0x43cdae17, 0x6b4706e4, - 0x0e16430d, 0x530b5542, 0x2f7c26bb, 0x13075f31, 0x43175342, 0x60181317, 0x6550114e, 0x28624710, 0x58070021, 0x59181683, 0x2d540cf5, 0x05d5660c, - 0x20090c7b, 0x0e157e02, 0x8000ff2b, 0x14000080, 0x80ff8000, 0x27137e03, 0x336a4b20, 0x0f817107, 0x13876e18, 0x730f2f7e, 0x2f450b75, 0x6d02200b, - 0x6d66094c, 0x4b802009, 0x15820a02, 0x2f45fe20, 0x5e032006, 0x00202fd9, 0x450af741, 0xeb412e0f, 0x0ff3411f, 0x420a8b65, 0xf7410eae, 0x1c664810, - 0x540e1145, 0xbfa509f3, 0x42302f58, 0x80200c35, 0xcb066c47, 0x4b1120c1, 0x41492abb, 0x34854110, 0xa7097b72, 0x251545c7, 0x4b2c7f56, 0xc5b40bab, - 0x940cd54e, 0x2e6151c8, 0x09f35f18, 0x4b420420, 0x09677121, 0x8f24f357, 0x1b5418e1, 0x08915a1f, 0x3143d894, 0x22541805, 0x1b9b4b0e, 0x8c0d3443, - 0x1400240d, 0x18ff8000, 0x582e6387, 0xf99b2b3b, 0x8807a550, 0x17a14790, 0x2184fd20, 0x5758fe20, 0x2354882c, 0x15000080, 0x5e056751, 0x334c2c2f, - 0x97c58f0c, 0x1fd7410f, 0x0d4d4018, 0x4114dc41, 0x04470ed6, 0x0dd54128, 0x00820020, 0x02011523, 0x22008700, 0x86480024, 0x0001240a, 0x8682001a, - 0x0002240b, 0x866c000e, 0x8a03200b, 0x8a042017, 0x0005220b, 0x22218614, 0x84060000, 0x86012017, 0x8212200f, 0x250b8519, 0x000d0001, 0x0b850031, - 0x07000224, 0x0b862600, 0x11000324, 0x0b862d00, 0x238a0420, 0x0a000524, 0x17863e00, 0x17840620, 0x01000324, 0x57820904, 0x0b85a783, 0x0b85a785, - 0x0b85a785, 0x22000325, 0x85007a00, 0x85a7850b, 0x85a7850b, 0x22a7850b, 0x82300032, 0x00342201, 0x0805862f, 0x35003131, 0x54207962, 0x74736972, - 0x47206e61, 0x6d6d6972, 0x65527265, 0x616c7567, 0x58545472, 0x6f725020, 0x43796767, 0x6e61656c, 0x30325454, 0x822f3430, 0x35313502, 0x79006200, - 0x54002000, 0x69007200, 0x74007300, 0x6e006100, 0x47200f82, 0x6d240f84, 0x65006d00, 0x52200982, 0x67240582, 0x6c007500, 0x72201d82, 0x54222b82, - 0x23825800, 0x19825020, 0x67006f22, 0x79220182, 0x1b824300, 0x3b846520, 0x1f825420, 0x41000021, 0x1422099b, 0x0b410000, 0x87088206, 0x01012102, - 0x78080982, 0x01020101, 0x01040103, 0x01060105, 0x01080107, 0x010a0109, 0x010c010b, 0x010e010d, 0x0110010f, 0x01120111, 0x01140113, 0x01160115, - 0x01180117, 0x011a0119, 0x011c011b, 0x011e011d, 0x0020011f, 0x00040003, 0x00060005, 0x00080007, 0x000a0009, 0x000c000b, 0x000e000d, 0x0010000f, - 0x00120011, 0x00140013, 0x00160015, 0x00180017, 0x001a0019, 0x001c001b, 0x001e001d, 0x08bb821f, 0x22002142, 0x24002300, 0x26002500, 0x28002700, - 0x2a002900, 0x2c002b00, 0x2e002d00, 0x30002f00, 0x32003100, 0x34003300, 0x36003500, 0x38003700, 0x3a003900, 0x3c003b00, 0x3e003d00, 0x40003f00, - 0x42004100, 0x4b09f382, 0x00450044, 0x00470046, 0x00490048, 0x004b004a, 0x004d004c, 0x004f004e, 0x00510050, 0x00530052, 0x00550054, 0x00570056, - 0x00590058, 0x005b005a, 0x005d005c, 0x005f005e, 0x01610060, 0x01220121, 0x01240123, 0x01260125, 0x01280127, 0x012a0129, 0x012c012b, 0x012e012d, - 0x0130012f, 0x01320131, 0x01340133, 0x01360135, 0x01380137, 0x013a0139, 0x013c013b, 0x013e013d, 0x0140013f, 0x00ac0041, 0x008400a3, 0x00bd0085, - 0x00e80096, 0x008e0086, 0x009d008b, 0x00a400a9, 0x008a00ef, 0x008300da, 0x00f20093, 0x008d00f3, 0x00880097, 0x00de00c3, 0x009e00f1, 0x00f500aa, - 0x00f600f4, 0x00ad00a2, 0x00c700c9, 0x006200ae, 0x00900063, 0x00cb0064, 0x00c80065, 0x00cf00ca, 0x00cd00cc, 0x00e900ce, 0x00d30066, 0x00d100d0, - 0x006700af, 0x009100f0, 0x00d400d6, 0x006800d5, 0x00ed00eb, 0x006a0089, 0x006b0069, 0x006c006d, 0x00a0006e, 0x0071006f, 0x00720070, 0x00750073, - 0x00760074, 0x00ea0077, 0x007a0078, 0x007b0079, 0x007c007d, 0x00a100b8, 0x007e007f, 0x00810080, 0x00ee00ec, 0x6e750eba, 0x646f6369, 0x78302365, - 0x31303030, 0x32200e8d, 0x33200e8d, 0x34200e8d, 0x35200e8d, 0x36200e8d, 0x37200e8d, 0x38200e8d, 0x39200e8d, 0x61200e8d, 0x62200e8d, 0x63200e8d, - 0x64200e8d, 0x65200e8d, 0x66200e8d, 0x31210e8c, 0x8d0e8d30, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, - 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x66312def, 0x6c656406, 0x04657465, 0x6f727545, 0x3820ec8c, 0x3820ec8d, - 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, - 0x3820ec8d, 0x200ddc41, 0x0ddc4139, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, - 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0x00663923, 0x48fa0500, 0x00f762f9, -}; - -static void GetDefaultCompressedFontDataTTF(const void** ttf_compressed_data, unsigned int* ttf_compressed_size) -{ - *ttf_compressed_data = proggy_clean_ttf_compressed_data; - *ttf_compressed_size = proggy_clean_ttf_compressed_size; -} - -//----------------------------------------------------------------------------- - -//---- Include imgui_user.inl at the end of imgui.cpp -//---- So you can include code that extends ImGui using its private data/functions. +// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed. +// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github. #ifdef IMGUI_INCLUDE_IMGUI_USER_INL #include "imgui_user.inl" #endif diff --git a/modules/onscreengui/ext/imgui/imgui.h b/modules/onscreengui/ext/imgui/imgui.h index 8331d747c2..50971f949b 100644 --- a/modules/onscreengui/ext/imgui/imgui.h +++ b/modules/onscreengui/ext/imgui/imgui.h @@ -1,19 +1,27 @@ -// ImGui library v1.39 WIP -// See .cpp file for documentation. -// See ImGui::ShowTestWindow() for sample code. -// Read 'Programmer guide' in .cpp for notes on how to setup ImGui in your codebase. +// dear imgui, v1.49 +// (headers) + +// See imgui.cpp file for documentation. +// See ImGui::ShowTestWindow() in imgui_demo.cpp for demo code. +// Read 'Programmer guide' in imgui.cpp for notes on how to setup ImGui in your codebase. // Get latest version at https://github.com/ocornut/imgui #pragma once +#if !defined(IMGUI_DISABLE_INCLUDE_IMCONFIG_H) || defined(IMGUI_INCLUDE_IMCONFIG_H) #include "imconfig.h" // User-editable configuration file +#endif #include // FLT_MAX #include // va_list #include // ptrdiff_t, NULL -#include // NULL, malloc, free, qsort, atoi #include // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp -#define IMGUI_VERSION "1.39 WIP" +#define IMGUI_VERSION "1.49" + +// Define attributes of all API symbols declarations, e.g. for DLL under Windows. +#ifndef IMGUI_API +#define IMGUI_API +#endif // Define assertion handler. #ifndef IM_ASSERT @@ -21,43 +29,68 @@ #define IM_ASSERT(_EXPR) assert(_EXPR) #endif -// Define attributes of all API symbols declarations, e.g. for DLL under Windows. -#ifndef IMGUI_API -#define IMGUI_API +// Some compilers support applying printf-style warnings to user functions. +#if defined(__clang__) || defined(__GNUC__) +#define IM_PRINTFARGS(FMT) __attribute__((format(printf, FMT, (FMT+1)))) +#else +#define IM_PRINTFARGS(FMT) +#endif + +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" #endif // Forward declarations -struct ImDrawCmd; -struct ImDrawList; -struct ImFont; -struct ImFontAtlas; -struct ImGuiIO; -struct ImGuiStorage; -struct ImGuiStyle; +struct ImDrawChannel; // Temporary storage for outputting drawing commands out of order, used by ImDrawList::ChannelsSplit() +struct ImDrawCmd; // A single draw command within a parent ImDrawList (generally maps to 1 GPU draw call) +struct ImDrawData; // All draw command lists required to render the frame +struct ImDrawList; // A single draw command list (generally one per window) +struct ImDrawVert; // A single vertex (20 bytes by default, override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT) +struct ImFont; // Runtime data for a single font within a parent ImFontAtlas +struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF font loader +struct ImFontConfig; // Configuration data when adding a font or merging fonts +struct ImColor; // Helper functions to create a color that can be converted to either u32 or float4 +struct ImGuiIO; // Main configuration and I/O between your application and ImGui +struct ImGuiOnceUponAFrame; // Simple helper for running a block of code not more than once a frame, used by IMGUI_ONCE_UPON_A_FRAME macro +struct ImGuiStorage; // Simple custom key value storage +struct ImGuiStyle; // Runtime data for styling/colors +struct ImGuiTextFilter; // Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" +struct ImGuiTextBuffer; // Text buffer for logging/accumulating text +struct ImGuiTextEditCallbackData; // Shared state of ImGui::InputText() when using custom ImGuiTextEditCallback (rare/advanced use) +struct ImGuiSizeConstraintCallbackData;// Structure used to constraint window size in custom ways when using custom ImGuiSizeConstraintCallback (rare/advanced use) +struct ImGuiListClipper; // Helper to manually clip large list of items +struct ImGuiContext; // ImGui context (opaque) +// Enumerations (declared as int for compatibility and to not pollute the top of this file) typedef unsigned int ImU32; typedef unsigned short ImWchar; // character for keyboard input/display -typedef void* ImTextureID; // user data to refer to a texture (e.g. store your texture handle/id) +typedef void* ImTextureID; // user data to identify a texture (this is whatever to you want it to be! read the FAQ about ImTextureID in imgui.cpp) typedef ImU32 ImGuiID; // unique ID used by widgets (typically hashed from a stack of string) -typedef int ImGuiCol; // enum ImGuiCol_ -typedef int ImGuiStyleVar; // enum ImGuiStyleVar_ -typedef int ImGuiKey; // enum ImGuiKey_ -typedef int ImGuiAlign; // enum ImGuiAlign_ -typedef int ImGuiColorEditMode; // enum ImGuiColorEditMode_ -typedef int ImGuiMouseCursor; // enum ImGuiMouseCursor_ -typedef int ImGuiWindowFlags; // enum ImGuiWindowFlags_ -typedef int ImGuiSetCond; // enum ImGuiSetCond_ -typedef int ImGuiInputTextFlags; // enum ImGuiInputTextFlags_ -struct ImGuiTextEditCallbackData; // for advanced uses of InputText() +typedef int ImGuiCol; // a color identifier for styling // enum ImGuiCol_ +typedef int ImGuiStyleVar; // a variable identifier for styling // enum ImGuiStyleVar_ +typedef int ImGuiKey; // a key identifier (ImGui-side enum) // enum ImGuiKey_ +typedef int ImGuiAlign; // alignment // enum ImGuiAlign_ +typedef int ImGuiColorEditMode; // color edit mode for ColorEdit*() // enum ImGuiColorEditMode_ +typedef int ImGuiMouseCursor; // a mouse cursor identifier // enum ImGuiMouseCursor_ +typedef int ImGuiWindowFlags; // window flags for Begin*() // enum ImGuiWindowFlags_ +typedef int ImGuiSetCond; // condition flags for Set*() // enum ImGuiSetCond_ +typedef int ImGuiInputTextFlags; // flags for InputText*() // enum ImGuiInputTextFlags_ +typedef int ImGuiSelectableFlags; // flags for Selectable() // enum ImGuiSelectableFlags_ +typedef int ImGuiTreeNodeFlags; // flags for TreeNode*(), Collapsing*() // enum ImGuiTreeNodeFlags_ typedef int (*ImGuiTextEditCallback)(ImGuiTextEditCallbackData *data); +typedef void (*ImGuiSizeConstraintCallback)(ImGuiSizeConstraintCallbackData* data); + +// Others helpers at bottom of the file: +// class ImVector<> // Lightweight std::vector like class. +// IMGUI_ONCE_UPON_A_FRAME // Execute a block of code once per frame only (convenient for creating UI within deep-nested code that runs multiple times) struct ImVec2 { float x, y; ImVec2() { x = y = 0.0f; } ImVec2(float _x, float _y) { x = _x; y = _y; } - -#ifdef IM_VEC2_CLASS_EXTRA // Define constructor and implicit cast operators to convert back<>forth from your math types and ImVec2. +#ifdef IM_VEC2_CLASS_EXTRA // Define constructor and implicit cast operators in imconfig.h to convert back<>forth from your math types and ImVec2. IM_VEC2_CLASS_EXTRA #endif }; @@ -67,24 +100,11 @@ struct ImVec4 float x, y, z, w; ImVec4() { x = y = z = w = 0.0f; } ImVec4(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; } - -#ifdef IM_VEC4_CLASS_EXTRA // Define constructor and implicit cast operators to convert back<>forth from your math types and ImVec4. +#ifdef IM_VEC4_CLASS_EXTRA // Define constructor and implicit cast operators in imconfig.h to convert back<>forth from your math types and ImVec4. IM_VEC4_CLASS_EXTRA #endif }; -// Helpers at bottom of the file: -// - class ImVector<> // Lightweight std::vector like class. Use '#define ImVector std::vector' if you want to use the STL type or your own type. -// - IMGUI_ONCE_UPON_A_FRAME // Execute a block of code once per frame only (convenient for creating UI within deep-nested code that runs multiple times) -// - struct ImGuiTextFilter // Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" -// - struct ImGuiTextBuffer // Text buffer for logging/accumulating text -// - struct ImGuiStorage // Custom key value storage (if you need to alter open/close states manually) -// - struct ImGuiTextEditCallbackData // Shared state of ImGui::InputText() when using custom callbacks -// - struct ImColor // Helper functions to created packed 32-bit RGBA color values -// - struct ImDrawList // Draw command list -// - struct ImFontAtlas // Bake multiple fonts into a single texture, TTF font loader, bake glyphs into bitmap -// - struct ImFont // Single font - // ImGui end-user API // In a namespace so that user can add extra functions in a separate file (e.g. Value() helpers for your vector or common types) namespace ImGui @@ -92,51 +112,62 @@ namespace ImGui // Main IMGUI_API ImGuiIO& GetIO(); IMGUI_API ImGuiStyle& GetStyle(); - IMGUI_API void NewFrame(); - IMGUI_API void Render(); + IMGUI_API ImDrawData* GetDrawData(); // same value as passed to your io.RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame() + IMGUI_API void NewFrame(); // start a new ImGui frame, you can submit any command from this point until NewFrame()/Render(). + IMGUI_API void Render(); // ends the ImGui frame, finalize rendering data, then call your io.RenderDrawListsFn() function if set. IMGUI_API void Shutdown(); IMGUI_API void ShowUserGuide(); // help block - IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // style editor block - IMGUI_API void ShowTestWindow(bool* opened = NULL); // test window, demonstrate ImGui features - IMGUI_API void ShowMetricsWindow(bool* opened = NULL); // metrics window for debugging imgui + IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // style editor block. you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style) + IMGUI_API void ShowTestWindow(bool* p_open = NULL); // test window demonstrating ImGui features + IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // metrics window for debugging ImGui // Window - // See implementation in .cpp for details - IMGUI_API bool Begin(const char* name = "Debug", bool* p_opened = NULL, ImGuiWindowFlags flags = 0); // return false when window is collapsed, so you can early out in your code. 'bool* p_opened' creates a widget on the upper-right to close the window (which sets your bool to false). - IMGUI_API bool Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_use, float bg_alpha = -1.0f, ImGuiWindowFlags flags = 0); // this is the older/longer API. call SetNextWindowSize() instead if you want to set a window size. For regular windows, 'size_on_first_use' only applies to the first time EVER the window is created and probably not what you want! maybe obsolete this API eventually. - IMGUI_API void End(); - IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // size==0.0f: use remaining window size, size<0.0f: use remaining window size minus abs(size). size>0.0f: fixed size. each axis can use a different mode, e.g. ImVec2(0,400). - IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // " + IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // push window to the stack and start appending to it. see .cpp for details. return false when window is collapsed, so you can early out in your code. 'bool* p_open' creates a widget on the upper-right to close the window (which sets your bool to false). + IMGUI_API bool Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha = -1.0f, ImGuiWindowFlags flags = 0); // OBSOLETE. this is the older/longer API. the extra parameters aren't very relevant. call SetNextWindowSize() instead if you want to set a window size. For regular windows, 'size_on_first_use' only applies to the first time EVER the window is created and probably not what you want! might obsolete this API eventually. + IMGUI_API void End(); // finish appending to current window, pop it off the window stack. + IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // begin a scrolling region. size==0.0f: use remaining window size, size<0.0f: use remaining window size minus abs(size). size>0.0f: fixed size. each axis can use a different mode, e.g. ImVec2(0,400). + IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // " IMGUI_API void EndChild(); - IMGUI_API ImVec2 GetContentRegionMax(); // window or current column boundaries, in windows coordinates - IMGUI_API ImVec2 GetWindowContentRegionMin(); // window boundaries, in windows coordinates - IMGUI_API ImVec2 GetWindowContentRegionMax(); + IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates + IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos() + IMGUI_API float GetContentRegionAvailWidth(); // + IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min (roughly (0,0)-Scroll), in window coordinates + IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(), in window coordinates + IMGUI_API float GetWindowContentRegionWidth(); // IMGUI_API ImDrawList* GetWindowDrawList(); // get rendering command-list if you want to append your own draw primitives - IMGUI_API ImFont* GetWindowFont(); - IMGUI_API float GetWindowFontSize(); // size (also height in pixels) of current font with current scale applied - IMGUI_API void SetWindowFontScale(float scale); // per-window font scale. Adjust IO.FontGlobalScale if you want to scale all windows - IMGUI_API ImVec2 GetWindowPos(); // you should rarely need/care about the window position, but it can be useful if you want to do your own drawing - IMGUI_API ImVec2 GetWindowSize(); // get current window position + IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (useful if you want to do your own drawing via the DrawList api) + IMGUI_API ImVec2 GetWindowSize(); // get current window size IMGUI_API float GetWindowWidth(); - IMGUI_API bool GetWindowCollapsed(); + IMGUI_API float GetWindowHeight(); + IMGUI_API bool IsWindowCollapsed(); + IMGUI_API void SetWindowFontScale(float scale); // per-window font scale. Adjust IO.FontGlobalScale if you want to scale all windows - IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiSetCond cond = 0); // set next window position - call before Begin() - IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiSetCond cond = 0); // set next window size. set to ImVec2(0,0) to force an auto-fit - IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiSetCond cond = 0); // set next window collapsed state - IMGUI_API void SetNextWindowFocus(); // set next window to be focused / front-most - IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiSetCond cond = 0); // set current window position - call within Begin()/End(). may incur tearing - IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiSetCond cond = 0); // set current window size. set to ImVec2(0,0) to force an auto-fit. may incur tearing - IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiSetCond cond = 0); // set current window collapsed state - IMGUI_API void SetWindowFocus(); // set current window to be focused / front-most - IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond = 0); // set named window position - call within Begin()/End(). may incur tearing - IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond cond = 0); // set named window size. set to ImVec2(0,0) to force an auto-fit. may incur tearing + IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiSetCond cond = 0); // set next window position. call before Begin() + IMGUI_API void SetNextWindowPosCenter(ImGuiSetCond cond = 0); // set next window position to be centered on screen. call before Begin() + IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiSetCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin() + IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeConstraintCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Use callback to apply non-trivial programmatic constraints. + IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (enforce the range of scrollbars). set axis to 0.0f to leave it automatic. call before Begin() + IMGUI_API void SetNextWindowContentWidth(float width); // set next window content width (enforce the range of horizontal scrollbar). call before Begin() + IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiSetCond cond = 0); // set next window collapsed state. call before Begin() + IMGUI_API void SetNextWindowFocus(); // set next window to be focused / front-most. call before Begin() + IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiSetCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects. + IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiSetCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0,0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects. + IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiSetCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed(). + IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / front-most. prefer using SetNextWindowFocus(). + IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond = 0); // set named window position. + IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis. IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiSetCond cond = 0); // set named window collapsed state IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / front-most. use NULL to remove focus. - IMGUI_API float GetScrollPosY(); // get scrolling position [0..GetScrollMaxY()] - IMGUI_API float GetScrollMaxY(); // get maximum scrolling position == ContentSize.Y - WindowSize.Y - IMGUI_API void SetScrollPosHere(); // adjust scrolling position to center into the current cursor position - IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget + IMGUI_API float GetScrollX(); // get scrolling amount [0..GetScrollMaxX()] + IMGUI_API float GetScrollY(); // get scrolling amount [0..GetScrollMaxY()] + IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.X - WindowSize.X + IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.Y - WindowSize.Y + IMGUI_API void SetScrollX(float scroll_x); // set scrolling amount [0..GetScrollMaxX()] + IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0..GetScrollMaxY()] + IMGUI_API void SetScrollHere(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. + IMGUI_API void SetScrollFromPosY(float pos_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position valid. use GetCursorPos() or GetCursorStartPos()+offset to get valid positions. + IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use negative 'offset' to access previous widgets. IMGUI_API void SetStateStorage(ImGuiStorage* tree); // replace tree state storage with our own (if you want to manipulate it yourself, typically clear subsection of it) IMGUI_API ImGuiStorage* GetStateStorage(); @@ -148,84 +179,89 @@ namespace ImGui IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); IMGUI_API void PopStyleVar(int count = 1); + IMGUI_API ImFont* GetFont(); // get current font + IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied + IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API + IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier + IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied // Parameters stacks (current window) IMGUI_API void PushItemWidth(float item_width); // width of items for the common item+label case, pixels. 0.0f = default to ~2/3 of windows width, >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side) IMGUI_API void PopItemWidth(); IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position - IMGUI_API void PushAllowKeyboardFocus(bool v); // allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets - IMGUI_API void PopAllowKeyboardFocus(); IMGUI_API void PushTextWrapPos(float wrap_pos_x = 0.0f); // word-wrapping for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space IMGUI_API void PopTextWrapPos(); + IMGUI_API void PushAllowKeyboardFocus(bool v); // allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets + IMGUI_API void PopAllowKeyboardFocus(); + IMGUI_API void PushButtonRepeat(bool repeat); // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (uses io.KeyRepeatDelay/io.KeyRepeatRate for now). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame. + IMGUI_API void PopButtonRepeat(); - // Tooltip - IMGUI_API void SetTooltip(const char* fmt, ...); // set tooltip under mouse-cursor, typically use with ImGui::IsHovered(). last call wins - IMGUI_API void SetTooltipV(const char* fmt, va_list args); - IMGUI_API void BeginTooltip(); // use to create full-featured tooltip windows that aren't just text - IMGUI_API void EndTooltip(); - - // Popup - IMGUI_API void BeginPopup(bool* p_opened); - IMGUI_API void EndPopup(); - - // Layout - IMGUI_API void BeginGroup(); - IMGUI_API void EndGroup(); + // Cursor / Layout IMGUI_API void Separator(); // horizontal line - IMGUI_API void SameLine(int column_x = 0, int spacing_w = -1); // call between widgets or groups to layout them horizontally + IMGUI_API void SameLine(float pos_x = 0.0f, float spacing_w = -1.0f); // call between widgets or groups to layout them horizontally + IMGUI_API void NewLine(); // undo a SameLine() IMGUI_API void Spacing(); // add vertical spacing - IMGUI_API void Indent(); // move content position toward the right by style.IndentSpacing pixels - IMGUI_API void Unindent(); // move content position back to the left (cancel Indent) - IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border=true); // setup number of columns. use an identifier to distinguish multiple column sets. close with Columns(1). + IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size + IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by style.IndentSpacing or indent_w if >0 + IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by style.IndentSpacing or indent_w if >0 + IMGUI_API void BeginGroup(); // lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) + IMGUI_API void EndGroup(); + IMGUI_API ImVec2 GetCursorPos(); // cursor position is relative to window position + IMGUI_API float GetCursorPosX(); // " + IMGUI_API float GetCursorPosY(); // " + IMGUI_API void SetCursorPos(const ImVec2& local_pos); // " + IMGUI_API void SetCursorPosX(float x); // " + IMGUI_API void SetCursorPosY(float y); // " + IMGUI_API ImVec2 GetCursorStartPos(); // initial cursor position + IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute screen coordinates [0..io.DisplaySize] (useful to work with ImDrawList API) + IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position in absolute screen coordinates [0..io.DisplaySize] + IMGUI_API void AlignFirstTextHeightToWidgets(); // call once if the first item on the line is a Text() item and you want to vertically lower it to match subsequent (bigger) widgets + IMGUI_API float GetTextLineHeight(); // height of font == GetWindowFontSize() + IMGUI_API float GetTextLineHeightWithSpacing(); // distance (in pixels) between 2 consecutive lines of text == GetWindowFontSize() + GetStyle().ItemSpacing.y + IMGUI_API float GetItemsLineHeightWithSpacing(); // distance (in pixels) between 2 consecutive lines of standard height widgets == GetWindowFontSize() + GetStyle().FramePadding.y*2 + GetStyle().ItemSpacing.y + + // Columns + // You can also use SameLine(pos_x) for simplified columning. The columns API is still work-in-progress and rather lacking. + IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true); // setup number of columns. use an identifier to distinguish multiple column sets. close with Columns(1). IMGUI_API void NextColumn(); // next column IMGUI_API int GetColumnIndex(); // get current column index IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetcolumnsCount() inclusive. column 0 is usually 0.0f and not resizable unless you call this IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column IMGUI_API float GetColumnWidth(int column_index = -1); // column width (== GetColumnOffset(GetColumnIndex()+1) - GetColumnOffset(GetColumnOffset()) IMGUI_API int GetColumnsCount(); // number of columns (what was passed to Columns()) - IMGUI_API ImVec2 GetCursorPos(); // cursor position is relative to window position - IMGUI_API float GetCursorPosX(); // " - IMGUI_API float GetCursorPosY(); // " - IMGUI_API void SetCursorPos(const ImVec2& pos); // " - IMGUI_API void SetCursorPosX(float x); // " - IMGUI_API void SetCursorPosY(float y); // " - IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute screen coordinates [0..io.DisplaySize] - IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position in absolute screen coordinates [0..io.DisplaySize] - IMGUI_API void AlignFirstTextHeightToWidgets(); // call once if the first item on the line is a Text() item and you want to vertically lower it to match subsequent (bigger) widgets - IMGUI_API float GetTextLineHeight(); // height of font == GetWindowFontSize() - IMGUI_API float GetTextLineHeightWithSpacing(); // spacing (in pixels) between 2 consecutive lines of text == GetWindowFontSize() + GetStyle().ItemSpacing.y // ID scopes - // If you are creating widgets in a loop you most likely want to push a unique identifier so ImGui can differentiate them - // You can also use "##extra" within your widget name to distinguish them from each others (see 'Programmer Guide') + // If you are creating widgets in a loop you most likely want to push a unique identifier so ImGui can differentiate them. + // You can also use the "##foobar" syntax within widget label to distinguish them from each others. Read "A primer on the use of labels/IDs" in the FAQ for more details. IMGUI_API void PushID(const char* str_id); // push identifier into the ID stack. IDs are hash of the *entire* stack! IMGUI_API void PushID(const char* str_id_begin, const char* str_id_end); IMGUI_API void PushID(const void* ptr_id); - IMGUI_API void PushID(const int int_id); + IMGUI_API void PushID(int int_id); IMGUI_API void PopID(); IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). useful if you want to query into ImGuiStorage yourself. otherwise rarely needed IMGUI_API ImGuiID GetID(const char* str_id_begin, const char* str_id_end); IMGUI_API ImGuiID GetID(const void* ptr_id); // Widgets - IMGUI_API void Text(const char* fmt, ...); + IMGUI_API void Text(const char* fmt, ...) IM_PRINTFARGS(1); IMGUI_API void TextV(const char* fmt, va_list args); - IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor(); + IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_PRINTFARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor(); IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args); - IMGUI_API void TextWrapped(const char* fmt, ...); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos(); + IMGUI_API void TextDisabled(const char* fmt, ...) IM_PRINTFARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor(); + IMGUI_API void TextDisabledV(const char* fmt, va_list args); + IMGUI_API void TextWrapped(const char* fmt, ...) IM_PRINTFARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize(). IMGUI_API void TextWrappedV(const char* fmt, va_list args); - IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // doesn't require null terminated string if 'text_end' is specified. no copy done to any bounded stack buffer, recommended for long chunks of text - IMGUI_API void LabelText(const char* label, const char* fmt, ...); // display text+label aligned the same way as value+label widgets + IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // doesn't require null terminated string if 'text_end' is specified. no copy done to any bounded stack buffer, recommended for long chunks of text + IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_PRINTFARGS(2); // display text+label aligned the same way as value+label widgets IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args); - IMGUI_API void Bullet(); - IMGUI_API void BulletText(const char* fmt, ...); + IMGUI_API void Bullet(); // draw a small circle and keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses + IMGUI_API void BulletText(const char* fmt, ...) IM_PRINTFARGS(1); // shortcut for Bullet()+Text() IMGUI_API void BulletTextV(const char* fmt, va_list args); - IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0,0), bool repeat_when_held = false); - IMGUI_API bool SmallButton(const char* label); + IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0,0)); // button + IMGUI_API bool SmallButton(const char* label); // button with FramePadding=(0,0) IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size); IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0)); - IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0,0,0,1), const ImVec4& tint_col = ImVec4(1,1,1,1)); // <0 frame_padding uses default frame padding settings. 0 for no padding - IMGUI_API bool CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false); + IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0,0,0,0), const ImVec4& tint_col = ImVec4(1,1,1,1)); // <0 frame_padding uses default frame padding settings. 0 for no padding IMGUI_API bool Checkbox(const char* label, bool* v); IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value); IMGUI_API bool RadioButton(const char* label, bool active); @@ -234,15 +270,41 @@ namespace ImGui IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items = -1); // separate items with \0, end item-list with \0\0 IMGUI_API bool Combo(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1); IMGUI_API bool ColorButton(const ImVec4& col, bool small_height = false, bool outline_border = true); - IMGUI_API bool ColorEdit3(const char* label, float col[3]); - IMGUI_API bool ColorEdit4(const char* label, float col[4], bool show_alpha = true); - IMGUI_API void ColorEditMode(ImGuiColorEditMode mode); - IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), size_t stride = sizeof(float)); + IMGUI_API bool ColorEdit3(const char* label, float col[3]); // Hint: 'float col[3]' function argument is same as 'float* col'. You can pass address of first element out of a contiguous set, e.g. &myvector.x + IMGUI_API bool ColorEdit4(const char* label, float col[4], bool show_alpha = true); // " + IMGUI_API void ColorEditMode(ImGuiColorEditMode mode); // FIXME-OBSOLETE: This is inconsistent with most of the API and will be obsoleted/replaced. + IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), int stride = sizeof(float)); IMGUI_API void PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0)); - IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), size_t stride = sizeof(float)); + IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), int stride = sizeof(float)); IMGUI_API void PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0)); + IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-1,0), const char* overlay = NULL); - // Widgets: Sliders (tip: ctrl+click on a slider to input text) + // Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can go off-bounds) + // For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every functions, remember than a 'float v[3]' function argument is the same as 'float* v'. You can pass address of your first element out of a contiguous set, e.g. &myvector.x + IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); // If v_min >= v_max we have no bound + IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); + IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); + IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); + IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", const char* display_format_max = NULL, float power = 1.0f); + IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); // If v_min >= v_max we have no bound + IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); + IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); + IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); + IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f", const char* display_format_max = NULL); + + // Widgets: Input with Keyboard + IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiTextEditCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0,0), ImGuiInputTextFlags flags = 0, ImGuiTextEditCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputFloat2(const char* label, float v[2], int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputFloat3(const char* label, float v[3], int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputFloat4(const char* label, float v[4], int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputInt(const char* label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags = 0); + + // Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can go off-bounds) IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); // adjust display_format to decorate the value with a prefix or a suffix. Use power!=1.0 for logarithmic sliders IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); @@ -255,128 +317,166 @@ namespace ImGui IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* display_format = "%.0f"); - // Widgets: Drags (tip: ctrl+click on a drag box to input text) - IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); // If v_min >= v_max we have no bound - IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); - IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); - IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); - IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); // If v_min >= v_max we have no bound - IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); - IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); - IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); - - // Widgets: Input - IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiTextEditCallback callback = NULL, void* user_data = NULL); - IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); - IMGUI_API bool InputFloat2(const char* label, float v[2], int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); - IMGUI_API bool InputFloat3(const char* label, float v[3], int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); - IMGUI_API bool InputFloat4(const char* label, float v[4], int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); - IMGUI_API bool InputInt(const char* label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags extra_flags = 0); - IMGUI_API bool InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags = 0); - IMGUI_API bool InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags = 0); - IMGUI_API bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags = 0); - // Widgets: Trees - IMGUI_API bool TreeNode(const char* str_label_id); // if returning 'true' the node is open and the user is responsible for calling TreePop - IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...); // " - IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...); // " - IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args); // " - IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args); // " - IMGUI_API void TreePush(const char* str_id = NULL); // already called by TreeNode(), but you can call Push/Pop yourself for layouting purpose - IMGUI_API void TreePush(const void* ptr_id = NULL); // " - IMGUI_API void TreePop(); - IMGUI_API void SetNextTreeNodeOpened(bool opened, ImGuiSetCond cond = 0); // set next tree node to be opened. + IMGUI_API bool TreeNode(const char* label); // if returning 'true' the node is open and the tree id is pushed into the id stack. user is responsible for calling TreePop(). + IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_PRINTFARGS(2); // read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet(). + IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_PRINTFARGS(2); // " + IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args); // " + IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args); // " + IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0); + IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_PRINTFARGS(3); + IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_PRINTFARGS(3); + IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args); + IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args); + IMGUI_API void TreePush(const char* str_id = NULL); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call Push/Pop yourself for layout purpose + IMGUI_API void TreePush(const void* ptr_id = NULL); // " + IMGUI_API void TreePop(); // ~ Unindent()+PopId() + IMGUI_API void TreeAdvanceToLabelPos(); // advance cursor x position by GetTreeNodeToLabelSpacing() + IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceeding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode + IMGUI_API void SetNextTreeNodeOpen(bool is_open, ImGuiSetCond cond = 0); // set next TreeNode/CollapsingHeader open state. + IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop(). + IMGUI_API bool CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags = 0); // when 'p_open' isn't NULL, display an additional small close button on upper right of the header // Widgets: Selectable / Lists - IMGUI_API bool Selectable(const char* label, bool selected = false, const ImVec2& size = ImVec2(0,0)); - IMGUI_API bool Selectable(const char* label, bool* p_selected, const ImVec2& size = ImVec2(0,0)); + IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height + IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); IMGUI_API bool ListBox(const char* label, int* current_item, const char** items, int items_count, int height_in_items = -1); IMGUI_API bool ListBox(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1); IMGUI_API bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0,0)); // use if you want to reimplement ListBox() will custom data or interactions. make sure to call ListBoxFooter() afterwards. IMGUI_API bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1); // " IMGUI_API void ListBoxFooter(); // terminate the scrolling region - // Widgets: Menus - // FIXME-WIP: v1.39 in development - IMGUI_API bool MenuItem(const char* label, const char* shortcut = NULL, bool selected = false); // bool enabled = true - IMGUI_API bool MenuItem(const char* label, const char* shortcut, bool* p_selected); // bool enabled = true - - // Widgets: Value() Helpers. Output single value in "name: value" format (tip: freely declare your own within the ImGui namespace!) + // Widgets: Value() Helpers. Output single value in "name: value" format (tip: freely declare more in your code to handle your types. you can add functions to the ImGui namespace) IMGUI_API void Value(const char* prefix, bool b); IMGUI_API void Value(const char* prefix, int v); IMGUI_API void Value(const char* prefix, unsigned int v); IMGUI_API void Value(const char* prefix, float v, const char* float_format = NULL); - IMGUI_API void Color(const char* prefix, const ImVec4& v); - IMGUI_API void Color(const char* prefix, unsigned int v); + IMGUI_API void ValueColor(const char* prefix, const ImVec4& v); + IMGUI_API void ValueColor(const char* prefix, unsigned int v); - // Logging: all text output from interface is redirected to tty/file/clipboard. Tree nodes are automatically opened. + // Tooltips + IMGUI_API void SetTooltip(const char* fmt, ...) IM_PRINTFARGS(1); // set tooltip under mouse-cursor, typically use with ImGui::IsHovered(). last call wins + IMGUI_API void SetTooltipV(const char* fmt, va_list args); + IMGUI_API void BeginTooltip(); // use to create full-featured tooltip windows that aren't just text + IMGUI_API void EndTooltip(); + + // Menus + IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar. only call EndMainMenuBar() if this returns true! + IMGUI_API void EndMainMenuBar(); + IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set). only call EndMenuBar() if this returns true! + IMGUI_API void EndMenuBar(); + IMGUI_API bool BeginMenu(const char* label, bool enabled = true); // create a sub-menu entry. only call EndMenu() if this returns true! + IMGUI_API void EndMenu(); + IMGUI_API bool MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true); // return true when activated. shortcuts are displayed for convenience but not processed by ImGui at the moment + IMGUI_API bool MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true); // return true when activated + toggle (*p_selected) if p_selected != NULL + + // Popups + IMGUI_API void OpenPopup(const char* str_id); // mark popup as open. popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). + IMGUI_API bool BeginPopup(const char* str_id); // return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() returned true! + IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags extra_flags = 0); // modal dialog (can't close them by clicking outside) + IMGUI_API bool BeginPopupContextItem(const char* str_id, int mouse_button = 1); // helper to open and begin popup when clicked on last item. read comments in .cpp! + IMGUI_API bool BeginPopupContextWindow(bool also_over_items = true, const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked on current window. + IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked in void (no window). + IMGUI_API void EndPopup(); + IMGUI_API void CloseCurrentPopup(); // close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup. + + // Logging: all text output from interface is redirected to tty/file/clipboard. By default, tree nodes are automatically opened during logging. IMGUI_API void LogToTTY(int max_depth = -1); // start logging to tty IMGUI_API void LogToFile(int max_depth = -1, const char* filename = NULL); // start logging to file IMGUI_API void LogToClipboard(int max_depth = -1); // start logging to OS clipboard IMGUI_API void LogFinish(); // stop logging (close file, etc.) IMGUI_API void LogButtons(); // helper to display buttons for logging to tty/file/clipboard - IMGUI_API void LogText(const char* fmt, ...); // pass text data straight to log (without being displayed) + IMGUI_API void LogText(const char* fmt, ...) IM_PRINTFARGS(1); // pass text data straight to log (without being displayed) + + // Clipping + IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect); + IMGUI_API void PopClipRect(); // Utilities IMGUI_API bool IsItemHovered(); // was the last item hovered by mouse? - IMGUI_API bool IsItemHoveredRect(); // was the last item hovered by mouse? even if another item is active while we are hovering this + IMGUI_API bool IsItemHoveredRect(); // was the last item hovered by mouse? even if another item is active or window is blocked by popup while we are hovering this IMGUI_API bool IsItemActive(); // was the last item active? (e.g. button being held, text field being edited- items that don't interact will always return false) - IMGUI_API bool IsAnyItemActive(); // - IMGUI_API bool IsItemVisible(); + IMGUI_API bool IsItemClicked(int mouse_button = 0); // was the last item clicked? (e.g. button/node just clicked on) + IMGUI_API bool IsItemVisible(); // was the last item visible? (aka not out of sight due to clipping/scrolling.) + IMGUI_API bool IsAnyItemHovered(); + IMGUI_API bool IsAnyItemActive(); IMGUI_API ImVec2 GetItemRectMin(); // get bounding rect of last item in screen space IMGUI_API ImVec2 GetItemRectMax(); // " IMGUI_API ImVec2 GetItemRectSize(); // " - IMGUI_API bool IsWindowFocused(); // is current window focused (differentiate child windows from each others) - IMGUI_API bool IsRootWindowFocused(); // is current root window focused + IMGUI_API void SetItemAllowOverlap(); // allow last item to be overlapped by a subsequent item. sometimes useful with invisible buttons, selectables, etc. to catch unused area. + IMGUI_API bool IsWindowHovered(); // is current window hovered and hoverable (not blocked by a popup) (differentiate child windows from each others) + IMGUI_API bool IsWindowFocused(); // is current window focused + IMGUI_API bool IsRootWindowFocused(); // is current root window focused (root = top-most parent of a child, otherwise self) IMGUI_API bool IsRootWindowOrAnyChildFocused(); // is current root window or any of its child (including current window) focused - IMGUI_API bool IsRectClipped(const ImVec2& size); // test if rectangle of given size starting from cursor pos is out of clipping region. to perform coarse clipping on user's side (as an optimization) - IMGUI_API bool IsKeyDown(int key_index); // key_index into the keys_down[512] array, imgui doesn't know the semantic of each entry - IMGUI_API bool IsKeyPressed(int key_index, bool repeat = true); // " - IMGUI_API bool IsMouseDown(int button); - IMGUI_API bool IsMouseClicked(int button, bool repeat = false); - IMGUI_API bool IsMouseDoubleClicked(int button); - IMGUI_API bool IsMouseHoveringWindow(); // is mouse hovering current window ("window" in API names always refer to current window) - IMGUI_API bool IsMouseHoveringAnyWindow(); // is mouse hovering any active imgui window - IMGUI_API bool IsMouseHoveringRect(const ImVec2& rect_min, const ImVec2& rect_max);// is mouse hovering given bounding rect - IMGUI_API bool IsMouseDragging(int button = 0, float lock_threshold = -1.0f); // is mouse dragging. if lock_threshold < -1.0f uses io.MouseDraggingThreshold + IMGUI_API bool IsRootWindowOrAnyChildHovered(); // is current root window or any of its child (including current window) hovered and hoverable (not blocked by a popup) + IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle of given size starting from cursor pos is visible (not clipped). to perform coarse clipping on user's side (as an optimization) IMGUI_API bool IsPosHoveringAnyWindow(const ImVec2& pos); // is given position hovering any active imgui window - IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls - IMGUI_API ImVec2 GetMouseDragDelta(int button = 0, float lock_threshold = -1.0f); // dragging amount since clicking, also see: GetItemActiveDragDelta(). if lock_threshold < -1.0f uses io.MouseDraggingThreshold - IMGUI_API void ResetMouseDragDelta(int button = 0); - IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired cursor type, reset in ImGui::NewFrame(), this updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you - IMGUI_API void SetMouseCursor(ImGuiMouseCursor type); // set desired cursor type IMGUI_API float GetTime(); IMGUI_API int GetFrameCount(); IMGUI_API const char* GetStyleColName(ImGuiCol idx); IMGUI_API ImVec2 CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge = false, float outward = +0.0f); // utility to find the closest point the last item bounding rectangle edge. useful to visually link items IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f); - IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // helper to manually clip large list of items. see comments in implementation + IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // calculate coarse clipping for large list of evenly sized items. Prefer using the ImGuiListClipper higher-level helper if you can. - IMGUI_API void BeginChildFrame(ImGuiID id, const ImVec2& size); // helper to create a child window / scrolling region that looks like a normal widget frame + IMGUI_API bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags = 0); // helper to create a child window / scrolling region that looks like a normal widget frame IMGUI_API void EndChildFrame(); + IMGUI_API ImVec4 ColorConvertU32ToFloat4(ImU32 in); IMGUI_API ImU32 ColorConvertFloat4ToU32(const ImVec4& in); IMGUI_API void ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v); IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b); - // Proxy functions to access the MemAllocFn/MemFreeFn pointers in ImGui::GetIO() + // Inputs + IMGUI_API int GetKeyIndex(ImGuiKey key); // map ImGuiKey_* values into user's key index. == io.KeyMap[key] + IMGUI_API bool IsKeyDown(int key_index); // key_index into the keys_down[] array, imgui doesn't know the semantic of each entry, uses your own indices! + IMGUI_API bool IsKeyPressed(int key_index, bool repeat = true); // uses user's key indices as stored in the keys_down[] array. if repeat=true. uses io.KeyRepeatDelay / KeyRepeatRate + IMGUI_API bool IsKeyReleased(int key_index); // " + IMGUI_API bool IsMouseDown(int button); // is mouse button held + IMGUI_API bool IsMouseClicked(int button, bool repeat = false); // did mouse button clicked (went from !Down to Down) + IMGUI_API bool IsMouseDoubleClicked(int button); // did mouse button double-clicked. a double-click returns false in IsMouseClicked(). uses io.MouseDoubleClickTime. + IMGUI_API bool IsMouseReleased(int button); // did mouse button released (went from Down to !Down) + IMGUI_API bool IsMouseHoveringWindow(); // is mouse hovering current window ("window" in API names always refer to current window). disregarding of any consideration of being blocked by a popup. (unlike IsWindowHovered() this will return true even if the window is blocked because of a popup) + IMGUI_API bool IsMouseHoveringAnyWindow(); // is mouse hovering any visible window + IMGUI_API bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true); // is mouse hovering given bounding rect (in screen space). clipped by current clipping settings. disregarding of consideration of focus/window ordering/blocked by a popup. + IMGUI_API bool IsMouseDragging(int button = 0, float lock_threshold = -1.0f); // is mouse dragging. if lock_threshold < -1.0f uses io.MouseDraggingThreshold + IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls + IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve backup of mouse positioning at the time of opening popup we have BeginPopup() into + IMGUI_API ImVec2 GetMouseDragDelta(int button = 0, float lock_threshold = -1.0f); // dragging amount since clicking. if lock_threshold < -1.0f uses io.MouseDraggingThreshold + IMGUI_API void ResetMouseDragDelta(int button = 0); // + IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired cursor type, reset in ImGui::NewFrame(), this updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you + IMGUI_API void SetMouseCursor(ImGuiMouseCursor type); // set desired cursor type + IMGUI_API void CaptureKeyboardFromApp(bool capture = true); // manually override io.WantCaptureKeyboard flag next frame (said flag is entirely left for your application handle). e.g. force capture keyboard when your widget is being hovered. + IMGUI_API void CaptureMouseFromApp(bool capture = true); // manually override io.WantCaptureMouse flag next frame (said flag is entirely left for your application handle). + + // Helpers functions to access functions pointers in ImGui::GetIO() IMGUI_API void* MemAlloc(size_t sz); IMGUI_API void MemFree(void* ptr); + IMGUI_API const char* GetClipboardText(); + IMGUI_API void SetClipboardText(const char* text); - // Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself + // Internal context access - if you want to use multiple context, share context between modules (e.g. DLL). There is a default context created and active by default. + // All contexts share a same ImFontAtlas by default. If you want different font atlas, you can new() them and overwrite the GetIO().Fonts variable of an ImGui context. IMGUI_API const char* GetVersion(); - IMGUI_API void* GetInternalState(); - IMGUI_API size_t GetInternalStateSize(); - IMGUI_API void SetInternalState(void* state, bool construct = false); + IMGUI_API ImGuiContext* CreateContext(void* (*malloc_fn)(size_t) = NULL, void (*free_fn)(void*) = NULL); + IMGUI_API void DestroyContext(ImGuiContext* ctx); + IMGUI_API ImGuiContext* GetCurrentContext(); + IMGUI_API void SetCurrentContext(ImGuiContext* ctx); // Obsolete (will be removed) - IMGUI_API void GetDefaultFontData(const void** fnt_data, unsigned int* fnt_size, const void** png_data, unsigned int* png_size); // OBSOLETE - static inline void OpenNextNode(bool open) { ImGui::SetNextTreeNodeOpened(open, 0); } // OBSOLETE - static inline bool GetWindowIsFocused() { return ImGui::IsWindowFocused(); } // OBSOLETE - static inline ImVec2 GetItemBoxMin() { return GetItemRectMin(); } // OBSOLETE - static inline ImVec2 GetItemBoxMax() { return GetItemRectMax(); } // OBSOLETE - static inline bool IsClipped(const ImVec2& size) { return IsRectClipped(size); } // OBSOLETE - static inline bool IsMouseHoveringBox(const ImVec2& rect_min, const ImVec2& rect_max) { return IsMouseHoveringRect(rect_min, rect_max); } // OBSOLETE +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + static inline bool CollapsingHeader(const char* label, const char* str_id, bool framed = true, bool default_open = false) { (void)str_id; (void)framed; ImGuiTreeNodeFlags default_open_flags = 1<<5; return CollapsingHeader(label, (default_open ? default_open_flags : 0)); } // OBSOLETE 1.49+ + static inline ImFont* GetWindowFont() { return GetFont(); } // OBSOLETE 1.48+ + static inline float GetWindowFontSize() { return GetFontSize(); } // OBSOLETE 1.48+ + static inline void OpenNextNode(bool open) { ImGui::SetNextTreeNodeOpen(open, 0); } // OBSOLETE 1.34+ + static inline bool GetWindowIsFocused() { return ImGui::IsWindowFocused(); } // OBSOLETE 1.36+ + static inline bool GetWindowCollapsed() { return ImGui::IsWindowCollapsed(); } // OBSOLETE 1.39+ + static inline ImVec2 GetItemBoxMin() { return GetItemRectMin(); } // OBSOLETE 1.36+ + static inline ImVec2 GetItemBoxMax() { return GetItemRectMax(); } // OBSOLETE 1.36+ + static inline bool IsClipped(const ImVec2& size) { return !IsRectVisible(size); } // OBSOLETE 1.38+ + static inline bool IsRectClipped(const ImVec2& size) { return !IsRectVisible(size); } // OBSOLETE 1.39+ + static inline bool IsMouseHoveringBox(const ImVec2& rect_min, const ImVec2& rect_max) { return IsMouseHoveringRect(rect_min, rect_max); } // OBSOLETE 1.36+ + static inline void SetScrollPosHere() { SetScrollHere(); } // OBSOLETE 1.42+ +#endif } // namespace ImGui @@ -387,19 +487,29 @@ enum ImGuiWindowFlags_ ImGuiWindowFlags_NoTitleBar = 1 << 0, // Disable title-bar ImGuiWindowFlags_NoResize = 1 << 1, // Disable user resizing with the lower-right grip ImGuiWindowFlags_NoMove = 1 << 2, // Disable user moving the window - ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbar (window can still scroll with mouse or programatically) - ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user scrolling with mouse wheel + ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbars (window can still scroll with mouse or programatically) + ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user vertically scrolling with mouse wheel ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame ImGuiWindowFlags_ShowBorders = 1 << 7, // Show borders around windows and items ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file + ImGuiWindowFlags_NoInputs = 1 << 9, // Disable catching mouse or keyboard inputs + ImGuiWindowFlags_MenuBar = 1 << 10, // Has a menu-bar + ImGuiWindowFlags_HorizontalScrollbar = 1 << 11, // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. + ImGuiWindowFlags_NoFocusOnAppearing = 1 << 12, // Disable taking focus when transitioning from hidden to visible state + ImGuiWindowFlags_NoBringToFrontOnFocus = 1 << 13, // Disable bringing window to front when taking focus (e.g. clicking on it or programatically giving it focus) + ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14, // Always show vertical scrollbar (even if ContentSize.y < Size.y) + ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15, // Always show horizontal scrollbar (even if ContentSize.x < Size.x) + ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 16, // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient) // [Internal] - ImGuiWindowFlags_ChildWindow = 1 << 9, // For internal use by BeginChild() - ImGuiWindowFlags_ChildWindowAutoFitX = 1 << 10, // For internal use by BeginChild() - ImGuiWindowFlags_ChildWindowAutoFitY = 1 << 11, // For internal use by BeginChild() - ImGuiWindowFlags_ComboBox = 1 << 12, // For internal use by ComboBox() - ImGuiWindowFlags_Tooltip = 1 << 13, // For internal use by BeginTooltip() - ImGuiWindowFlags_Popup = 1 << 14 // For internal use by BeginPopup() + ImGuiWindowFlags_ChildWindow = 1 << 20, // Don't use! For internal use by BeginChild() + ImGuiWindowFlags_ChildWindowAutoFitX = 1 << 21, // Don't use! For internal use by BeginChild() + ImGuiWindowFlags_ChildWindowAutoFitY = 1 << 22, // Don't use! For internal use by BeginChild() + ImGuiWindowFlags_ComboBox = 1 << 23, // Don't use! For internal use by ComboBox() + ImGuiWindowFlags_Tooltip = 1 << 24, // Don't use! For internal use by BeginTooltip() + ImGuiWindowFlags_Popup = 1 << 25, // Don't use! For internal use by BeginPopup() + ImGuiWindowFlags_Modal = 1 << 26, // Don't use! For internal use by BeginPopupModal() + ImGuiWindowFlags_ChildMenu = 1 << 27 // Don't use! For internal use by BeginMenu() }; // Flags for ImGui::InputText() @@ -414,30 +524,67 @@ enum ImGuiInputTextFlags_ ImGuiInputTextFlags_EnterReturnsTrue = 1 << 5, // Return 'true' when Enter is pressed (as opposed to when the value was modified) ImGuiInputTextFlags_CallbackCompletion = 1 << 6, // Call user function on pressing TAB (for completion handling) ImGuiInputTextFlags_CallbackHistory = 1 << 7, // Call user function on pressing Up/Down arrows (for history handling) - ImGuiInputTextFlags_CallbackAlways = 1 << 8, // Call user function every time - ImGuiInputTextFlags_CallbackCharFilter = 1 << 9 // Call user function to filter character. Modify data->EventChar to replace/filter input, or return 1 to discard character. + ImGuiInputTextFlags_CallbackAlways = 1 << 8, // Call user function every time. User code may query cursor position, modify text buffer. + ImGuiInputTextFlags_CallbackCharFilter = 1 << 9, // Call user function to filter character. Modify data->EventChar to replace/filter input, or return 1 to discard character. + ImGuiInputTextFlags_AllowTabInput = 1 << 10, // Pressing TAB input a '\t' character into the text field + ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 11, // In multi-line mode, allow exiting edition by pressing Enter. Ctrl+Enter to add new line (by default adds new lines with Enter). + ImGuiInputTextFlags_NoHorizontalScroll = 1 << 12, // Disable following the cursor horizontally + ImGuiInputTextFlags_AlwaysInsertMode = 1 << 13, // Insert mode + ImGuiInputTextFlags_ReadOnly = 1 << 14, // Read-only mode + ImGuiInputTextFlags_Password = 1 << 15, // Password mode, display all characters as '*' + // [Internal] + ImGuiInputTextFlags_Multiline = 1 << 20 // For internal use by InputTextMultiline() +}; + +// Flags for ImGui::TreeNodeEx(), ImGui::CollapsingHeader*() +enum ImGuiTreeNodeFlags_ +{ + ImGuiTreeNodeFlags_Selected = 1 << 0, // Draw as selected + ImGuiTreeNodeFlags_Framed = 1 << 1, // Full colored frame (e.g. for CollapsingHeader) + ImGuiTreeNodeFlags_AllowOverlapMode = 1 << 2, // Hit testing to allow subsequent widgets to overlap this one + ImGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3, // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack + ImGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4, // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes) + ImGuiTreeNodeFlags_DefaultOpen = 1 << 5, // Default node to be open + ImGuiTreeNodeFlags_OpenOnDoubleClick = 1 << 6, // Need double-click to open node + ImGuiTreeNodeFlags_OpenOnArrow = 1 << 7, // Only open when clicking on the arrow part. If ImGuiTreeNodeFlags_OpenOnDoubleClick is also set, single-click arrow or double-click all box to open. + ImGuiTreeNodeFlags_Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes). + ImGuiTreeNodeFlags_Bullet = 1 << 9, // Display a bullet instead of arrow + //ImGuITreeNodeFlags_SpanAllAvailWidth = 1 << 10, // FIXME: TODO: Extend hit box horizontally even if not framed + //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 11, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible + ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoAutoOpenOnLog +}; + +// Flags for ImGui::Selectable() +enum ImGuiSelectableFlags_ +{ + // Default: 0 + ImGuiSelectableFlags_DontClosePopups = 1 << 0, // Clicking this don't close parent popup window + ImGuiSelectableFlags_SpanAllColumns = 1 << 1, // Selectable frame can span all columns (text will still fit in current column) + ImGuiSelectableFlags_AllowDoubleClick = 1 << 2 // Generate press events on double clicks too }; // User fill ImGuiIO.KeyMap[] array with indices into the ImGuiIO.KeysDown[512] array enum ImGuiKey_ { - ImGuiKey_Tab, - ImGuiKey_LeftArrow, - ImGuiKey_RightArrow, - ImGuiKey_UpArrow, - ImGuiKey_DownArrow, - ImGuiKey_Home, - ImGuiKey_End, - ImGuiKey_Delete, - ImGuiKey_Backspace, - ImGuiKey_Enter, - ImGuiKey_Escape, - ImGuiKey_A, // for CTRL+A: select all - ImGuiKey_C, // for CTRL+C: copy - ImGuiKey_V, // for CTRL+V: paste - ImGuiKey_X, // for CTRL+X: cut - ImGuiKey_Y, // for CTRL+Y: redo - ImGuiKey_Z, // for CTRL+Z: undo + ImGuiKey_Tab, // for tabbing through fields + ImGuiKey_LeftArrow, // for text edit + ImGuiKey_RightArrow,// for text edit + ImGuiKey_UpArrow, // for text edit + ImGuiKey_DownArrow, // for text edit + ImGuiKey_PageUp, + ImGuiKey_PageDown, + ImGuiKey_Home, // for text edit + ImGuiKey_End, // for text edit + ImGuiKey_Delete, // for text edit + ImGuiKey_Backspace, // for text edit + ImGuiKey_Enter, // for text edit + ImGuiKey_Escape, // for text edit + ImGuiKey_A, // for text edit CTRL+A: select all + ImGuiKey_C, // for text edit CTRL+C: copy + ImGuiKey_V, // for text edit CTRL+V: paste + ImGuiKey_X, // for text edit CTRL+X: cut + ImGuiKey_Y, // for text edit CTRL+Y: redo + ImGuiKey_Z, // for text edit CTRL+Z: undo ImGuiKey_COUNT }; @@ -445,8 +592,10 @@ enum ImGuiKey_ enum ImGuiCol_ { ImGuiCol_Text, - ImGuiCol_WindowBg, - ImGuiCol_ChildWindowBg, + ImGuiCol_TextDisabled, + ImGuiCol_WindowBg, // Background of normal windows + ImGuiCol_ChildWindowBg, // Background of child windows + ImGuiCol_PopupBg, // Background of popups, menus, tooltips windows ImGuiCol_Border, ImGuiCol_BorderShadow, ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input @@ -454,6 +603,8 @@ enum ImGuiCol_ ImGuiCol_FrameBgActive, ImGuiCol_TitleBg, ImGuiCol_TitleBgCollapsed, + ImGuiCol_TitleBgActive, + ImGuiCol_MenuBarBg, ImGuiCol_ScrollbarBg, ImGuiCol_ScrollbarGrab, ImGuiCol_ScrollbarGrabHovered, @@ -482,7 +633,7 @@ enum ImGuiCol_ ImGuiCol_PlotHistogram, ImGuiCol_PlotHistogramHovered, ImGuiCol_TextSelectedBg, - ImGuiCol_TooltipBg, + ImGuiCol_ModalWindowDarkening, // darken entire screen when a modal window is active ImGuiCol_COUNT }; @@ -493,6 +644,7 @@ enum ImGuiStyleVar_ ImGuiStyleVar_Alpha, // float ImGuiStyleVar_WindowPadding, // ImVec2 ImGuiStyleVar_WindowRounding, // float + ImGuiStyleVar_WindowMinSize, // ImVec2 ImGuiStyleVar_ChildWindowRounding, // float ImGuiStyleVar_FramePadding, // ImVec2 ImGuiStyleVar_FrameRounding, // float @@ -507,10 +659,13 @@ enum ImGuiAlign_ ImGuiAlign_Left = 1 << 0, ImGuiAlign_Center = 1 << 1, ImGuiAlign_Right = 1 << 2, - ImGuiAlign_Default = ImGuiAlign_Left, + ImGuiAlign_Top = 1 << 3, + ImGuiAlign_VCenter = 1 << 4, + ImGuiAlign_Default = ImGuiAlign_Left | ImGuiAlign_Top }; // Enumeration for ColorEditMode() +// FIXME-OBSOLETE: Will be replaced by future color/picker api enum ImGuiColorEditMode_ { ImGuiColorEditMode_UserSelect = -2, @@ -556,20 +711,23 @@ struct ImGuiStyle ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! - float WindowFillAlphaDefault; // Default alpha of window background, if not specified in ImGui::Begin() - float IndentSpacing; // Horizontal indentation when e.g. entering a tree node + float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). float ColumnsMinSpacing; // Minimum horizontal spacing between two columns - float ScrollbarWidth; // Width of the vertical scrollbar + float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar float ScrollbarRounding; // Radius of grab corners for scrollbar float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar + float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. ImVec2 DisplayWindowPadding; // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows. ImVec2 DisplaySafeAreaPadding; // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. + bool AntiAliasedLines; // Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU. + bool AntiAliasedShapes; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) + float CurveTessellationTol; // Tessellation tolerance. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. ImVec4 Colors[ImGuiCol_COUNT]; IMGUI_API ImGuiStyle(); }; -// This is where your app communicate with ImGui. Call ImGui::GetIO() to access. +// This is where your app communicate with ImGui. Access via ImGui::GetIO(). // Read 'Programmer guide' section in .cpp file for general usage. struct ImGuiIO { @@ -586,21 +744,31 @@ struct ImGuiIO float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels. float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging int KeyMap[ImGuiKey_COUNT]; // // Map of indices into the KeysDown[512] entries array + float KeyRepeatDelay; // = 0.250f // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.). + float KeyRepeatRate; // = 0.020f // When holding a key/button, rate at which it repeats, in seconds. void* UserData; // = NULL // Store your own data for retrieval by callbacks. ImFontAtlas* Fonts; // // Load and assemble one or more fonts into a single tightly packed texture. Output to Fonts array. float FontGlobalScale; // = 1.0f // Global scale all fonts bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel. + ImVec2 DisplayFramebufferScale; // = (1.0f,1.0f) // For retina display or other situations where window coordinates are different from framebuffer coordinates. User storage only, presently not used by ImGui. ImVec2 DisplayVisibleMin; // (0.0f,0.0f) // If you use DisplaySize as a virtual space larger than your screen, set DisplayVisibleMin/Max to the visible area. ImVec2 DisplayVisibleMax; // (0.0f,0.0f) // If the values are the same, we defaults to Min=(0.0f) and Max=DisplaySize + // Advanced/subtle behaviors + bool WordMovementUsesAltKey; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl + bool ShortcutsUseSuperKey; // = defined(__APPLE__) // OS X style: Shortcuts using Cmd/Super instead of Ctrl + bool DoubleClickSelectsWord; // = defined(__APPLE__) // OS X style: Double click selects by word instead of selecting whole text + bool MultiSelectUsesSuperKey; // = defined(__APPLE__) // OS X style: Multi-selection in lists uses Cmd/Super instead of Ctrl [unused yet] + //------------------------------------------------------------------ // User Functions //------------------------------------------------------------------ - // REQUIRED: rendering function. - // See example code if you are unsure of how to implement this. - void (*RenderDrawListsFn)(ImDrawList** const draw_lists, int count); + // Rendering function, will be called in Render(). + // Alternatively you can keep this to NULL and call GetDrawData() after Render() to get the same pointer. + // See example applications if you are unsure of how to implement this. + void (*RenderDrawListsFn)(ImDrawData* data); // Optional: access OS clipboard // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) @@ -622,17 +790,20 @@ struct ImGuiIO //------------------------------------------------------------------ ImVec2 MousePos; // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) - bool MouseDown[5]; // Mouse buttons. ImGui itself only uses button 0 (left button). Others buttons allows to track if mouse is being used by your application + available to user as a convenience via IsMouse** API. - float MouseWheel; // Mouse wheel: 1 unit scrolls about 5 lines text. + bool MouseDown[5]; // Mouse buttons: left, right, middle + extras. ImGui itself mostly only uses left button (BeginPopupContext** are using right button). Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. + float MouseWheel; // Mouse wheel: 1 unit scrolls about 5 lines text. bool MouseDrawCursor; // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). bool KeyCtrl; // Keyboard modifier pressed: Control bool KeyShift; // Keyboard modifier pressed: Shift bool KeyAlt; // Keyboard modifier pressed: Alt + bool KeySuper; // Keyboard modifier pressed: Cmd/Super/Windows bool KeysDown[512]; // Keyboard keys that are pressed (in whatever storage order you naturally have access to keyboard data) ImWchar InputCharacters[16+1]; // List of characters input (translated by user from keypress+keyboard state). Fill using AddInputCharacter() helper. - // Function - IMGUI_API void AddInputCharacter(ImWchar c); // Helper to add a new character into InputCharacters[] + // Functions + IMGUI_API void AddInputCharacter(ImWchar c); // Helper to add a new character into InputCharacters[] + IMGUI_API void AddInputCharactersUTF8(const char* utf8_chars); // Helper to add new characters into InputCharacters[] from an UTF-8 string + inline void ClearInputCharacters() { InputCharacters[0] = 0; } // Helper to clear the text input buffer //------------------------------------------------------------------ // Output - Retrieve after calling NewFrame(), you can use them to discard inputs or hide them from the rest of your application @@ -640,8 +811,11 @@ struct ImGuiIO bool WantCaptureMouse; // Mouse is hovering a window or widget is active (= ImGui will use your mouse input) bool WantCaptureKeyboard; // Widget is active (= ImGui will use your keyboard input) + bool WantTextInput; // Some text input widget is active, which will read input characters from the InputCharacters array. float Framerate; // Framerate estimation, in frame per second. Rolling average estimation based on IO.DeltaTime over 120 frames - int MetricsRenderVertices; // Vertices processed during last call to Render() + int MetricsAllocs; // Number of active memory allocations + int MetricsRenderVertices; // Vertices output during last call to Render() + int MetricsRenderIndices; // Indices output during last call to Render() = number of triangles * 3 int MetricsActiveWindows; // Number of visible windows (exclude child windows) //------------------------------------------------------------------ @@ -654,10 +828,13 @@ struct ImGuiIO ImVec2 MouseClickedPos[5]; // Position at time of clicking float MouseClickedTime[5]; // Time of last click (used to figure out double-click) bool MouseDoubleClicked[5]; // Has mouse button been double-clicked? + bool MouseReleased[5]; // Mouse button went from Down to !Down bool MouseDownOwned[5]; // Track if button was clicked inside a window. We don't request mouse capture from the application if click started outside ImGui bounds. - float MouseDownTime[5]; // Time the mouse button has been down + float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked) + float MouseDownDurationPrev[5]; // Previous time the mouse button has been down float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the click point - float KeysDownTime[512]; // Time the keyboard key has been down + float KeysDownDuration[512]; // Duration the keyboard key has been down (0.0f == just pressed) + float KeysDownDurationPrev[512]; // Previous duration the key has been down IMGUI_API ImGuiIO(); }; @@ -666,19 +843,16 @@ struct ImGuiIO // Helpers //----------------------------------------------------------------------------- -// Lightweight std::vector<> like class to avoid dragging dependencies (also: windows implementation of STL with debug enabled is absurdly slow, so let's bypass it so our code runs fast in debug). -// Use '#define ImVector std::vector' if you want to use the STL type or your own type. +// Lightweight std::vector<> like class to avoid dragging dependencies (also: windows implementation of STL with debug enabled is absurdly slow, so let's bypass it so our code runs fast in debug). // Our implementation does NOT call c++ constructors because we don't use them in ImGui. Don't use this class as a straight std::vector replacement in your code! -#ifndef ImVector template class ImVector { -protected: - size_t Size; - size_t Capacity; +public: + int Size; + int Capacity; T* Data; -public: typedef T value_type; typedef value_type* iterator; typedef const value_type* const_iterator; @@ -687,13 +861,11 @@ public: ~ImVector() { if (Data) ImGui::MemFree(Data); } inline bool empty() const { return Size == 0; } - inline size_t size() const { return Size; } - inline size_t capacity() const { return Capacity; } + inline int size() const { return Size; } + inline int capacity() const { return Capacity; } - inline value_type& at(size_t i) { IM_ASSERT(i < Size); return Data[i]; } - inline const value_type& at(size_t i) const { IM_ASSERT(i < Size); return Data[i]; } - inline value_type& operator[](size_t i) { IM_ASSERT(i < Size); return Data[i]; } - inline const value_type& operator[](size_t i) const { IM_ASSERT(i < Size); return Data[i]; } + inline value_type& operator[](int i) { IM_ASSERT(i < Size); return Data[i]; } + inline const value_type& operator[](int i) const { IM_ASSERT(i < Size); return Data[i]; } inline void clear() { if (Data) { Size = Capacity = 0; ImGui::MemFree(Data); Data = NULL; } } inline iterator begin() { return Data; } @@ -704,28 +876,29 @@ public: inline const value_type& front() const { IM_ASSERT(Size > 0); return Data[0]; } inline value_type& back() { IM_ASSERT(Size > 0); return Data[Size-1]; } inline const value_type& back() const { IM_ASSERT(Size > 0); return Data[Size-1]; } - inline void swap(ImVector& rhs) { const size_t rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; const size_t rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; value_type* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; } + inline void swap(ImVector& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; value_type* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; } - inline void resize(size_t new_size) { if (new_size > Capacity) reserve(new_size); Size = new_size; } - inline void reserve(size_t new_capacity) - { + inline int _grow_capacity(int new_size) { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > new_size ? new_capacity : new_size; } + + inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; } + inline void reserve(int new_capacity) + { if (new_capacity <= Capacity) return; - T* new_data = (value_type*)ImGui::MemAlloc(new_capacity * sizeof(value_type)); - memcpy(new_data, Data, Size * sizeof(value_type)); + T* new_data = (value_type*)ImGui::MemAlloc((size_t)new_capacity * sizeof(value_type)); + memcpy(new_data, Data, (size_t)Size * sizeof(value_type)); ImGui::MemFree(Data); Data = new_data; - Capacity = new_capacity; + Capacity = new_capacity; } - inline void push_back(const value_type& v) { if (Size == Capacity) reserve(Capacity ? Capacity * 2 : 4); Data[Size++] = v; } + inline void push_back(const value_type& v) { if (Size == Capacity) reserve(_grow_capacity(Size+1)); Data[Size++] = v; } inline void pop_back() { IM_ASSERT(Size > 0); Size--; } - inline iterator erase(const_iterator it) { IM_ASSERT(it >= begin() && it < end()); const ptrdiff_t off = it - begin(); memmove(Data + off, Data + off + 1, (Size - (size_t)off - 1) * sizeof(value_type)); Size--; return Data + off; } - inline iterator insert(const_iterator it, const value_type& v) { IM_ASSERT(it >= begin() && it <= end()); const ptrdiff_t off = it - begin(); if (Size == Capacity) reserve(Capacity ? Capacity * 2 : 4); if (off < (int)Size) memmove(Data + off + 1, Data + off, (Size - (size_t)off) * sizeof(value_type)); Data[off] = v; Size++; return Data + off; } + inline iterator erase(const_iterator it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(value_type)); Size--; return Data + off; } + inline iterator insert(const_iterator it, const value_type& v) { IM_ASSERT(it >= Data && it <= Data+Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(Capacity ? Capacity * 2 : 4); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(value_type)); Data[off] = v; Size++; return Data + off; } }; -#endif // #ifndef ImVector -// Helper: execute a block of code once a frame only +// Helper: execute a block of code at maximum once a frame // Convenient if you want to quickly create an UI within deep-nested code that runs multiple times every frame. // Usage: // IMGUI_ONCE_UPON_A_FRAME @@ -738,7 +911,7 @@ struct ImGuiOnceUponAFrame { ImGuiOnceUponAFrame() { RefFrame = -1; } mutable int RefFrame; - operator bool() const { const int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; } + operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; } }; // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" @@ -755,8 +928,8 @@ struct ImGuiTextFilter const char* end() const { return e; } bool empty() const { return b == e; } char front() const { return *b; } - static bool isblank(char c) { return c == ' ' || c == '\t'; } - void trim_blanks() { while (b < e && isblank(*b)) b++; while (e > b && isblank(*(e-1))) e--; } + static bool is_blank(char c) { return c == ' ' || c == '\t'; } + void trim_blanks() { while (b < e && is_blank(*b)) b++; while (e > b && is_blank(*(e-1))) e--; } IMGUI_API void split(char separator, ImVector& out); }; @@ -765,11 +938,12 @@ struct ImGuiTextFilter int CountGrep; ImGuiTextFilter(const char* default_filter = ""); - void Clear() { InputBuf[0] = 0; Build(); } - void Draw(const char* label = "Filter (inc,-exc)", float width = -1.0f); // Helper calling InputText+Build - bool PassFilter(const char* val) const; - bool IsActive() const { return !Filters.empty(); } - IMGUI_API void Build(); + ~ImGuiTextFilter() {} + void Clear() { InputBuf[0] = 0; Build(); } + bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build + bool PassFilter(const char* text, const char* text_end = NULL) const; + bool IsActive() const { return !Filters.empty(); } + IMGUI_API void Build(); }; // Helper: Text buffer for logging/accumulating text @@ -778,16 +952,18 @@ struct ImGuiTextBuffer ImVector Buf; ImGuiTextBuffer() { Buf.push_back(0); } + inline char operator[](int i) { return Buf.Data[i]; } const char* begin() const { return &Buf.front(); } const char* end() const { return &Buf.back(); } // Buf is zero-terminated, so end() will point on the zero-terminator - size_t size() const { return Buf.size()-1; } - bool empty() { return size() >= 1; } + int size() const { return Buf.Size - 1; } + bool empty() { return Buf.Size <= 1; } void clear() { Buf.clear(); Buf.push_back(0); } - IMGUI_API void append(const char* fmt, ...); + const char* c_str() const { return Buf.Data; } + IMGUI_API void append(const char* fmt, ...) IM_PRINTFARGS(2); IMGUI_API void appendv(const char* fmt, va_list args); }; -// Helper: Key->value storage +// Helper: Simple Key->value storage // - Store collapse state for a tree (Int 0/1) // - Store color edit options (Int using values in ImGuiColorEditMode enum). // - Custom user storage for temporary values. @@ -795,107 +971,169 @@ struct ImGuiTextBuffer // Declare your own storage if: // - You want to manipulate the open/close state of a particular sub-tree in your interface (tree node uses Int 0/1 to store their state). // - You want to store custom debug data easily without adding or editing structures in your code. +// Types are NOT stored, so it is up to you to make sure your Key don't collide with different types. struct ImGuiStorage { - struct Pair - { - ImGuiID key; - union { int val_i; float val_f; void* val_p; }; - Pair(ImGuiID _key, int _val_i) { key = _key; val_i = _val_i; } - Pair(ImGuiID _key, float _val_f) { key = _key; val_f = _val_f; } - Pair(ImGuiID _key, void* _val_p) { key = _key; val_p = _val_p; } + struct Pair + { + ImGuiID key; + union { int val_i; float val_f; void* val_p; }; + Pair(ImGuiID _key, int _val_i) { key = _key; val_i = _val_i; } + Pair(ImGuiID _key, float _val_f) { key = _key; val_f = _val_f; } + Pair(ImGuiID _key, void* _val_p) { key = _key; val_p = _val_p; } }; - ImVector Data; + ImVector Data; // - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N) // - Set***() functions find pair, insertion on demand if missing. - // - Sorted insertion is costly but should amortize. A typical frame shouldn't need to insert any new pair. - IMGUI_API void Clear(); - IMGUI_API int GetInt(ImGuiID key, int default_val = 0) const; - IMGUI_API void SetInt(ImGuiID key, int val); - IMGUI_API float GetFloat(ImGuiID key, float default_val = 0.0f) const; - IMGUI_API void SetFloat(ImGuiID key, float val); - IMGUI_API void* GetVoidPtr(ImGuiID key) const; // default_val is NULL - IMGUI_API void SetVoidPtr(ImGuiID key, void* val); + // - Sorted insertion is costly, paid once. A typical frame shouldn't need to insert any new pair. + IMGUI_API void Clear(); + IMGUI_API int GetInt(ImGuiID key, int default_val = 0) const; + IMGUI_API void SetInt(ImGuiID key, int val); + IMGUI_API bool GetBool(ImGuiID key, bool default_val = false) const; + IMGUI_API void SetBool(ImGuiID key, bool val); + IMGUI_API float GetFloat(ImGuiID key, float default_val = 0.0f) const; + IMGUI_API void SetFloat(ImGuiID key, float val); + IMGUI_API void* GetVoidPtr(ImGuiID key) const; // default_val is NULL + IMGUI_API void SetVoidPtr(ImGuiID key, void* val); - // - Get***Ref() functions finds pair, insert on demand if missing, return pointer. Useful if you intend to do Get+Set. + // - Get***Ref() functions finds pair, insert on demand if missing, return pointer. Useful if you intend to do Get+Set. // - References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. // - A typical use case where this is convenient: // float* pvar = ImGui::GetFloatRef(key); ImGui::SliderFloat("var", pvar, 0, 100.0f); some_var += *pvar; // - You can also use this to quickly create temporary editable values during a session of using Edit&Continue, without restarting your application. - IMGUI_API int* GetIntRef(ImGuiID key, int default_val = 0); - IMGUI_API float* GetFloatRef(ImGuiID key, float default_val = 0); - IMGUI_API void** GetVoidPtrRef(ImGuiID key, void* default_val = NULL); + IMGUI_API int* GetIntRef(ImGuiID key, int default_val = 0); + IMGUI_API bool* GetBoolRef(ImGuiID key, bool default_val = false); + IMGUI_API float* GetFloatRef(ImGuiID key, float default_val = 0.0f); + IMGUI_API void** GetVoidPtrRef(ImGuiID key, void* default_val = NULL); // Use on your own storage if you know only integer are being stored (open/close all tree nodes) - IMGUI_API void SetAllInt(int val); + IMGUI_API void SetAllInt(int val); }; -// Shared state of InputText(), passed to callback when a ImGuiInputTextFlags_Callback* flag is used. +// Shared state of InputText(), passed to callback when a ImGuiInputTextFlags_Callback* flag is used and the corresponding callback is triggered. struct ImGuiTextEditCallbackData { ImGuiInputTextFlags EventFlag; // One of ImGuiInputTextFlags_Callback* // Read-only ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only void* UserData; // What user passed to InputText() // Read-only + bool ReadOnly; // Read-only mode // Read-only // CharFilter event: ImWchar EventChar; // Character input // Read-write (replace character or set to zero) // Completion,History,Always events: + // If you modify the buffer contents make sure you update 'BufTextLen' and set 'BufDirty' to true. ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only - char* Buf; // Current text // Read-write (pointed data only) - size_t BufSize; // // Read-only - bool BufDirty; // Set if you modify Buf directly // Write + char* Buf; // Current text buffer // Read-write (pointed data only, can't replace the actual pointer) + int BufTextLen; // Current text length in bytes // Read-write + int BufSize; // Maximum text length in bytes // Read-only + bool BufDirty; // Set if you modify Buf/BufTextLen!! // Write int CursorPos; // // Read-write int SelectionStart; // // Read-write (== to SelectionEnd when no selection) int SelectionEnd; // // Read-write - // NB: calling those function loses selection. - void DeleteChars(int pos, int bytes_count); - void InsertChars(int pos, const char* text, const char* text_end = NULL); + // NB: Helper functions for text manipulation. Calling those function loses selection. + void DeleteChars(int pos, int bytes_count); + void InsertChars(int pos, const char* text, const char* text_end = NULL); + bool HasSelection() const { return SelectionStart != SelectionEnd; } }; -// ImColor() is just a helper that implicity converts to either ImU32 (packed 4x1 byte) or ImVec4 (4x1 float) -// None of the ImGui API are using ImColor directly but you can use it as a convenience to pass colors in either formats. +// Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin(). +// NB: For basic min/max size constraint on each axis you don't need to use the callback! The SetNextWindowSizeConstraints() parameters are enough. +struct ImGuiSizeConstraintCallbackData +{ + void* UserData; // Read-only. What user passed to SetNextWindowSizeConstraints() + ImVec2 Pos; // Read-only. Window position, for reference. + ImVec2 CurrentSize; // Read-only. Current window size. + ImVec2 DesiredSize; // Read-write. Desired size, based on user's mouse position. Write to this field to restrain resizing. +}; + +// ImColor() helper to implicity converts colors to either ImU32 (packed 4x1 byte) or ImVec4 (4x1 float) +// Prefer using IM_COL32() macros if you want a guaranteed compile-time ImU32 for usage with ImDrawList API. +// Avoid storing ImColor! Store either u32 of ImVec4. This is not a full-featured color class. +// None of the ImGui API are using ImColor directly but you can use it as a convenience to pass colors in either ImU32 or ImVec4 formats. struct ImColor { ImVec4 Value; - ImColor(int r, int g, int b, int a = 255) { Value.x = (float)r / 255.0f; Value.y = (float)g / 255.0f; Value.z = (float)b / 255.0f; Value.w = (float)a / 255.0f; } + ImColor() { Value.x = Value.y = Value.z = Value.w = 0.0f; } + ImColor(int r, int g, int b, int a = 255) { float sc = 1.0f/255.0f; Value.x = (float)r * sc; Value.y = (float)g * sc; Value.z = (float)b * sc; Value.w = (float)a * sc; } + ImColor(ImU32 rgba) { float sc = 1.0f/255.0f; Value.x = (float)(rgba&0xFF) * sc; Value.y = (float)((rgba>>8)&0xFF) * sc; Value.z = (float)((rgba>>16)&0xFF) * sc; Value.w = (float)(rgba >> 24) * sc; } ImColor(float r, float g, float b, float a = 1.0f) { Value.x = r; Value.y = g; Value.z = b; Value.w = a; } ImColor(const ImVec4& col) { Value = col; } - operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); } - operator ImVec4() const { return Value; } + inline operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); } + inline operator ImVec4() const { return Value; } + + inline void SetHSV(float h, float s, float v, float a = 1.0f){ ImGui::ColorConvertHSVtoRGB(h, s, v, Value.x, Value.y, Value.z); Value.w = a; } static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r,g,b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r,g,b,a); } }; +// Helper: Manually clip large list of items. +// If you are submitting lots of evenly spaced items and you have a random access to the list, you can perform coarse clipping based on visibility to save yourself from processing those items at all. +// The clipper calculates the range of visible items and advance the cursor to compensate for the non-visible items we have skipped. +// ImGui already clip items based on their bounds but it needs to measure text size to do so. Coarse clipping before submission makes this cost and your own data fetching/submission cost null. +// Usage: +// ImGuiListClipper clipper(1000); // we have 1000 elements, evenly spaced. +// while (clipper.Step()) +// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) +// ImGui::Text("line number %d", i); +// - Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height (step skipped if we passed a known height as second arg to constructor). +// - Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. +// - (Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user call Step(). Does nothing and switch to Step 3.) +// - Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. +struct ImGuiListClipper +{ + float StartPosY; + float ItemsHeight; + int ItemsCount, StepNo, DisplayStart, DisplayEnd; + + // items_count: Use -1 to ignore (you can call Begin later). Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step). + // items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetItemsLineHeightWithSpacing(). + // If you don't specify an items_height, you NEED to call Step(). If you specify items_height you may call the old Begin()/End() api directly, but prefer calling Step(). + ImGuiListClipper(int items_count = -1, float items_height = -1.0f) { Begin(items_count, items_height); } // NB: Begin() initialize every fields (as we allow user to call Begin/End multiple times on a same instance if they want). + ~ImGuiListClipper() { IM_ASSERT(ItemsCount == -1); } // Assert if user forgot to call End() or Step() until false. + + IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items. + IMGUI_API void Begin(int items_count, float items_height = -1.0f); // Automatically called by constructor if you passed 'items_count' or by Step() in Step 1. + IMGUI_API void End(); // Automatically called on the last call of Step() that returns false. +}; + //----------------------------------------------------------------------------- // Draw List -// Hold a series of drawing commands. The user provides a renderer for ImDrawList. +// Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. //----------------------------------------------------------------------------- +// Helpers macros to generate 32-bits encoded colors +#define IM_COL32(R,G,B,A) (((ImU32)(A)<<24) | ((ImU32)(B)<<16) | ((ImU32)(G)<<8) | ((ImU32)(R))) +#define IM_COL32_WHITE (0xFFFFFFFF) +#define IM_COL32_BLACK (0xFF000000) +#define IM_COL32_BLACK_TRANS (0x00000000) // Transparent black + // Draw callbacks for advanced uses. -// NB- You most likely DO NOT need to care about draw callbacks just to create your own widget or customized UI rendering (you can poke into the draw list for that) -// Draw callback are useful for example if you want to render a complex 3D scene inside a UI element. -// The expected behavior from your rendering loop is: -// if (cmd.user_callback != NULL) -// cmd.user_callback(parent_list, cmd); -// else -// RenderTriangles() -// It is up to you to decide if your rendering loop or the callback should be responsible for backup/restoring rendering state. +// NB- You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering (you can poke into the draw list for that) +// Draw callback may be useful for example, A) Change your GPU render state, B) render a complex 3D scene inside a UI element (without an intermediate texture/render target), etc. +// The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) cmd.UserCallback(parent_list, cmd); else RenderTriangles()' typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd); // Typically, 1 command = 1 gpu draw call (unless command is a callback) struct ImDrawCmd { - unsigned int vtx_count; // Number of vertices (multiple of 3) to be drawn as triangles. The vertices are stored in the callee ImDrawList's vtx_buffer[] array. - ImVec4 clip_rect; // Clipping rectangle (x1, y1, x2, y2) - ImTextureID texture_id; // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas. - ImDrawCallback user_callback; // If != NULL, call the function instead of rendering the vertices. vtx_count will be 0. clip_rect and texture_id will be set normally. - void* user_callback_data; // The draw callback code can access this. + unsigned int ElemCount; // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[]. + ImVec4 ClipRect; // Clipping rectangle (x1, y1, x2, y2) + ImTextureID TextureId; // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas. + ImDrawCallback UserCallback; // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. + void* UserCallbackData; // The draw callback code can access this. + + ImDrawCmd() { ElemCount = 0; ClipRect.x = ClipRect.y = -8192.0f; ClipRect.z = ClipRect.w = +8192.0f; TextureId = NULL; UserCallback = NULL; UserCallbackData = NULL; } }; +// Vertex index (override with '#define ImDrawIdx unsigned int' inside in imconfig.h) +#ifndef ImDrawIdx +typedef unsigned short ImDrawIdx; +#endif + // Vertex layout #ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert @@ -905,64 +1143,142 @@ struct ImDrawVert ImU32 col; }; #else -// You can change the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h +// You can override the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h // The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine. -// The type has to be described by the #define (you can either declare the struct or use a typedef) +// The type has to be described within the macro (you can either declare the struct or use a typedef) IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; #endif +// Draw channels are used by the Columns API to "split" the render list into different channels while building, so items of each column can be batched together. +// You can also use them to simulate drawing layers and submit primitives in a different order than how they will be rendered. +struct ImDrawChannel +{ + ImVector CmdBuffer; + ImVector IdxBuffer; +}; + // Draw command list // This is the low-level list of polygons that ImGui functions are filling. At the end of the frame, all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering. // At the moment, each ImGui window contains its own ImDrawList but they could potentially be merged in the future. // If you want to add custom rendering within a window, you can use ImGui::GetWindowDrawList() to access the current draw list and add your own primitives. // You can interleave normal ImGui:: calls and adding primitives to the current draw list. // All positions are in screen coordinates (0,0=top-left, 1 pixel per unit). Primitives are always added to the list and not culled (culling is done at render time and at a higher-level by ImGui:: functions). -// Note that this only gives you access to rendering polygons. If your intent is to create custom widgets and the publicly exposed functions/data aren't sufficient, you can add code in imgui_user.inl struct ImDrawList { // This is what you have to render - ImVector commands; // Commands. Typically 1 command = 1 gpu draw call. - ImVector vtx_buffer; // Vertex buffer. Each command consume ImDrawCmd::vtx_count of those + ImVector CmdBuffer; // Commands. Typically 1 command = 1 gpu draw call. + ImVector IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those + ImVector VtxBuffer; // Vertex buffer. - // [Internal to ImGui] - ImVector clip_rect_stack; // [Internal] - ImVector texture_id_stack; // [Internal] - ImDrawVert* vtx_write; // [Internal] point within vtx_buffer after each add command (to avoid using the ImVector<> operators too much) + // [Internal, used while building lists] + const char* _OwnerName; // Pointer to owner window's name (if any) for debugging + unsigned int _VtxCurrentIdx; // [Internal] == VtxBuffer.Size + ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + ImVector _ClipRectStack; // [Internal] + ImVector _TextureIdStack; // [Internal] + ImVector _Path; // [Internal] current path building + int _ChannelsCurrent; // [Internal] current channel number (0) + int _ChannelsCount; // [Internal] number of active channels (1+) + ImVector _Channels; // [Internal] draw channels for columns API (not resized down so _ChannelsCount may be smaller than _Channels.Size) - ImDrawList() { Clear(); } - IMGUI_API void Clear(); - IMGUI_API void ClearFreeMemory(); - IMGUI_API void PushClipRect(const ImVec4& clip_rect); // Scissoring. The values are x1, y1, x2, y2. + ImDrawList() { _OwnerName = NULL; Clear(); } + ~ImDrawList() { ClearFreeMemory(); } + IMGUI_API void PushClipRect(ImVec2 clip_rect_min, ImVec2 clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) IMGUI_API void PushClipRectFullScreen(); IMGUI_API void PopClipRect(); IMGUI_API void PushTextureID(const ImTextureID& texture_id); IMGUI_API void PopTextureID(); - // Primitives + // Primitives IMGUI_API void AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness = 1.0f); - IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners = 0x0F); - IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners = 0x0F); + IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners = 0x0F, float thickness = 1.0f); // a: upper-left, b: lower-right + IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners = 0x0F); // a: upper-left, b: lower-right + IMGUI_API void AddRectFilledMultiColor(const ImVec2& a, const ImVec2& b, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); + IMGUI_API void AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col); + IMGUI_API void AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness = 1.0f); IMGUI_API void AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col); - IMGUI_API void AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12); + IMGUI_API void AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12, float thickness = 1.0f); IMGUI_API void AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12); - IMGUI_API void AddArcFast(const ImVec2& center, float radius, ImU32 col, int a_min_12, int a_max_12, bool filled = false, const ImVec2& third_point_offset = ImVec2(0,0)); // Angles in 0..12 range - IMGUI_API void AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec2* cpu_clip_max = NULL); - IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv0, const ImVec2& uv1, ImU32 col = 0xFFFFFFFF); + IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL); + IMGUI_API void AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL); + IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), ImU32 col = 0xFFFFFFFF); + IMGUI_API void AddPolyline(const ImVec2* points, const int num_points, ImU32 col, bool closed, float thickness, bool anti_aliased); + IMGUI_API void AddConvexPolyFilled(const ImVec2* points, const int num_points, ImU32 col, bool anti_aliased); + IMGUI_API void AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments = 0); + + // Stateful path API, add points then finish with PathFill() or PathStroke() + inline void PathClear() { _Path.resize(0); } + inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); } + inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path[_Path.Size-1], &pos, 8) != 0) _Path.push_back(pos); } + inline void PathFill(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col, true); PathClear(); } + inline void PathStroke(ImU32 col, bool closed, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, closed, thickness, true); PathClear(); } + IMGUI_API void PathArcTo(const ImVec2& centre, float radius, float a_min, float a_max, int num_segments = 10); + IMGUI_API void PathArcToFast(const ImVec2& centre, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle + IMGUI_API void PathBezierCurveTo(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, int num_segments = 0); + IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, int rounding_corners = 0x0F); + + // Channels + // - Use to simulate layers. By switching channels to can render out-of-order (e.g. submit foreground primitives before background primitives) + // - Use to minimize draw calls (e.g. if going back-and-forth between multiple non-overlapping clipping rectangles, prefer to append into separate channels then merge at the end) + IMGUI_API void ChannelsSplit(int channels_count); + IMGUI_API void ChannelsMerge(); + IMGUI_API void ChannelsSetCurrent(int channel_index); // Advanced - IMGUI_API void AddCallback(ImDrawCallback callback, void* callback_data); // Your rendering function must check for 'user_callback' in ImDrawCmd and call the function instead of rendering triangles. + IMGUI_API void AddCallback(ImDrawCallback callback, void* callback_data); // Your rendering function must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles. IMGUI_API void AddDrawCmd(); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible // Internal helpers - IMGUI_API void PrimReserve(unsigned int vtx_count); - IMGUI_API void PrimTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col); - IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); + // NB: all primitives needs to be reserved via PrimReserve() beforehand! + IMGUI_API void Clear(); + IMGUI_API void ClearFreeMemory(); + IMGUI_API void PrimReserve(int idx_count, int vtx_count); + IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles) IMGUI_API void PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col); - IMGUI_API void PrimQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col); - IMGUI_API void PrimLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness = 1.0f); + IMGUI_API void PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col); + inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col){ _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; } + inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; } + inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } IMGUI_API void UpdateClipRect(); IMGUI_API void UpdateTextureID(); - IMGUI_API void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { vtx_write->pos = pos; vtx_write->uv = uv; vtx_write->col = col; vtx_write++; } +}; + +// All draw data to render an ImGui frame +struct ImDrawData +{ + bool Valid; // Only valid after Render() is called and before the next NewFrame() is called. + ImDrawList** CmdLists; + int CmdListsCount; + int TotalVtxCount; // For convenience, sum of all cmd_lists vtx_buffer.Size + int TotalIdxCount; // For convenience, sum of all cmd_lists idx_buffer.Size + + // Functions + ImDrawData() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; } + IMGUI_API void DeIndexAllBuffers(); // For backward compatibility: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! + IMGUI_API void ScaleClipRects(const ImVec2& sc); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. +}; + +struct ImFontConfig +{ + void* FontData; // // TTF data + int FontDataSize; // // TTF data size + bool FontDataOwnedByAtlas; // true // TTF data ownership taken by the container ImFontAtlas (will delete memory itself). Set to true + int FontNo; // 0 // Index of font within TTF file + float SizePixels; // // Size in pixels for rasterizer + int OversampleH, OversampleV; // 3, 1 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis. + bool PixelSnapH; // false // Align every character to pixel boundary (if enabled, set OversampleH/V to 1) + ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs + const ImWchar* GlyphRanges; // // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. + bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). + bool MergeGlyphCenterV; // false // When merging (multiple ImFontInput for one ImFont), vertically center new glyphs instead of aligning their baseline + + // [Internal] + char Name[32]; // Name (strictly for debugging) + ImFont* DstFont; + + IMGUI_API ImFontConfig(); }; // Load and rasterize multiple TTF fonts into a same texture. @@ -973,14 +1289,17 @@ struct ImDrawList // 3. Upload the pixels data into a texture within your graphics system. // 4. Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture. This value will be passed back to you during rendering to identify the texture. // 5. Call ClearTexData() to free textures memory on the heap. +// NB: If you use a 'glyph_ranges' array you need to make sure that your array persist up until the ImFont is cleared. We only copy the pointer, not the data. struct ImFontAtlas { IMGUI_API ImFontAtlas(); IMGUI_API ~ImFontAtlas(); - IMGUI_API ImFont* AddFontDefault(); - IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels, const ImWchar* glyph_ranges = NULL, int font_no = 0); - IMGUI_API ImFont* AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float size_pixels, const ImWchar* glyph_ranges = NULL, int font_no = 0); // Transfer ownership of 'ttf_data' to ImFontAtlas, will be deleted after Build() - IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImWchar* glyph_ranges = NULL, int font_no = 0); // 'compressed_ttf_data' untouched and still owned by caller. Compress with binary_to_compressed_c.cpp + IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg); + IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL); + IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); + IMGUI_API ImFont* AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Transfer ownership of 'ttf_data' to ImFontAtlas, will be deleted after Build() + IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_ttf_data' still owned by caller. Compress with binary_to_compressed_c.cpp + IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_ttf_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 paramaeter IMGUI_API void ClearTexData(); // Clear the CPU-side texture data. Saves RAM once the texture has been copied to graphics memory. IMGUI_API void ClearInputData(); // Clear the input TTF data (inc sizes, glyph ranges) IMGUI_API void ClearFonts(); // Clear the ImGui-side font data (glyphs storage, UV coordinates) @@ -993,76 +1312,88 @@ struct ImFontAtlas // Pitch = Width * BytesPerPixels IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel - IMGUI_API void SetTexID(void* id) { TexID = id; } + void SetTexID(void* id) { TexID = id; } // Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list) - // (Those functions could be static but aren't so most users don't have to refer to the ImFontAtlas:: name ever if in their code; just using io.Fonts->) + // NB: Make sure that your string are UTF-8 and NOT in your local code page. See FAQ for details. IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin + IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs IMGUI_API const ImWchar* GetGlyphRangesChinese(); // Japanese + full set of about 21000 CJK Unified Ideographs + IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters // Members // (Access texture data via GetTexData*() calls which will setup a default font for you.) void* TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It ia passed back to you during rendering. unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 - int TexWidth; - int TexHeight; - ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel (part of the TexExtraData block) - ImVector Fonts; + int TexWidth; // Texture width calculated during Build(). + int TexHeight; // Texture height calculated during Build(). + int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. + ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel + ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. // Private - struct ImFontAtlasData; - ImVector InputData; // Internal data + ImVector ConfigData; // Internal data IMGUI_API bool Build(); // Build pixels data. This is automatically for you by the GetTexData*** functions. IMGUI_API void RenderCustomTexData(int pass, void* rects); }; -// TTF font loading and rendering +// Font runtime data and rendering // ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32(). -// Kerning isn't supported. At the moment some ImGui code does per-character CalcTextSize calls, need something more state-ful. struct ImFont { - // Members: Settings - float FontSize; // // Height of characters, set during loading (don't change after loading) - float Scale; // = 1.0f // Base font scale, multiplied by the per-window font scale which you can adjust with SetFontScale() - ImVec2 DisplayOffset; // = (0.0f,0.0f) // Offset font rendering by xx pixels - ImWchar FallbackChar; // = '?' // Replacement glyph if one isn't found. Only set via SetFallbackChar() - - // Members: Runtime data struct Glyph { - ImWchar Codepoint; - signed short XAdvance; - signed short Width, Height; - signed short XOffset, YOffset; - float U0, V0, U1, V1; // Texture coordinates + ImWchar Codepoint; + float XAdvance; + float X0, Y0, X1, Y1; + float U0, V0, U1, V1; // Texture coordinates }; - float BaseLine; // Distance from top to bottom of e.g. 'A' [0..FontSize] - ImFontAtlas* ContainerAtlas; // What we has been loaded into - ImVector Glyphs; - const Glyph* FallbackGlyph; // == FindGlyph(FontFallbackChar) - float FallbackXAdvance; // - ImVector IndexXAdvance; // Glyphs->XAdvance directly indexable (for CalcTextSize functions which are often bottleneck in large UI) - ImVector IndexLookup; // Index glyphs by Unicode code-point + + // Members: Hot ~62/78 bytes + float FontSize; // // Height of characters, set during loading (don't change after loading) + float Scale; // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetFontScale() + ImVec2 DisplayOffset; // = (0.f,1.f) // Offset font rendering by xx pixels + ImVector Glyphs; // // All glyphs. + ImVector IndexXAdvance; // // Sparse. Glyphs->XAdvance in a directly indexable way (more cache-friendly, for CalcTextSize functions which are often bottleneck in large UI). + ImVector IndexLookup; // // Sparse. Index glyphs by Unicode code-point. + const Glyph* FallbackGlyph; // == FindGlyph(FontFallbackChar) + float FallbackXAdvance; // == FallbackGlyph->XAdvance + ImWchar FallbackChar; // = '?' // Replacement glyph if one isn't found. Only set via SetFallbackChar() + + // Members: Cold ~18/26 bytes + short ConfigDataCount; // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont. + ImFontConfig* ConfigData; // // Pointer within ContainerAtlas->ConfigData + ImFontAtlas* ContainerAtlas; // // What we has been loaded into + float Ascent, Descent; // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] // Methods IMGUI_API ImFont(); IMGUI_API ~ImFont(); IMGUI_API void Clear(); IMGUI_API void BuildLookupTable(); - IMGUI_API const Glyph* FindGlyph(unsigned short c) const; + IMGUI_API const Glyph* FindGlyph(ImWchar c) const; IMGUI_API void SetFallbackChar(ImWchar c); - IMGUI_API bool IsLoaded() const { return ContainerAtlas != NULL; } + float GetCharAdvance(ImWchar c) const { return ((int)c < IndexXAdvance.Size) ? IndexXAdvance[(int)c] : FallbackXAdvance; } + bool IsLoaded() const { return ContainerAtlas != NULL; } // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable. // 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable. IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL) const; // utf8 - IMGUI_API ImVec2 CalcTextSizeW(float size, float max_width, const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining = NULL) const; // wchar - IMGUI_API void RenderText(float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, ImDrawList* draw_list, float wrap_width = 0.0f, const ImVec2* cpu_clip_max = NULL) const; IMGUI_API const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const; + IMGUI_API void RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, unsigned short c) const; + IMGUI_API void RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false) const; + + // Private + IMGUI_API void GrowIndex(int new_size); + IMGUI_API void AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built. }; +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + //---- Include imgui_user.h at the end of imgui.h //---- So you can include code that extends ImGui using any of the types declared above. //---- (also convenient for user to only explicitly include vanilla imgui.h) diff --git a/modules/onscreengui/ext/imgui/imgui_demo.cpp b/modules/onscreengui/ext/imgui/imgui_demo.cpp new file mode 100644 index 0000000000..6ec0018e99 --- /dev/null +++ b/modules/onscreengui/ext/imgui/imgui_demo.cpp @@ -0,0 +1,2538 @@ +// dear imgui, v1.49 +// (demo code) + +// Don't remove this file from your project! It is useful reference code that you can execute. +// You can call ImGui::ShowTestWindow() in your code to learn about various features of ImGui. +// Everything in this file will be stripped out by the linker if you don't call ImGui::ShowTestWindow(). + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#include // toupper, isprint +#include // sqrtf, fabsf, fmodf, powf, cosf, sinf, floorf, ceilf +#include // vsnprintf, sscanf, printf +#include // NULL, malloc, free, qsort, atoi +#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier +#include // intptr_t +#else +#include // intptr_t +#endif + +#ifdef _MSC_VER +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#define snprintf _snprintf +#endif +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wdeprecated-declarations" // warning : 'xx' is deprecated: The POSIX name for this item.. // for strdup used in demo code (so user can copy & paste the code) +#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' +#pragma clang diagnostic ignored "-Wformat-security" // warning : warning: format string is not a string literal +#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. +#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier // +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size +#pragma GCC diagnostic ignored "-Wformat-security" // warning : format string is not a string literal (potentially insecure) +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value +#endif + +// Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n. +#ifdef _WIN32 +#define IM_NEWLINE "\r\n" +#else +#define IM_NEWLINE "\n" +#endif + +#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) +#define IM_MAX(_A,_B) (((_A) >= (_B)) ? (_A) : (_B)) + +//----------------------------------------------------------------------------- +// DEMO CODE +//----------------------------------------------------------------------------- + +#ifndef IMGUI_DISABLE_TEST_WINDOWS + +static void ShowExampleAppConsole(bool* p_open); +static void ShowExampleAppLog(bool* p_open); +static void ShowExampleAppLayout(bool* p_open); +static void ShowExampleAppPropertyEditor(bool* p_open); +static void ShowExampleAppLongText(bool* p_open); +static void ShowExampleAppAutoResize(bool* p_open); +static void ShowExampleAppConstrainedResize(bool* p_open); +static void ShowExampleAppFixedOverlay(bool* p_open); +static void ShowExampleAppManipulatingWindowTitle(bool* p_open); +static void ShowExampleAppCustomRendering(bool* p_open); +static void ShowExampleAppMainMenuBar(); +static void ShowExampleMenuFile(); + +static void ShowHelpMarker(const char* desc) +{ + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(desc); +} + +void ImGui::ShowUserGuide() +{ + ImGui::BulletText("Double-click on title bar to collapse window."); + ImGui::BulletText("Click and drag on lower right corner to resize window."); + ImGui::BulletText("Click and drag on any empty space to move window."); + ImGui::BulletText("Mouse Wheel to scroll."); + if (ImGui::GetIO().FontAllowUserScaling) + ImGui::BulletText("CTRL+Mouse Wheel to zoom window contents."); + ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields."); + ImGui::BulletText("CTRL+Click on a slider or drag box to input text."); + ImGui::BulletText( + "While editing text:\n" + "- Hold SHIFT or use mouse to select text\n" + "- CTRL+Left/Right to word jump\n" + "- CTRL+A or double-click to select all\n" + "- CTRL+X,CTRL+C,CTRL+V clipboard\n" + "- CTRL+Z,CTRL+Y undo/redo\n" + "- ESCAPE to revert\n" + "- You can apply arithmetic operators +,*,/ on numerical values.\n" + " Use +- to subtract.\n"); +} + +// Demonstrate most ImGui features (big function!) +void ImGui::ShowTestWindow(bool* p_open) +{ + // Examples apps + static bool show_app_main_menu_bar = false; + static bool show_app_console = false; + static bool show_app_log = false; + static bool show_app_layout = false; + static bool show_app_property_editor = false; + static bool show_app_long_text = false; + static bool show_app_auto_resize = false; + static bool show_app_constrained_resize = false; + static bool show_app_fixed_overlay = false; + static bool show_app_manipulating_window_title = false; + static bool show_app_custom_rendering = false; + static bool show_app_style_editor = false; + + static bool show_app_metrics = false; + static bool show_app_about = false; + + if (show_app_main_menu_bar) ShowExampleAppMainMenuBar(); + if (show_app_console) ShowExampleAppConsole(&show_app_console); + if (show_app_log) ShowExampleAppLog(&show_app_log); + if (show_app_layout) ShowExampleAppLayout(&show_app_layout); + if (show_app_property_editor) ShowExampleAppPropertyEditor(&show_app_property_editor); + if (show_app_long_text) ShowExampleAppLongText(&show_app_long_text); + if (show_app_auto_resize) ShowExampleAppAutoResize(&show_app_auto_resize); + if (show_app_constrained_resize) ShowExampleAppConstrainedResize(&show_app_constrained_resize); + if (show_app_fixed_overlay) ShowExampleAppFixedOverlay(&show_app_fixed_overlay); + if (show_app_manipulating_window_title) ShowExampleAppManipulatingWindowTitle(&show_app_manipulating_window_title); + if (show_app_custom_rendering) ShowExampleAppCustomRendering(&show_app_custom_rendering); + + if (show_app_metrics) ImGui::ShowMetricsWindow(&show_app_metrics); + if (show_app_style_editor) { ImGui::Begin("Style Editor", &show_app_style_editor); ImGui::ShowStyleEditor(); ImGui::End(); } + if (show_app_about) + { + ImGui::Begin("About ImGui", &show_app_about, ImGuiWindowFlags_AlwaysAutoResize); + ImGui::Text("dear imgui, %s", ImGui::GetVersion()); + ImGui::Separator(); + ImGui::Text("By Omar Cornut and all github contributors."); + ImGui::Text("ImGui is licensed under the MIT License, see LICENSE for more information."); + ImGui::End(); + } + + static bool no_titlebar = false; + static bool no_border = true; + static bool no_resize = false; + static bool no_move = false; + static bool no_scrollbar = false; + static bool no_collapse = false; + static bool no_menu = false; + + // Demonstrate the various window flags. Typically you would just use the default. + ImGuiWindowFlags window_flags = 0; + if (no_titlebar) window_flags |= ImGuiWindowFlags_NoTitleBar; + if (!no_border) window_flags |= ImGuiWindowFlags_ShowBorders; + if (no_resize) window_flags |= ImGuiWindowFlags_NoResize; + if (no_move) window_flags |= ImGuiWindowFlags_NoMove; + if (no_scrollbar) window_flags |= ImGuiWindowFlags_NoScrollbar; + if (no_collapse) window_flags |= ImGuiWindowFlags_NoCollapse; + if (!no_menu) window_flags |= ImGuiWindowFlags_MenuBar; + ImGui::SetNextWindowSize(ImVec2(550,680), ImGuiSetCond_FirstUseEver); + if (!ImGui::Begin("ImGui Demo", p_open, window_flags)) + { + // Early out if the window is collapsed, as an optimization. + ImGui::End(); + return; + } + + //ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.65f); // 2/3 of the space for widget and 1/3 for labels + ImGui::PushItemWidth(-140); // Right align, keep 140 pixels for labels + + ImGui::Text("Dear ImGui says hello."); + + // Menu + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("Menu")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Examples")) + { + ImGui::MenuItem("Main menu bar", NULL, &show_app_main_menu_bar); + ImGui::MenuItem("Console", NULL, &show_app_console); + ImGui::MenuItem("Log", NULL, &show_app_log); + ImGui::MenuItem("Simple layout", NULL, &show_app_layout); + ImGui::MenuItem("Property editor", NULL, &show_app_property_editor); + ImGui::MenuItem("Long text display", NULL, &show_app_long_text); + ImGui::MenuItem("Auto-resizing window", NULL, &show_app_auto_resize); + ImGui::MenuItem("Constrained-resizing window", NULL, &show_app_constrained_resize); + ImGui::MenuItem("Simple overlay", NULL, &show_app_fixed_overlay); + ImGui::MenuItem("Manipulating window title", NULL, &show_app_manipulating_window_title); + ImGui::MenuItem("Custom rendering", NULL, &show_app_custom_rendering); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Help")) + { + ImGui::MenuItem("Metrics", NULL, &show_app_metrics); + ImGui::MenuItem("Style Editor", NULL, &show_app_style_editor); + ImGui::MenuItem("About ImGui", NULL, &show_app_about); + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + + ImGui::Spacing(); + if (ImGui::CollapsingHeader("Help")) + { + ImGui::TextWrapped("This window is being created by the ShowTestWindow() function. Please refer to the code for programming reference.\n\nUser Guide:"); + ImGui::ShowUserGuide(); + } + + if (ImGui::CollapsingHeader("Window options")) + { + ImGui::Checkbox("No titlebar", &no_titlebar); ImGui::SameLine(150); + ImGui::Checkbox("No border", &no_border); ImGui::SameLine(300); + ImGui::Checkbox("No resize", &no_resize); + ImGui::Checkbox("No move", &no_move); ImGui::SameLine(150); + ImGui::Checkbox("No scrollbar", &no_scrollbar); ImGui::SameLine(300); + ImGui::Checkbox("No collapse", &no_collapse); + ImGui::Checkbox("No menu", &no_menu); + + if (ImGui::TreeNode("Style")) + { + ImGui::ShowStyleEditor(); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Logging")) + { + ImGui::TextWrapped("The logging API redirects all text output so you can easily capture the content of a window or a block. Tree nodes can be automatically expanded. You can also call ImGui::LogText() to output directly to the log without a visual output."); + ImGui::LogButtons(); + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Widgets")) + { + if (ImGui::TreeNode("Trees")) + { + if (ImGui::TreeNode("Basic trees")) + { + for (int i = 0; i < 5; i++) + if (ImGui::TreeNode((void*)(intptr_t)i, "Child %d", i)) + { + ImGui::Text("blah blah"); + ImGui::SameLine(); + if (ImGui::SmallButton("print")) printf("Child %d pressed", i); + ImGui::TreePop(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Advanced, with Selectable nodes")) + { + ShowHelpMarker("This is a more standard looking tree with selectable nodes.\nClick to select, CTRL+Click to toggle, click on arrows or double-click to open."); + static bool align_label_with_current_x_position = false; + ImGui::Checkbox("Align label with current X position)", &align_label_with_current_x_position); + ImGui::Text("Hello!"); + if (align_label_with_current_x_position) + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + + static int selection_mask = (1 << 2); // Dumb representation of what may be user-side selection state. You may carry selection state inside or outside your objects in whatever format you see fit. + int node_clicked = -1; // Temporary storage of what node we have clicked to process selection at the end of the loop. May be a pointer to your own node type, etc. + ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, ImGui::GetFontSize()*3); // Increase spacing to differentiate leaves from expanded contents. + for (int i = 0; i < 6; i++) + { + // Disable the default open on single-click behavior and pass in Selected flag according to our selection state. + ImGuiTreeNodeFlags node_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ((selection_mask & (1 << i)) ? ImGuiTreeNodeFlags_Selected : 0); + if (i < 3) + { + // Node + bool node_open = ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Node %d", i); + if (ImGui::IsItemClicked()) + node_clicked = i; + if (node_open) + { + ImGui::Text("Blah blah\nBlah Blah"); + ImGui::TreePop(); + } + } + else + { + // Leaf: The only reason we have a TreeNode at all is to allow selection of the leaf. Otherwise we can use BulletText() or TreeAdvanceToLabelPos()+Text(). + ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags | ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen, "Selectable Leaf %d", i); + if (ImGui::IsItemClicked()) + node_clicked = i; + } + } + if (node_clicked != -1) + { + // Update selection state. Process outside of tree loop to avoid visual inconsistencies during the clicking-frame. + if (ImGui::GetIO().KeyCtrl) + selection_mask ^= (1 << node_clicked); // CTRL+click to toggle + else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, this commented bit preserve selection when clicking on item that is part of the selection + selection_mask = (1 << node_clicked); // Click to single-select + } + ImGui::PopStyleVar(); + if (align_label_with_current_x_position) + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Collapsing Headers")) + { + static bool closable_group = true; + if (ImGui::CollapsingHeader("Header")) + { + ImGui::Checkbox("Enable extra group", &closable_group); + for (int i = 0; i < 5; i++) + ImGui::Text("Some content %d", i); + } + if (ImGui::CollapsingHeader("Header with a close button", &closable_group)) + { + for (int i = 0; i < 5; i++) + ImGui::Text("More content %d", i); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Bullets")) + { + ImGui::BulletText("Bullet point 1"); + ImGui::BulletText("Bullet point 2\nOn multiple lines"); + ImGui::Bullet(); ImGui::Text("Bullet point 3 (two calls)"); + ImGui::Bullet(); ImGui::SmallButton("Button"); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Colored Text")) + { + // Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility. + ImGui::TextColored(ImVec4(1.0f,0.0f,1.0f,1.0f), "Pink"); + ImGui::TextColored(ImVec4(1.0f,1.0f,0.0f,1.0f), "Yellow"); + ImGui::TextDisabled("Disabled"); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Word Wrapping")) + { + // Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility. + ImGui::TextWrapped("This text should automatically wrap on the edge of the window. The current implementation for text wrapping follows simple rules suitable for English and possibly other languages."); + ImGui::Spacing(); + + static float wrap_width = 200.0f; + ImGui::SliderFloat("Wrap width", &wrap_width, -20, 600, "%.0f"); + + ImGui::Text("Test paragraph 1:"); + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(pos.x + wrap_width, pos.y), ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()), 0xFFFF00FF); + ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); + ImGui::Text("lazy dog. This paragraph is made to fit within %.0f pixels. The quick brown fox jumps over the lazy dog.", wrap_width); + ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), 0xFF00FFFF); + ImGui::PopTextWrapPos(); + + ImGui::Text("Test paragraph 2:"); + pos = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(pos.x + wrap_width, pos.y), ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()), 0xFFFF00FF); + ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); + ImGui::Text("aaaaaaaa bbbbbbbb, cccccccc,dddddddd. eeeeeeee ffffffff. gggggggg!hhhhhhhh"); + ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), 0xFF00FFFF); + ImGui::PopTextWrapPos(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("UTF-8 Text")) + { + // UTF-8 test with Japanese characters + // (needs a suitable font, try Arial Unicode or M+ fonts http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html) + // Most compiler appears to support UTF-8 in source code (with Visual Studio you need to save your file as 'UTF-8 without signature') + // However for the sake for maximum portability here we are *not* including raw UTF-8 character in this source file, instead we encode the string with hexadecimal constants. + // In your own application be reasonable and use UTF-8 in source or retrieve the data from file system! + // Note that characters values are preserved even if the font cannot be displayed, so you can safely copy & paste garbled characters into another application. + ImGui::TextWrapped("CJK text will only appears if the font was loaded with the appropriate CJK character ranges. Call io.Font->LoadFromFileTTF() manually to load extra character ranges."); + ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)"); + ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)"); + static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"; + ImGui::InputText("UTF-8 input", buf, IM_ARRAYSIZE(buf)); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Images")) + { + ImGui::TextWrapped("Below we are displaying the font texture (which is the only texture we have access to in this demo). Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. Hover the texture for a zoomed view!"); + ImVec2 tex_screen_pos = ImGui::GetCursorScreenPos(); + float tex_w = (float)ImGui::GetIO().Fonts->TexWidth; + float tex_h = (float)ImGui::GetIO().Fonts->TexHeight; + ImTextureID tex_id = ImGui::GetIO().Fonts->TexID; + ImGui::Text("%.0fx%.0f", tex_w, tex_h); + ImGui::Image(tex_id, ImVec2(tex_w, tex_h), ImVec2(0,0), ImVec2(1,1), ImColor(255,255,255,255), ImColor(255,255,255,128)); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + float focus_sz = 32.0f; + float focus_x = ImGui::GetMousePos().x - tex_screen_pos.x - focus_sz * 0.5f; if (focus_x < 0.0f) focus_x = 0.0f; else if (focus_x > tex_w - focus_sz) focus_x = tex_w - focus_sz; + float focus_y = ImGui::GetMousePos().y - tex_screen_pos.y - focus_sz * 0.5f; if (focus_y < 0.0f) focus_y = 0.0f; else if (focus_y > tex_h - focus_sz) focus_y = tex_h - focus_sz; + ImGui::Text("Min: (%.2f, %.2f)", focus_x, focus_y); + ImGui::Text("Max: (%.2f, %.2f)", focus_x + focus_sz, focus_y + focus_sz); + ImVec2 uv0 = ImVec2((focus_x) / tex_w, (focus_y) / tex_h); + ImVec2 uv1 = ImVec2((focus_x + focus_sz) / tex_w, (focus_y + focus_sz) / tex_h); + ImGui::Image(tex_id, ImVec2(128,128), uv0, uv1, ImColor(255,255,255,255), ImColor(255,255,255,128)); + ImGui::EndTooltip(); + } + ImGui::TextWrapped("And now some textured buttons.."); + static int pressed_count = 0; + for (int i = 0; i < 8; i++) + { + ImGui::PushID(i); + int frame_padding = -1 + i; // -1 = uses default padding + if (ImGui::ImageButton(tex_id, ImVec2(32,32), ImVec2(0,0), ImVec2(32.0f/tex_w,32/tex_h), frame_padding, ImColor(0,0,0,255))) + pressed_count += 1; + ImGui::PopID(); + ImGui::SameLine(); + } + ImGui::NewLine(); + ImGui::Text("Pressed %d times.", pressed_count); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Selectables")) + { + if (ImGui::TreeNode("Basic")) + { + static bool selected[4] = { false, true, false, false }; + ImGui::Selectable("1. I am selectable", &selected[0]); + ImGui::Selectable("2. I am selectable", &selected[1]); + ImGui::Text("3. I am not selectable"); + ImGui::Selectable("4. I am selectable", &selected[2]); + if (ImGui::Selectable("5. I am double clickable", selected[3], ImGuiSelectableFlags_AllowDoubleClick)) + if (ImGui::IsMouseDoubleClicked(0)) + selected[3] = !selected[3]; + ImGui::TreePop(); + } + if (ImGui::TreeNode("Rendering more text into the same block")) + { + static bool selected[3] = { false, false, false }; + ImGui::Selectable("main.c", &selected[0]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes"); + ImGui::Selectable("Hello.cpp", &selected[1]); ImGui::SameLine(300); ImGui::Text("12,345 bytes"); + ImGui::Selectable("Hello.h", &selected[2]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes"); + ImGui::TreePop(); + } + if (ImGui::TreeNode("Grid")) + { + static bool selected[16] = { true, false, false, false, false, true, false, false, false, false, true, false, false, false, false, true }; + for (int i = 0; i < 16; i++) + { + ImGui::PushID(i); + if (ImGui::Selectable("Sailor", &selected[i], 0, ImVec2(50,50))) + { + int x = i % 4, y = i / 4; + if (x > 0) selected[i - 1] ^= 1; + if (x < 3) selected[i + 1] ^= 1; + if (y > 0) selected[i - 4] ^= 1; + if (y < 3) selected[i + 4] ^= 1; + } + if ((i % 4) < 3) ImGui::SameLine(); + ImGui::PopID(); + } + ImGui::TreePop(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Filtered Text Input")) + { + static char buf1[64] = ""; ImGui::InputText("default", buf1, 64); + static char buf2[64] = ""; ImGui::InputText("decimal", buf2, 64, ImGuiInputTextFlags_CharsDecimal); + static char buf3[64] = ""; ImGui::InputText("hexadecimal", buf3, 64, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); + static char buf4[64] = ""; ImGui::InputText("uppercase", buf4, 64, ImGuiInputTextFlags_CharsUppercase); + static char buf5[64] = ""; ImGui::InputText("no blank", buf5, 64, ImGuiInputTextFlags_CharsNoBlank); + struct TextFilters { static int FilterImGuiLetters(ImGuiTextEditCallbackData* data) { if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar)) return 0; return 1; } }; + static char buf6[64] = ""; ImGui::InputText("\"imgui\" letters", buf6, 64, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); + + ImGui::Text("Password input"); + static char bufpass[64] = "password123"; + ImGui::InputText("password", bufpass, 64, ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsNoBlank); + ImGui::SameLine(); ShowHelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n"); + ImGui::InputText("password (clear)", bufpass, 64, ImGuiInputTextFlags_CharsNoBlank); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Multi-line Text Input")) + { + static bool read_only = false; + static char text[1024*16] = + "/*\n" + " The Pentium F00F bug, shorthand for F0 0F C7 C8,\n" + " the hexadecimal encoding of one offending instruction,\n" + " more formally, the invalid operand with locked CMPXCHG8B\n" + " instruction bug, is a design flaw in the majority of\n" + " Intel Pentium, Pentium MMX, and Pentium OverDrive\n" + " processors (all in the P5 microarchitecture).\n" + "*/\n\n" + "label:\n" + "\tlock cmpxchg8b eax\n"; + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0)); + ImGui::Checkbox("Read-only", &read_only); + ImGui::PopStyleVar(); + ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-1.0f, ImGui::GetTextLineHeight() * 16), ImGuiInputTextFlags_AllowTabInput | (read_only ? ImGuiInputTextFlags_ReadOnly : 0)); + ImGui::TreePop(); + } + + static bool a=false; + if (ImGui::Button("Button")) { printf("Clicked\n"); a ^= 1; } + if (a) + { + ImGui::SameLine(); + ImGui::Text("Thanks for clicking me!"); + } + + static bool check = true; + ImGui::Checkbox("checkbox", &check); + + static int e = 0; + ImGui::RadioButton("radio a", &e, 0); ImGui::SameLine(); + ImGui::RadioButton("radio b", &e, 1); ImGui::SameLine(); + ImGui::RadioButton("radio c", &e, 2); + + // Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style. + for (int i = 0; i < 7; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::PushStyleColor(ImGuiCol_Button, ImColor::HSV(i/7.0f, 0.6f, 0.6f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImColor::HSV(i/7.0f, 0.7f, 0.7f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImColor::HSV(i/7.0f, 0.8f, 0.8f)); + ImGui::Button("Click"); + ImGui::PopStyleColor(3); + ImGui::PopID(); + } + + ImGui::Text("Hover over me"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("I am a tooltip"); + + ImGui::SameLine(); + ImGui::Text("- or me"); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text("I am a fancy tooltip"); + static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; + ImGui::PlotLines("Curve", arr, IM_ARRAYSIZE(arr)); + ImGui::EndTooltip(); + } + + // Testing IMGUI_ONCE_UPON_A_FRAME macro + //for (int i = 0; i < 5; i++) + //{ + // IMGUI_ONCE_UPON_A_FRAME + // { + // ImGui::Text("This will be displayed only once."); + // } + //} + + ImGui::Separator(); + + ImGui::LabelText("label", "Value"); + + static int item = 1; + ImGui::Combo("combo", &item, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); // Combo using values packed in a single constant string (for really quick combo) + + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK" }; + static int item2 = -1; + ImGui::Combo("combo scroll", &item2, items, IM_ARRAYSIZE(items)); // Combo using proper array. You can also pass a callback to retrieve array value, no need to create/copy an array just for that. + + { + static char str0[128] = "Hello, world!"; + static int i0=123; + static float f0=0.001f; + ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0)); + ImGui::SameLine(); ShowHelpMarker("Hold SHIFT or use mouse to select text.\n" "CTRL+Left/Right to word jump.\n" "CTRL+A or double-click to select all.\n" "CTRL+X,CTRL+C,CTRL+V clipboard.\n" "CTRL+Z,CTRL+Y undo/redo.\n" "ESCAPE to revert.\n"); + + ImGui::InputInt("input int", &i0); + ImGui::SameLine(); ShowHelpMarker("You can apply arithmetic operators +,*,/ on numerical values.\n e.g. [ 100 ], input \'*2\', result becomes [ 200 ]\nUse +- to subtract.\n"); + + ImGui::InputFloat("input float", &f0, 0.01f, 1.0f); + + static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; + ImGui::InputFloat3("input float3", vec4a); + } + + { + static int i1=50, i2=42; + ImGui::DragInt("drag int", &i1, 1); + ImGui::SameLine(); ShowHelpMarker("Click and drag to edit value.\nHold SHIFT/ALT for faster/slower edit.\nDouble-click or CTRL+click to input value."); + + ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%.0f%%"); + + static float f1=1.00f, f2=0.0067f; + ImGui::DragFloat("drag float", &f1, 0.005f); + ImGui::DragFloat("drag small float", &f2, 0.0001f, 0.0f, 0.0f, "%.06f ns"); + } + + { + static int i1=0; + ImGui::SliderInt("slider int", &i1, -1, 3); + ImGui::SameLine(); ShowHelpMarker("CTRL+click to input value."); + + static float f1=0.123f, f2=0.0f; + ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f"); + ImGui::SliderFloat("slider log float", &f2, -10.0f, 10.0f, "%.4f", 3.0f); + static float angle = 0.0f; + ImGui::SliderAngle("slider angle", &angle); + } + + static float col1[3] = { 1.0f,0.0f,0.2f }; + static float col2[4] = { 0.4f,0.7f,0.0f,0.5f }; + ImGui::ColorEdit3("color 1", col1); + ImGui::SameLine(); ShowHelpMarker("Click on the colored square to change edit mode.\nCTRL+click on individual component to input value.\n"); + + ImGui::ColorEdit4("color 2", col2); + + const char* listbox_items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; + static int listbox_item_current = 1; + ImGui::ListBox("listbox\n(single select)", &listbox_item_current, listbox_items, IM_ARRAYSIZE(listbox_items), 4); + + //static int listbox_item_current2 = 2; + //ImGui::PushItemWidth(-1); + //ImGui::ListBox("##listbox2", &listbox_item_current2, listbox_items, IM_ARRAYSIZE(listbox_items), 4); + //ImGui::PopItemWidth(); + + if (ImGui::TreeNode("Range Widgets")) + { + ImGui::Unindent(); + + static float begin = 10, end = 90; + static int begin_i = 100, end_i = 1000; + ImGui::DragFloatRange2("range", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%"); + ImGui::DragIntRange2("range int (no bounds)", &begin_i, &end_i, 5, 0, 0, "Min: %.0f units", "Max: %.0f units"); + + ImGui::Indent(); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Multi-component Widgets")) + { + ImGui::Unindent(); + + static float vec4f[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; + static int vec4i[4] = { 1, 5, 100, 255 }; + + ImGui::InputFloat2("input float2", vec4f); + ImGui::DragFloat2("drag float2", vec4f, 0.01f, 0.0f, 1.0f); + ImGui::SliderFloat2("slider float2", vec4f, 0.0f, 1.0f); + ImGui::DragInt2("drag int2", vec4i, 1, 0, 255); + ImGui::InputInt2("input int2", vec4i); + ImGui::SliderInt2("slider int2", vec4i, 0, 255); + ImGui::Spacing(); + + ImGui::InputFloat3("input float3", vec4f); + ImGui::DragFloat3("drag float3", vec4f, 0.01f, 0.0f, 1.0f); + ImGui::SliderFloat3("slider float3", vec4f, 0.0f, 1.0f); + ImGui::DragInt3("drag int3", vec4i, 1, 0, 255); + ImGui::InputInt3("input int3", vec4i); + ImGui::SliderInt3("slider int3", vec4i, 0, 255); + ImGui::Spacing(); + + ImGui::InputFloat4("input float4", vec4f); + ImGui::DragFloat4("drag float4", vec4f, 0.01f, 0.0f, 1.0f); + ImGui::SliderFloat4("slider float4", vec4f, 0.0f, 1.0f); + ImGui::InputInt4("input int4", vec4i); + ImGui::DragInt4("drag int4", vec4i, 1, 0, 255); + ImGui::SliderInt4("slider int4", vec4i, 0, 255); + + ImGui::Indent(); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Vertical Sliders")) + { + ImGui::Unindent(); + const float spacing = 4; + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing)); + + static int int_value = 0; + ImGui::VSliderInt("##int", ImVec2(18,160), &int_value, 0, 5); + ImGui::SameLine(); + + static float values[7] = { 0.0f, 0.60f, 0.35f, 0.9f, 0.70f, 0.20f, 0.0f }; + ImGui::PushID("set1"); + for (int i = 0; i < 7; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::PushStyleColor(ImGuiCol_FrameBg, ImColor::HSV(i/7.0f, 0.5f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, ImColor::HSV(i/7.0f, 0.6f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_FrameBgActive, ImColor::HSV(i/7.0f, 0.7f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_SliderGrab, ImColor::HSV(i/7.0f, 0.9f, 0.9f)); + ImGui::VSliderFloat("##v", ImVec2(18,160), &values[i], 0.0f, 1.0f, ""); + if (ImGui::IsItemActive() || ImGui::IsItemHovered()) + ImGui::SetTooltip("%.3f", values[i]); + ImGui::PopStyleColor(4); + ImGui::PopID(); + } + ImGui::PopID(); + + ImGui::SameLine(); + ImGui::PushID("set2"); + static float values2[4] = { 0.20f, 0.80f, 0.40f, 0.25f }; + const int rows = 3; + const ImVec2 small_slider_size(18, (160.0f-(rows-1)*spacing)/rows); + for (int nx = 0; nx < 4; nx++) + { + if (nx > 0) ImGui::SameLine(); + ImGui::BeginGroup(); + for (int ny = 0; ny < rows; ny++) + { + ImGui::PushID(nx*rows+ny); + ImGui::VSliderFloat("##v", small_slider_size, &values2[nx], 0.0f, 1.0f, ""); + if (ImGui::IsItemActive() || ImGui::IsItemHovered()) + ImGui::SetTooltip("%.3f", values2[nx]); + ImGui::PopID(); + } + ImGui::EndGroup(); + } + ImGui::PopID(); + + ImGui::SameLine(); + ImGui::PushID("set3"); + for (int i = 0; i < 4; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 40); + ImGui::VSliderFloat("##v", ImVec2(40,160), &values[i], 0.0f, 1.0f, "%.2f\nsec"); + ImGui::PopStyleVar(); + ImGui::PopID(); + } + ImGui::PopID(); + ImGui::PopStyleVar(); + + ImGui::Indent(); + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Graphs widgets")) + { + static bool animate = true; + ImGui::Checkbox("Animate", &animate); + + static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; + ImGui::PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr)); + + // Create a dummy array of contiguous float values to plot + // Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float and the sizeof() of your structure in the Stride parameter. + static float values[90] = { 0 }; + static int values_offset = 0; + if (animate) + { + static float refresh_time = ImGui::GetTime(); // Create dummy data at fixed 60 hz rate for the demo + for (; ImGui::GetTime() > refresh_time + 1.0f/60.0f; refresh_time += 1.0f/60.0f) + { + static float phase = 0.0f; + values[values_offset] = cosf(phase); + values_offset = (values_offset+1) % IM_ARRAYSIZE(values); + phase += 0.10f*values_offset; + } + } + ImGui::PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, "avg 0.0", -1.0f, 1.0f, ImVec2(0,80)); + ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0,80)); + + // Use functions to generate output + // FIXME: This is rather awkward because current plot API only pass in indices. We probably want an API passing floats and user provide sample rate/count. + struct Funcs + { + static float Sin(void*, int i) { return sinf(i * 0.1f); } + static float Saw(void*, int i) { return (i & 1) ? 1.0f : 0.0f; } + }; + static int func_type = 0, display_count = 70; + ImGui::Separator(); + ImGui::PushItemWidth(100); ImGui::Combo("func", &func_type, "Sin\0Saw\0"); ImGui::PopItemWidth(); + ImGui::SameLine(); + ImGui::SliderInt("Sample count", &display_count, 1, 500); + float (*func)(void*, int) = (func_type == 0) ? Funcs::Sin : Funcs::Saw; + ImGui::PlotLines("Lines", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0,80)); + ImGui::PlotHistogram("Histogram", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0,80)); + ImGui::Separator(); + + // Animate a simple progress bar + static float progress = 0.0f, progress_dir = 1.0f; + if (animate) + { + progress += progress_dir * 0.4f * ImGui::GetIO().DeltaTime; + if (progress >= +1.1f) { progress = +1.1f; progress_dir *= -1.0f; } + if (progress <= -0.1f) { progress = -0.1f; progress_dir *= -1.0f; } + } + + // Typically we would use ImVec2(-1.0f,0.0f) to use all available width, or ImVec2(width,0.0f) for a specified width. ImVec2(0.0f,0.0f) uses ItemWidth. + ImGui::ProgressBar(progress, ImVec2(0.0f,0.0f)); + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); + ImGui::Text("Progress Bar"); + + float progress_saturated = (progress < 0.0f) ? 0.0f : (progress > 1.0f) ? 1.0f : progress; + char buf[32]; + sprintf(buf, "%d/%d", (int)(progress_saturated*1753), 1753); + ImGui::ProgressBar(progress, ImVec2(0.f,0.f), buf); + } + + if (ImGui::CollapsingHeader("Layout")) + { + if (ImGui::TreeNode("Child regions")) + { + ImGui::Text("Without border"); + static int line = 50; + bool goto_line = ImGui::Button("Goto"); + ImGui::SameLine(); + ImGui::PushItemWidth(100); + goto_line |= ImGui::InputInt("##Line", &line, 0, 0, ImGuiInputTextFlags_EnterReturnsTrue); + ImGui::PopItemWidth(); + ImGui::BeginChild("Sub1", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f,300), false, ImGuiWindowFlags_HorizontalScrollbar); + for (int i = 0; i < 100; i++) + { + ImGui::Text("%04d: scrollable region", i); + if (goto_line && line == i) + ImGui::SetScrollHere(); + } + if (goto_line && line >= 100) + ImGui::SetScrollHere(); + ImGui::EndChild(); + + ImGui::SameLine(); + + ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, 5.0f); + ImGui::BeginChild("Sub2", ImVec2(0,300), true); + ImGui::Text("With border"); + ImGui::Columns(2); + for (int i = 0; i < 100; i++) + { + if (i == 50) + ImGui::NextColumn(); + char buf[32]; + sprintf(buf, "%08x", i*5731); + ImGui::Button(buf, ImVec2(-1.0f, 0.0f)); + } + ImGui::EndChild(); + ImGui::PopStyleVar(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Widgets Width")) + { + static float f = 0.0f; + ImGui::Text("PushItemWidth(100)"); + ImGui::SameLine(); ShowHelpMarker("Fixed width."); + ImGui::PushItemWidth(100); + ImGui::DragFloat("float##1", &f); + ImGui::PopItemWidth(); + + ImGui::Text("PushItemWidth(GetWindowWidth() * 0.5f)"); + ImGui::SameLine(); ShowHelpMarker("Half of window width."); + ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f); + ImGui::DragFloat("float##2", &f); + ImGui::PopItemWidth(); + + ImGui::Text("PushItemWidth(GetContentRegionAvailWidth() * 0.5f)"); + ImGui::SameLine(); ShowHelpMarker("Half of available width.\n(~ right-cursor_pos)\n(works within a column set)"); + ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth() * 0.5f); + ImGui::DragFloat("float##3", &f); + ImGui::PopItemWidth(); + + ImGui::Text("PushItemWidth(-100)"); + ImGui::SameLine(); ShowHelpMarker("Align to right edge minus 100"); + ImGui::PushItemWidth(-100); + ImGui::DragFloat("float##4", &f); + ImGui::PopItemWidth(); + + ImGui::Text("PushItemWidth(-1)"); + ImGui::SameLine(); ShowHelpMarker("Align to right edge"); + ImGui::PushItemWidth(-1); + ImGui::DragFloat("float##5", &f); + ImGui::PopItemWidth(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Basic Horizontal Layout")) + { + ImGui::TextWrapped("(Use ImGui::SameLine() to keep adding items to the right of the preceeding item)"); + + // Text + ImGui::Text("Two items: Hello"); ImGui::SameLine(); + ImGui::TextColored(ImVec4(1,1,0,1), "Sailor"); + + // Adjust spacing + ImGui::Text("More spacing: Hello"); ImGui::SameLine(0, 20); + ImGui::TextColored(ImVec4(1,1,0,1), "Sailor"); + + // Button + ImGui::AlignFirstTextHeightToWidgets(); + ImGui::Text("Normal buttons"); ImGui::SameLine(); + ImGui::Button("Banana"); ImGui::SameLine(); + ImGui::Button("Apple"); ImGui::SameLine(); + ImGui::Button("Corniflower"); + + // Button + ImGui::Text("Small buttons"); ImGui::SameLine(); + ImGui::SmallButton("Like this one"); ImGui::SameLine(); + ImGui::Text("can fit within a text block."); + + // Aligned to arbitrary position. Easy/cheap column. + ImGui::Text("Aligned"); + ImGui::SameLine(150); ImGui::Text("x=150"); + ImGui::SameLine(300); ImGui::Text("x=300"); + ImGui::Text("Aligned"); + ImGui::SameLine(150); ImGui::SmallButton("x=150"); + ImGui::SameLine(300); ImGui::SmallButton("x=300"); + + // Checkbox + static bool c1=false,c2=false,c3=false,c4=false; + ImGui::Checkbox("My", &c1); ImGui::SameLine(); + ImGui::Checkbox("Tailor", &c2); ImGui::SameLine(); + ImGui::Checkbox("Is", &c3); ImGui::SameLine(); + ImGui::Checkbox("Rich", &c4); + + // Various + static float f0=1.0f, f1=2.0f, f2=3.0f; + ImGui::PushItemWidth(80); + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD" }; + static int item = -1; + ImGui::Combo("Combo", &item, items, IM_ARRAYSIZE(items)); ImGui::SameLine(); + ImGui::SliderFloat("X", &f0, 0.0f,5.0f); ImGui::SameLine(); + ImGui::SliderFloat("Y", &f1, 0.0f,5.0f); ImGui::SameLine(); + ImGui::SliderFloat("Z", &f2, 0.0f,5.0f); + ImGui::PopItemWidth(); + + ImGui::PushItemWidth(80); + ImGui::Text("Lists:"); + static int selection[4] = { 0, 1, 2, 3 }; + for (int i = 0; i < 4; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::ListBox("", &selection[i], items, IM_ARRAYSIZE(items)); + ImGui::PopID(); + //if (ImGui::IsItemHovered()) ImGui::SetTooltip("ListBox %d hovered", i); + } + ImGui::PopItemWidth(); + + // Dummy + ImVec2 sz(30,30); + ImGui::Button("A", sz); ImGui::SameLine(); + ImGui::Dummy(sz); ImGui::SameLine(); + ImGui::Button("B", sz); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Groups")) + { + ImGui::TextWrapped("(Using ImGui::BeginGroup()/EndGroup() to layout items. BeginGroup() basically locks the horizontal position. EndGroup() bundles the whole group so that you can use functions such as IsItemHovered() on it.)"); + ImGui::BeginGroup(); + { + ImGui::BeginGroup(); + ImGui::Button("AAA"); + ImGui::SameLine(); + ImGui::Button("BBB"); + ImGui::SameLine(); + ImGui::BeginGroup(); + ImGui::Button("CCC"); + ImGui::Button("DDD"); + ImGui::EndGroup(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Group hovered"); + ImGui::SameLine(); + ImGui::Button("EEE"); + ImGui::EndGroup(); + } + // Capture the group size and create widgets using the same size + ImVec2 size = ImGui::GetItemRectSize(); + const float values[5] = { 0.5f, 0.20f, 0.80f, 0.60f, 0.25f }; + ImGui::PlotHistogram("##values", values, IM_ARRAYSIZE(values), 0, NULL, 0.0f, 1.0f, size); + + ImGui::Button("ACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f,size.y)); + ImGui::SameLine(); + ImGui::Button("REACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f,size.y)); + ImGui::EndGroup(); + ImGui::SameLine(); + + ImGui::Button("LEVERAGE\nBUZZWORD", size); + ImGui::SameLine(); + + ImGui::ListBoxHeader("List", size); + ImGui::Selectable("Selected", true); + ImGui::Selectable("Not Selected", false); + ImGui::ListBoxFooter(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Text Baseline Alignment")) + { + ImGui::TextWrapped("(This is testing the vertical alignment that occurs on text to keep it at the same baseline as widgets. Lines only composed of text or \"small\" widgets fit in less vertical spaces than lines with normal widgets)"); + + ImGui::Text("One\nTwo\nThree"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("Banana"); + + ImGui::Text("Banana"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("One\nTwo\nThree"); + + ImGui::Button("HOP"); ImGui::SameLine(); + ImGui::Text("Banana"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("Banana"); + + ImGui::Button("HOP"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("Banana"); + + ImGui::Button("TEST"); ImGui::SameLine(); + ImGui::Text("TEST"); ImGui::SameLine(); + ImGui::SmallButton("TEST"); + + ImGui::AlignFirstTextHeightToWidgets(); // If your line starts with text, call this to align it to upcoming widgets. + ImGui::Text("Text aligned to Widget"); ImGui::SameLine(); + ImGui::Button("Widget"); ImGui::SameLine(); + ImGui::Text("Widget"); ImGui::SameLine(); + ImGui::SmallButton("Widget"); + + // Tree + const float spacing = ImGui::GetStyle().ItemInnerSpacing.x; + ImGui::Button("Button##1"); + ImGui::SameLine(0.0f, spacing); + if (ImGui::TreeNode("Node##1")) { for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); } // Dummy tree data + + ImGui::AlignFirstTextHeightToWidgets(); // Vertically align text node a bit lower so it'll be vertically centered with upcoming widget. Otherwise you can use SmallButton (smaller fit). + bool node_open = ImGui::TreeNode("Node##2"); // Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add child content. + ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##2"); + if (node_open) { for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); } // Dummy tree data + + // Bullet + ImGui::Button("Button##3"); + ImGui::SameLine(0.0f, spacing); + ImGui::BulletText("Bullet text"); + + ImGui::AlignFirstTextHeightToWidgets(); + ImGui::BulletText("Node"); + ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##4"); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Scrolling")) + { + ImGui::TextWrapped("(Use SetScrollHere() or SetScrollFromPosY() to scroll to a given position.)"); + static bool track = true; + static int track_line = 50, scroll_to_px = 200; + ImGui::Checkbox("Track", &track); + ImGui::PushItemWidth(100); + ImGui::SameLine(130); track |= ImGui::DragInt("##line", &track_line, 0.25f, 0, 99, "Line %.0f"); + bool scroll_to = ImGui::Button("Scroll To"); + ImGui::SameLine(130); scroll_to |= ImGui::DragInt("##pos_y", &scroll_to_px, 1.00f, 0, 9999, "y = %.0f px"); + ImGui::PopItemWidth(); + if (scroll_to) track = false; + + for (int i = 0; i < 5; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::BeginGroup(); + ImGui::Text("%s", i == 0 ? "Top" : i == 1 ? "25%" : i == 2 ? "Center" : i == 3 ? "75%" : "Bottom"); + ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(ImGui::GetWindowWidth() * 0.17f, 200.0f), true); + if (scroll_to) + ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + scroll_to_px, i * 0.25f); + for (int line = 0; line < 100; line++) + { + if (track && line == track_line) + { + ImGui::TextColored(ImColor(255,255,0), "Line %d", line); + ImGui::SetScrollHere(i * 0.25f); // 0.0f:top, 0.5f:center, 1.0f:bottom + } + else + { + ImGui::Text("Line %d", line); + } + } + ImGui::EndChild(); + ImGui::EndGroup(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Horizontal Scrolling")) + { + ImGui::Bullet(); ImGui::TextWrapped("Horizontal scrolling for a window has to be enabled explicitly via the ImGuiWindowFlags_HorizontalScrollbar flag."); + ImGui::Bullet(); ImGui::TextWrapped("You may want to explicitly specify content width by calling SetNextWindowContentWidth() before Begin()."); + static int lines = 7; + ImGui::SliderInt("Lines", &lines, 1, 15); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2.0f, 1.0f)); + ImGui::BeginChild("scrolling", ImVec2(0, ImGui::GetItemsLineHeightWithSpacing()*7 + 30), true, ImGuiWindowFlags_HorizontalScrollbar); + for (int line = 0; line < lines; line++) + { + // Display random stuff + int num_buttons = 10 + ((line & 1) ? line * 9 : line * 3); + for (int n = 0; n < num_buttons; n++) + { + if (n > 0) ImGui::SameLine(); + ImGui::PushID(n + line * 1000); + char num_buf[16]; + const char* label = (!(n%15)) ? "FizzBuzz" : (!(n%3)) ? "Fizz" : (!(n%5)) ? "Buzz" : (sprintf(num_buf, "%d", n), num_buf); + float hue = n*0.05f; + ImGui::PushStyleColor(ImGuiCol_Button, ImColor::HSV(hue, 0.6f, 0.6f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImColor::HSV(hue, 0.7f, 0.7f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImColor::HSV(hue, 0.8f, 0.8f)); + ImGui::Button(label, ImVec2(40.0f + sinf((float)(line + n)) * 20.0f, 0.0f)); + ImGui::PopStyleColor(3); + ImGui::PopID(); + } + } + ImGui::EndChild(); + ImGui::PopStyleVar(2); + float scroll_x_delta = 0.0f; + ImGui::SmallButton("<<"); if (ImGui::IsItemActive()) scroll_x_delta = -ImGui::GetIO().DeltaTime * 1000.0f; + ImGui::SameLine(); ImGui::Text("Scroll from code"); ImGui::SameLine(); + ImGui::SmallButton(">>"); if (ImGui::IsItemActive()) scroll_x_delta = +ImGui::GetIO().DeltaTime * 1000.0f; + if (scroll_x_delta != 0.0f) + { + ImGui::BeginChild("scrolling"); // Demonstrate a trick: you can use Begin to set yourself in the context of another window (here we are already out of your child window) + ImGui::SetScrollX(ImGui::GetScrollX() + scroll_x_delta); + ImGui::End(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Clipping")) + { + static ImVec2 size(100, 100), offset(50, 20); + ImGui::TextWrapped("On a per-widget basis we are occasionally clipping text CPU-side if it won't fit in its frame. Otherwise we are doing coarser clipping + passing a scissor rectangle to the renderer. The system is designed to try minimizing both execution and CPU/GPU rendering cost."); + ImGui::DragFloat2("size", (float*)&size, 0.5f, 0.0f, 200.0f, "%.0f"); + ImGui::TextWrapped("(Click and drag)"); + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImVec4 clip_rect(pos.x, pos.y, pos.x+size.x, pos.y+size.y); + ImGui::InvisibleButton("##dummy", size); + if (ImGui::IsItemActive() && ImGui::IsMouseDragging()) { offset.x += ImGui::GetIO().MouseDelta.x; offset.y += ImGui::GetIO().MouseDelta.y; } + ImGui::GetWindowDrawList()->AddRectFilled(pos, ImVec2(pos.x+size.x,pos.y+size.y), ImColor(90,90,120,255)); + ImGui::GetWindowDrawList()->AddText(ImGui::GetFont(), ImGui::GetFontSize()*2.0f, ImVec2(pos.x+offset.x,pos.y+offset.y), ImColor(255,255,255,255), "Line 1 hello\nLine 2 clip me!", NULL, 0.0f, &clip_rect); + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Popups & Modal windows")) + { + if (ImGui::TreeNode("Popups")) + { + ImGui::TextWrapped("When a popup is active, it inhibits interacting with windows that are behind the popup. Clicking outside the popup closes it."); + + static int selected_fish = -1; + const char* names[] = { "Bream", "Haddock", "Mackerel", "Pollock", "Tilefish" }; + static bool toggles[] = { true, false, false, false, false }; + + if (ImGui::Button("Select..")) + ImGui::OpenPopup("select"); + ImGui::SameLine(); + ImGui::Text(selected_fish == -1 ? "" : names[selected_fish]); + if (ImGui::BeginPopup("select")) + { + ImGui::Text("Aquarium"); + ImGui::Separator(); + for (int i = 0; i < IM_ARRAYSIZE(names); i++) + if (ImGui::Selectable(names[i])) + selected_fish = i; + ImGui::EndPopup(); + } + + if (ImGui::Button("Toggle..")) + ImGui::OpenPopup("toggle"); + if (ImGui::BeginPopup("toggle")) + { + for (int i = 0; i < IM_ARRAYSIZE(names); i++) + ImGui::MenuItem(names[i], "", &toggles[i]); + if (ImGui::BeginMenu("Sub-menu")) + { + ImGui::MenuItem("Click me"); + ImGui::EndMenu(); + } + + ImGui::Separator(); + ImGui::Text("Tooltip here"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("I am a tooltip over a popup"); + + if (ImGui::Button("Stacked Popup")) + ImGui::OpenPopup("another popup"); + if (ImGui::BeginPopup("another popup")) + { + for (int i = 0; i < IM_ARRAYSIZE(names); i++) + ImGui::MenuItem(names[i], "", &toggles[i]); + if (ImGui::BeginMenu("Sub-menu")) + { + ImGui::MenuItem("Click me"); + ImGui::EndMenu(); + } + ImGui::EndPopup(); + } + ImGui::EndPopup(); + } + + if (ImGui::Button("Popup Menu..")) + ImGui::OpenPopup("popup from button"); + if (ImGui::BeginPopup("popup from button")) + { + ShowExampleMenuFile(); + ImGui::EndPopup(); + } + + ImGui::Spacing(); + ImGui::TextWrapped("Below we are testing adding menu items to a regular window. It's rather unusual but should work!"); + ImGui::Separator(); + // NB: As a quirk in this very specific example, we want to differentiate the parent of this menu from the parent of the various popup menus above. + // To do so we are encloding the items in a PushID()/PopID() block to make them two different menusets. If we don't, opening any popup above and hovering our menu here + // would open it. This is because once a menu is active, we allow to switch to a sibling menu by just hovering on it, which is the desired behavior for regular menus. + ImGui::PushID("foo"); + ImGui::MenuItem("Menu item", "CTRL+M"); + if (ImGui::BeginMenu("Menu inside a regular window")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + ImGui::PopID(); + ImGui::Separator(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Context menus")) + { + static float value = 0.5f; + ImGui::Text("Value = %.3f (<-- right-click here)", value); + if (ImGui::BeginPopupContextItem("item context menu")) + { + if (ImGui::Selectable("Set to zero")) value = 0.0f; + if (ImGui::Selectable("Set to PI")) value = 3.1415f; + ImGui::EndPopup(); + } + + static ImVec4 color = ImColor(0.8f, 0.5f, 1.0f, 1.0f); + ImGui::ColorButton(color); + if (ImGui::BeginPopupContextItem("color context menu")) + { + ImGui::Text("Edit color"); + ImGui::ColorEdit3("##edit", (float*)&color); + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + ImGui::SameLine(); ImGui::Text("(<-- right-click here)"); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Modals")) + { + ImGui::TextWrapped("Modal windows are like popups but the user cannot close them by clicking outside the window."); + + if (ImGui::Button("Delete..")) + ImGui::OpenPopup("Delete?"); + if (ImGui::BeginPopupModal("Delete?", NULL, ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGui::Text("All those beautiful files will be deleted.\nThis operation cannot be undone!\n\n"); + ImGui::Separator(); + + //static int dummy_i = 0; + //ImGui::Combo("Combo", &dummy_i, "Delete\0Delete harder\0"); + + static bool dont_ask_me_next_time = false; + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0)); + ImGui::Checkbox("Don't ask me next time", &dont_ask_me_next_time); + ImGui::PopStyleVar(); + + if (ImGui::Button("OK", ImVec2(120,0))) { ImGui::CloseCurrentPopup(); } + ImGui::SameLine(); + if (ImGui::Button("Cancel", ImVec2(120,0))) { ImGui::CloseCurrentPopup(); } + ImGui::EndPopup(); + } + + if (ImGui::Button("Stacked modals..")) + ImGui::OpenPopup("Stacked 1"); + if (ImGui::BeginPopupModal("Stacked 1")) + { + ImGui::Text("Hello from Stacked The First"); + + if (ImGui::Button("Another one..")) + ImGui::OpenPopup("Stacked 2"); + if (ImGui::BeginPopupModal("Stacked 2")) + { + ImGui::Text("Hello from Stacked The Second"); + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Columns")) + { + // Basic columns + if (ImGui::TreeNode("Basic")) + { + ImGui::Columns(4, "mycolumns"); + ImGui::Separator(); + ImGui::Text("ID"); ImGui::NextColumn(); + ImGui::Text("Name"); ImGui::NextColumn(); + ImGui::Text("Path"); ImGui::NextColumn(); + ImGui::Text("Flags"); ImGui::NextColumn(); + ImGui::Separator(); + const char* names[3] = { "One", "Two", "Three" }; + const char* paths[3] = { "/path/one", "/path/two", "/path/three" }; + static int selected = -1; + for (int i = 0; i < 3; i++) + { + char label[32]; + sprintf(label, "%04d", i); + if (ImGui::Selectable(label, selected == i, ImGuiSelectableFlags_SpanAllColumns)) + selected = i; + ImGui::NextColumn(); + ImGui::Text(names[i]); ImGui::NextColumn(); + ImGui::Text(paths[i]); ImGui::NextColumn(); + ImGui::Text("...."); ImGui::NextColumn(); + } + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + + // Scrolling columns + /* + if (ImGui::TreeNode("Scrolling")) + { + ImGui::BeginChild("##header", ImVec2(0, ImGui::GetTextLineHeightWithSpacing()+ImGui::GetStyle().ItemSpacing.y)); + ImGui::Columns(3); + ImGui::Text("ID"); ImGui::NextColumn(); + ImGui::Text("Name"); ImGui::NextColumn(); + ImGui::Text("Path"); ImGui::NextColumn(); + ImGui::Columns(1); + ImGui::Separator(); + ImGui::EndChild(); + ImGui::BeginChild("##scrollingregion", ImVec2(0, 60)); + ImGui::Columns(3); + for (int i = 0; i < 10; i++) + { + ImGui::Text("%04d", i); ImGui::NextColumn(); + ImGui::Text("Foobar"); ImGui::NextColumn(); + ImGui::Text("/path/foobar/%04d/", i); ImGui::NextColumn(); + } + ImGui::Columns(1); + ImGui::EndChild(); + ImGui::TreePop(); + } + */ + + // Create multiple items in a same cell before switching to next column + if (ImGui::TreeNode("Mixed items")) + { + ImGui::Columns(3, "mixed"); + ImGui::Separator(); + + ImGui::Text("Hello"); + ImGui::Button("Banana"); + ImGui::NextColumn(); + + ImGui::Text("ImGui"); + ImGui::Button("Apple"); + static float foo = 1.0f; + ImGui::InputFloat("red", &foo, 0.05f, 0, 3); + ImGui::Text("An extra line here."); + ImGui::NextColumn(); + + ImGui::Text("Sailor"); + ImGui::Button("Corniflower"); + static float bar = 1.0f; + ImGui::InputFloat("blue", &bar, 0.05f, 0, 3); + ImGui::NextColumn(); + + if (ImGui::CollapsingHeader("Category A")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); + if (ImGui::CollapsingHeader("Category B")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); + if (ImGui::CollapsingHeader("Category C")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + + // Word wrapping + if (ImGui::TreeNode("Word-wrapping")) + { + ImGui::Columns(2, "word-wrapping"); + ImGui::Separator(); + ImGui::TextWrapped("The quick brown fox jumps over the lazy dog."); + ImGui::TextWrapped("Hello Left"); + ImGui::NextColumn(); + ImGui::TextWrapped("The quick brown fox jumps over the lazy dog."); + ImGui::TextWrapped("Hello Right"); + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Borders")) + { + static bool h_borders = true; + static bool v_borders = true; + ImGui::Checkbox("horizontal", &h_borders); + ImGui::SameLine(); + ImGui::Checkbox("vertical", &v_borders); + ImGui::Columns(4, NULL, v_borders); + if (h_borders) ImGui::Separator(); + for (int i = 0; i < 8; i++) + { + ImGui::Text("%c%c%c", 'a'+i, 'a'+i, 'a'+i); + ImGui::NextColumn(); + } + ImGui::Columns(1); + if (h_borders) ImGui::Separator(); + ImGui::TreePop(); + } + + bool node_open = ImGui::TreeNode("Tree within single cell"); + ImGui::SameLine(); ShowHelpMarker("NB: Tree node must be poped before ending the cell.\nThere's no storage of state per-cell."); + if (node_open) + { + ImGui::Columns(2, "tree items"); + ImGui::Separator(); + if (ImGui::TreeNode("Hello")) { ImGui::BulletText("Sailor"); ImGui::TreePop(); } ImGui::NextColumn(); + if (ImGui::TreeNode("Bonjour")) { ImGui::BulletText("Marin"); ImGui::TreePop(); } ImGui::NextColumn(); + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Filtering")) + { + static ImGuiTextFilter filter; + ImGui::Text("Filter usage:\n" + " \"\" display all lines\n" + " \"xxx\" display lines containing \"xxx\"\n" + " \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n" + " \"-xxx\" hide lines containing \"xxx\""); + filter.Draw(); + const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" }; + for (int i = 0; i < IM_ARRAYSIZE(lines); i++) + if (filter.PassFilter(lines[i])) + ImGui::BulletText("%s", lines[i]); + } + + if (ImGui::CollapsingHeader("Keyboard, Mouse & Focus")) + { + if (ImGui::TreeNode("Tabbing")) + { + ImGui::Text("Use TAB/SHIFT+TAB to cycle through keyboard editable fields."); + static char buf[32] = "dummy"; + ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); + ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); + ImGui::InputText("3", buf, IM_ARRAYSIZE(buf)); + ImGui::PushAllowKeyboardFocus(false); + ImGui::InputText("4 (tab skip)", buf, IM_ARRAYSIZE(buf)); + //ImGui::SameLine(); ShowHelperMarker("Use ImGui::PushAllowKeyboardFocus(bool)\nto disable tabbing through certain widgets."); + ImGui::PopAllowKeyboardFocus(); + ImGui::InputText("5", buf, IM_ARRAYSIZE(buf)); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Focus from code")) + { + bool focus_1 = ImGui::Button("Focus on 1"); ImGui::SameLine(); + bool focus_2 = ImGui::Button("Focus on 2"); ImGui::SameLine(); + bool focus_3 = ImGui::Button("Focus on 3"); + int has_focus = 0; + static char buf[128] = "click on a button to set focus"; + + if (focus_1) ImGui::SetKeyboardFocusHere(); + ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); + if (ImGui::IsItemActive()) has_focus = 1; + + if (focus_2) ImGui::SetKeyboardFocusHere(); + ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); + if (ImGui::IsItemActive()) has_focus = 2; + + ImGui::PushAllowKeyboardFocus(false); + if (focus_3) ImGui::SetKeyboardFocusHere(); + ImGui::InputText("3 (tab skip)", buf, IM_ARRAYSIZE(buf)); + if (ImGui::IsItemActive()) has_focus = 3; + ImGui::PopAllowKeyboardFocus(); + if (has_focus) + ImGui::Text("Item with focus: %d", has_focus); + else + ImGui::Text("Item with focus: "); + ImGui::TextWrapped("Cursor & selection are preserved when refocusing last used item in code."); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Dragging")) + { + ImGui::TextWrapped("You can use ImGui::GetItemActiveDragDelta() to query for the dragged amount on any widget."); + ImGui::Button("Drag Me"); + if (ImGui::IsItemActive()) + { + // Draw a line between the button and the mouse cursor + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + draw_list->PushClipRectFullScreen(); + draw_list->AddLine(ImGui::CalcItemRectClosestPoint(ImGui::GetIO().MousePos, true, -2.0f), ImGui::GetIO().MousePos, ImColor(ImGui::GetStyle().Colors[ImGuiCol_Button]), 4.0f); + draw_list->PopClipRect(); + ImVec2 value_raw = ImGui::GetMouseDragDelta(0, 0.0f); + ImVec2 value_with_lock_threshold = ImGui::GetMouseDragDelta(0); + ImVec2 mouse_delta = ImGui::GetIO().MouseDelta; + ImGui::SameLine(); ImGui::Text("Raw (%.1f, %.1f), WithLockThresold (%.1f, %.1f), MouseDelta (%.1f, %.1f)", value_raw.x, value_raw.y, value_with_lock_threshold.x, value_with_lock_threshold.y, mouse_delta.x, mouse_delta.y); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Keyboard & Mouse State")) + { + ImGuiIO& io = ImGui::GetIO(); + + ImGui::Text("MousePos: (%g, %g)", io.MousePos.x, io.MousePos.y); + ImGui::Text("Mouse down:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (io.MouseDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); } + ImGui::Text("Mouse clicked:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } + ImGui::Text("Mouse dbl-clicked:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseDoubleClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } + ImGui::Text("Mouse released:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseReleased(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } + ImGui::Text("MouseWheel: %.1f", io.MouseWheel); + + ImGui::Text("Keys down:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (io.KeysDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("%d (%.02f secs)", i, io.KeysDownDuration[i]); } + ImGui::Text("Keys pressed:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyPressed(i)) { ImGui::SameLine(); ImGui::Text("%d", i); } + ImGui::Text("Keys release:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyReleased(i)) { ImGui::SameLine(); ImGui::Text("%d", i); } + ImGui::Text("KeyMods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : ""); + + ImGui::Text("WantCaptureMouse: %s", io.WantCaptureMouse ? "true" : "false"); + ImGui::Text("WantCaptureKeyboard: %s", io.WantCaptureKeyboard ? "true" : "false"); + ImGui::Text("WantTextInput: %s", io.WantTextInput ? "true" : "false"); + + ImGui::Button("Hovering me sets the\nkeyboard capture flag"); + if (ImGui::IsItemHovered()) + ImGui::CaptureKeyboardFromApp(true); + ImGui::SameLine(); + ImGui::Button("Holding me clears the\nthe keyboard capture flag"); + if (ImGui::IsItemActive()) + ImGui::CaptureKeyboardFromApp(false); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Mouse cursors")) + { + ImGui::TextWrapped("Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. You can also set io.MouseDrawCursor to ask ImGui to render the cursor for you in software."); + ImGui::Checkbox("io.MouseDrawCursor", &ImGui::GetIO().MouseDrawCursor); + ImGui::Text("Hover to see mouse cursors:"); + for (int i = 0; i < ImGuiMouseCursor_Count_; i++) + { + char label[32]; + sprintf(label, "Mouse cursor %d", i); + ImGui::Bullet(); ImGui::Selectable(label, false); + if (ImGui::IsItemHovered()) + ImGui::SetMouseCursor(i); + } + ImGui::TreePop(); + } + } + + ImGui::End(); +} + +void ImGui::ShowStyleEditor(ImGuiStyle* ref) +{ + ImGuiStyle& style = ImGui::GetStyle(); + + // You can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it compares to the default style) + const ImGuiStyle default_style; // Default style + if (ImGui::Button("Revert Style")) + style = ref ? *ref : default_style; + + if (ref) + { + ImGui::SameLine(); + if (ImGui::Button("Save Style")) + *ref = style; + } + + ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.55f); + + if (ImGui::TreeNode("Rendering")) + { + ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines); + ImGui::Checkbox("Anti-aliased shapes", &style.AntiAliasedShapes); + ImGui::PushItemWidth(100); + ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, FLT_MAX, NULL, 2.0f); + if (style.CurveTessellationTol < 0.0f) style.CurveTessellationTol = 0.10f; + ImGui::DragFloat("Global Alpha", &style.Alpha, 0.005f, 0.20f, 1.0f, "%.2f"); // Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero. + ImGui::PopItemWidth(); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Sizes")) + { + ImGui::SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 16.0f, "%.0f"); + ImGui::SliderFloat("ChildWindowRounding", &style.ChildWindowRounding, 0.0f, 16.0f, "%.0f"); + ImGui::SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 16.0f, "%.0f"); + ImGui::SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f"); + ImGui::SliderFloat("IndentSpacing", &style.IndentSpacing, 0.0f, 30.0f, "%.0f"); + ImGui::SliderFloat("ScrollbarSize", &style.ScrollbarSize, 1.0f, 20.0f, "%.0f"); + ImGui::SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 16.0f, "%.0f"); + ImGui::SliderFloat("GrabMinSize", &style.GrabMinSize, 1.0f, 20.0f, "%.0f"); + ImGui::SliderFloat("GrabRounding", &style.GrabRounding, 0.0f, 16.0f, "%.0f"); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Colors")) + { + static int output_dest = 0; + static bool output_only_modified = false; + if (ImGui::Button("Copy Colors")) + { + if (output_dest == 0) + ImGui::LogToClipboard(); + else + ImGui::LogToTTY(); + ImGui::LogText("ImGuiStyle& style = ImGui::GetStyle();" IM_NEWLINE); + for (int i = 0; i < ImGuiCol_COUNT; i++) + { + const ImVec4& col = style.Colors[i]; + const char* name = ImGui::GetStyleColName(i); + if (!output_only_modified || memcmp(&col, (ref ? &ref->Colors[i] : &default_style.Colors[i]), sizeof(ImVec4)) != 0) + ImGui::LogText("style.Colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE, name, 22 - (int)strlen(name), "", col.x, col.y, col.z, col.w); + } + ImGui::LogFinish(); + } + ImGui::SameLine(); ImGui::PushItemWidth(120); ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY"); ImGui::PopItemWidth(); + ImGui::SameLine(); ImGui::Checkbox("Only Modified Fields", &output_only_modified); + + static ImGuiColorEditMode edit_mode = ImGuiColorEditMode_RGB; + ImGui::RadioButton("RGB", &edit_mode, ImGuiColorEditMode_RGB); + ImGui::SameLine(); + ImGui::RadioButton("HSV", &edit_mode, ImGuiColorEditMode_HSV); + ImGui::SameLine(); + ImGui::RadioButton("HEX", &edit_mode, ImGuiColorEditMode_HEX); + //ImGui::Text("Tip: Click on colored square to change edit mode."); + + static ImGuiTextFilter filter; + filter.Draw("Filter colors", 200); + + ImGui::BeginChild("#colors", ImVec2(0, 300), true, ImGuiWindowFlags_AlwaysVerticalScrollbar); + ImGui::PushItemWidth(-160); + ImGui::ColorEditMode(edit_mode); + for (int i = 0; i < ImGuiCol_COUNT; i++) + { + const char* name = ImGui::GetStyleColName(i); + if (!filter.PassFilter(name)) + continue; + ImGui::PushID(i); + ImGui::ColorEdit4(name, (float*)&style.Colors[i], true); + if (memcmp(&style.Colors[i], (ref ? &ref->Colors[i] : &default_style.Colors[i]), sizeof(ImVec4)) != 0) + { + ImGui::SameLine(); if (ImGui::Button("Revert")) style.Colors[i] = ref ? ref->Colors[i] : default_style.Colors[i]; + if (ref) { ImGui::SameLine(); if (ImGui::Button("Save")) ref->Colors[i] = style.Colors[i]; } + } + ImGui::PopID(); + } + ImGui::PopItemWidth(); + ImGui::EndChild(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Fonts", "Fonts (%d)", ImGui::GetIO().Fonts->Fonts.Size)) + { + ImGui::SameLine(); ShowHelpMarker("Tip: Load fonts with io.Fonts->AddFontFromFileTTF()\nbefore calling io.Fonts->GetTex* functions."); + ImFontAtlas* atlas = ImGui::GetIO().Fonts; + if (ImGui::TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight)) + { + ImGui::Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0,0), ImVec2(1,1), ImColor(255,255,255,255), ImColor(255,255,255,128)); + ImGui::TreePop(); + } + ImGui::PushItemWidth(100); + for (int i = 0; i < atlas->Fonts.Size; i++) + { + ImFont* font = atlas->Fonts[i]; + ImGui::BulletText("Font %d: \'%s\', %.2f px, %d glyphs", i, font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size); + ImGui::TreePush((void*)(intptr_t)i); + if (i > 0) { ImGui::SameLine(); if (ImGui::SmallButton("Set as default")) { atlas->Fonts[i] = atlas->Fonts[0]; atlas->Fonts[0] = font; } } + ImGui::PushFont(font); + ImGui::Text("The quick brown fox jumps over the lazy dog"); + ImGui::PopFont(); + if (ImGui::TreeNode("Details")) + { + ImGui::DragFloat("font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f"); // scale only this font + ImGui::Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent); + ImGui::Text("Fallback character: '%c' (%d)", font->FallbackChar, font->FallbackChar); + for (int config_i = 0; config_i < font->ConfigDataCount; config_i++) + { + ImFontConfig* cfg = &font->ConfigData[config_i]; + ImGui::BulletText("Input %d: \'%s\'\nOversample: (%d,%d), PixelSnapH: %d", config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH); + } + ImGui::TreePop(); + } + ImGui::TreePop(); + } + static float window_scale = 1.0f; + ImGui::DragFloat("this window scale", &window_scale, 0.005f, 0.3f, 2.0f, "%.1f"); // scale only this window + ImGui::DragFloat("global scale", &ImGui::GetIO().FontGlobalScale, 0.005f, 0.3f, 2.0f, "%.1f"); // scale everything + ImGui::PopItemWidth(); + ImGui::SetWindowFontScale(window_scale); + ImGui::TreePop(); + } + + ImGui::PopItemWidth(); +} + +static void ShowExampleAppMainMenuBar() +{ + if (ImGui::BeginMainMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Edit")) + { + if (ImGui::MenuItem("Undo", "CTRL+Z")) {} + if (ImGui::MenuItem("Redo", "CTRL+Y", false, false)) {} // Disabled item + ImGui::Separator(); + if (ImGui::MenuItem("Cut", "CTRL+X")) {} + if (ImGui::MenuItem("Copy", "CTRL+C")) {} + if (ImGui::MenuItem("Paste", "CTRL+V")) {} + ImGui::EndMenu(); + } + ImGui::EndMainMenuBar(); + } +} + +static void ShowExampleMenuFile() +{ + ImGui::MenuItem("(dummy menu)", NULL, false, false); + if (ImGui::MenuItem("New")) {} + if (ImGui::MenuItem("Open", "Ctrl+O")) {} + if (ImGui::BeginMenu("Open Recent")) + { + ImGui::MenuItem("fish_hat.c"); + ImGui::MenuItem("fish_hat.inl"); + ImGui::MenuItem("fish_hat.h"); + if (ImGui::BeginMenu("More..")) + { + ImGui::MenuItem("Hello"); + ImGui::MenuItem("Sailor"); + if (ImGui::BeginMenu("Recurse..")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + ImGui::EndMenu(); + } + ImGui::EndMenu(); + } + if (ImGui::MenuItem("Save", "Ctrl+S")) {} + if (ImGui::MenuItem("Save As..")) {} + ImGui::Separator(); + if (ImGui::BeginMenu("Options")) + { + static bool enabled = true; + ImGui::MenuItem("Enabled", "", &enabled); + ImGui::BeginChild("child", ImVec2(0, 60), true); + for (int i = 0; i < 10; i++) + ImGui::Text("Scrolling Text %d", i); + ImGui::EndChild(); + static float f = 0.5f; + static int n = 0; + ImGui::SliderFloat("Value", &f, 0.0f, 1.0f); + ImGui::InputFloat("Input", &f, 0.1f); + ImGui::Combo("Combo", &n, "Yes\0No\0Maybe\0\0"); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Colors")) + { + for (int i = 0; i < ImGuiCol_COUNT; i++) + ImGui::MenuItem(ImGui::GetStyleColName((ImGuiCol)i)); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Disabled", false)) // Disabled + { + IM_ASSERT(0); + } + if (ImGui::MenuItem("Checked", NULL, true)) {} + if (ImGui::MenuItem("Quit", "Alt+F4")) {} +} + +static void ShowExampleAppAutoResize(bool* p_open) +{ + if (!ImGui::Begin("Example: Auto-resizing window", p_open, ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGui::End(); + return; + } + + static int lines = 10; + ImGui::Text("Window will resize every-frame to the size of its content.\nNote that you probably don't want to query the window size to\noutput your content because that would create a feedback loop."); + ImGui::SliderInt("Number of lines", &lines, 1, 20); + for (int i = 0; i < lines; i++) + ImGui::Text("%*sThis is line %d", i*4, "", i); // Pad with space to extend size horizontally + ImGui::End(); +} + +static void ShowExampleAppConstrainedResize(bool* p_open) +{ + struct CustomConstraints // Helper functions to demonstrate programmatic constraints + { + static void Square(ImGuiSizeConstraintCallbackData* data) { data->DesiredSize = ImVec2(IM_MAX(data->DesiredSize.x, data->DesiredSize.y), IM_MAX(data->DesiredSize.x, data->DesiredSize.y)); } + static void Step(ImGuiSizeConstraintCallbackData* data) { float step = (float)(int)(intptr_t)data->UserData; data->DesiredSize = ImVec2((int)(data->DesiredSize.x / step + 0.5f) * step, (int)(data->DesiredSize.y / step + 0.5f) * step); } + }; + + static int type = 0; + if (type == 0) ImGui::SetNextWindowSizeConstraints(ImVec2(-1, 0), ImVec2(-1, FLT_MAX)); // Vertical only + if (type == 1) ImGui::SetNextWindowSizeConstraints(ImVec2(0, -1), ImVec2(FLT_MAX, -1)); // Horizontal only + if (type == 2) ImGui::SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(FLT_MAX, FLT_MAX)); // Width > 100, Height > 100 + if (type == 3) ImGui::SetNextWindowSizeConstraints(ImVec2(300, 0), ImVec2(400, FLT_MAX)); // Width 300-400 + if (type == 4) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Square); // Always Square + if (type == 5) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Step, (void*)100);// Fixed Step + + if (ImGui::Begin("Example: Constrained Resize", p_open)) + { + const char* desc[] = + { + "Resize vertical only", + "Resize horizontal only", + "Width > 100, Height > 100", + "Width 300-400", + "Custom: Always Square", + "Custom: Fixed Steps (100)", + }; + ImGui::Combo("Constraint", &type, desc, IM_ARRAYSIZE(desc)); + if (ImGui::Button("200x200")) ImGui::SetWindowSize(ImVec2(200,200)); ImGui::SameLine(); + if (ImGui::Button("500x500")) ImGui::SetWindowSize(ImVec2(500,500)); ImGui::SameLine(); + if (ImGui::Button("800x200")) ImGui::SetWindowSize(ImVec2(800,200)); + for (int i = 0; i < 10; i++) + ImGui::Text("Hello, sailor! Making this line long enough for the example."); + } + ImGui::End(); +} + +static void ShowExampleAppFixedOverlay(bool* p_open) +{ + ImGui::SetNextWindowPos(ImVec2(10,10)); + if (!ImGui::Begin("Example: Fixed Overlay", p_open, ImVec2(0,0), 0.3f, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings)) + { + ImGui::End(); + return; + } + ImGui::Text("Simple overlay\non the top-left side of the screen."); + ImGui::Separator(); + ImGui::Text("Mouse Position: (%.1f,%.1f)", ImGui::GetIO().MousePos.x, ImGui::GetIO().MousePos.y); + ImGui::End(); +} + +static void ShowExampleAppManipulatingWindowTitle(bool*) +{ + // By default, Windows are uniquely identified by their title. + // You can use the "##" and "###" markers to manipulate the display/ID. Read FAQ at the top of this file! + + // Using "##" to display same title but have unique identifier. + ImGui::SetNextWindowPos(ImVec2(100,100), ImGuiSetCond_FirstUseEver); + ImGui::Begin("Same title as another window##1"); + ImGui::Text("This is window 1.\nMy title is the same as window 2, but my identifier is unique."); + ImGui::End(); + + ImGui::SetNextWindowPos(ImVec2(100,200), ImGuiSetCond_FirstUseEver); + ImGui::Begin("Same title as another window##2"); + ImGui::Text("This is window 2.\nMy title is the same as window 1, but my identifier is unique."); + ImGui::End(); + + // Using "###" to display a changing title but keep a static identifier "AnimatedTitle" + char buf[128]; + sprintf(buf, "Animated title %c %d###AnimatedTitle", "|/-\\"[(int)(ImGui::GetTime()/0.25f)&3], rand()); + ImGui::SetNextWindowPos(ImVec2(100,300), ImGuiSetCond_FirstUseEver); + ImGui::Begin(buf); + ImGui::Text("This window has a changing title."); + ImGui::End(); +} + +static void ShowExampleAppCustomRendering(bool* p_open) +{ + ImGui::SetNextWindowSize(ImVec2(350,560), ImGuiSetCond_FirstUseEver); + if (!ImGui::Begin("Example: Custom rendering", p_open)) + { + ImGui::End(); + return; + } + + // Tip: If you do a lot of custom rendering, you probably want to use your own geometrical types and benefit of overloaded operators, etc. + // Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your types and ImVec2/ImVec4. + // ImGui defines overloaded operators but they are internal to imgui.cpp and not exposed outside (to avoid messing with your types) + // In this example we are not using the maths operators! + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + + // Primitives + ImGui::Text("Primitives"); + static float sz = 36.0f; + static ImVec4 col = ImVec4(1.0f,1.0f,0.4f,1.0f); + ImGui::DragFloat("Size", &sz, 0.2f, 2.0f, 72.0f, "%.0f"); + ImGui::ColorEdit3("Color", &col.x); + { + const ImVec2 p = ImGui::GetCursorScreenPos(); + const ImU32 col32 = ImColor(col); + float x = p.x + 4.0f, y = p.y + 4.0f, spacing = 8.0f; + for (int n = 0; n < 2; n++) + { + float thickness = (n == 0) ? 1.0f : 4.0f; + draw_list->AddCircle(ImVec2(x+sz*0.5f, y+sz*0.5f), sz*0.5f, col32, 20, thickness); x += sz+spacing; + draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 0.0f, ~0, thickness); x += sz+spacing; + draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f, ~0, thickness); x += sz+spacing; + draw_list->AddTriangle(ImVec2(x+sz*0.5f, y), ImVec2(x+sz,y+sz-0.5f), ImVec2(x,y+sz-0.5f), col32, thickness); x += sz+spacing; + draw_list->AddLine(ImVec2(x, y), ImVec2(x+sz, y ), col32, thickness); x += sz+spacing; + draw_list->AddLine(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, thickness); x += sz+spacing; + draw_list->AddLine(ImVec2(x, y), ImVec2(x, y+sz), col32, thickness); x += spacing; + draw_list->AddBezierCurve(ImVec2(x, y), ImVec2(x+sz*1.3f,y+sz*0.3f), ImVec2(x+sz-sz*1.3f,y+sz-sz*0.3f), ImVec2(x+sz, y+sz), col32, thickness); + x = p.x + 4; + y += sz+spacing; + } + draw_list->AddCircleFilled(ImVec2(x+sz*0.5f, y+sz*0.5f), sz*0.5f, col32, 32); x += sz+spacing; + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x+sz, y+sz), col32); x += sz+spacing; + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f); x += sz+spacing; + draw_list->AddTriangleFilled(ImVec2(x+sz*0.5f, y), ImVec2(x+sz,y+sz-0.5f), ImVec2(x,y+sz-0.5f), col32); x += sz+spacing; + draw_list->AddRectFilledMultiColor(ImVec2(x, y), ImVec2(x+sz, y+sz), ImColor(0,0,0), ImColor(255,0,0), ImColor(255,255,0), ImColor(0,255,0)); + ImGui::Dummy(ImVec2((sz+spacing)*8, (sz+spacing)*3)); + } + ImGui::Separator(); + { + static ImVector points; + static bool adding_line = false; + ImGui::Text("Canvas example"); + if (ImGui::Button("Clear")) points.clear(); + if (points.Size >= 2) { ImGui::SameLine(); if (ImGui::Button("Undo")) { points.pop_back(); points.pop_back(); } } + ImGui::Text("Left-click and drag to add lines,\nRight-click to undo"); + + // Here we are using InvisibleButton() as a convenience to 1) advance the cursor and 2) allows us to use IsItemHovered() + // However you can draw directly and poll mouse/keyboard by yourself. You can manipulate the cursor using GetCursorPos() and SetCursorPos(). + // If you only use the ImDrawList API, you can notify the owner window of its extends by using SetCursorPos(max). + ImVec2 canvas_pos = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates! + ImVec2 canvas_size = ImGui::GetContentRegionAvail(); // Resize canvas to what's available + if (canvas_size.x < 50.0f) canvas_size.x = 50.0f; + if (canvas_size.y < 50.0f) canvas_size.y = 50.0f; + draw_list->AddRectFilledMultiColor(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), ImColor(50,50,50), ImColor(50,50,60), ImColor(60,60,70), ImColor(50,50,60)); + draw_list->AddRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), ImColor(255,255,255)); + + bool adding_preview = false; + ImGui::InvisibleButton("canvas", canvas_size); + if (ImGui::IsItemHovered()) + { + ImVec2 mouse_pos_in_canvas = ImVec2(ImGui::GetIO().MousePos.x - canvas_pos.x, ImGui::GetIO().MousePos.y - canvas_pos.y); + if (!adding_line && ImGui::IsMouseClicked(0)) + { + points.push_back(mouse_pos_in_canvas); + adding_line = true; + } + if (adding_line) + { + adding_preview = true; + points.push_back(mouse_pos_in_canvas); + if (!ImGui::GetIO().MouseDown[0]) + adding_line = adding_preview = false; + } + if (ImGui::IsMouseClicked(1) && !points.empty()) + { + adding_line = adding_preview = false; + points.pop_back(); + points.pop_back(); + } + } + draw_list->PushClipRect(canvas_pos, ImVec2(canvas_pos.x+canvas_size.x, canvas_pos.y+canvas_size.y)); // clip lines within the canvas (if we resize it, etc.) + for (int i = 0; i < points.Size - 1; i += 2) + draw_list->AddLine(ImVec2(canvas_pos.x + points[i].x, canvas_pos.y + points[i].y), ImVec2(canvas_pos.x + points[i+1].x, canvas_pos.y + points[i+1].y), 0xFF00FFFF, 2.0f); + draw_list->PopClipRect(); + if (adding_preview) + points.pop_back(); + } + ImGui::End(); +} + +// For the console example, here we are using a more C++ like approach of declaring a class to hold the data and the functions. +struct ExampleAppConsole +{ + char InputBuf[256]; + ImVector Items; + bool ScrollToBottom; + ImVector History; + int HistoryPos; // -1: new line, 0..History.Size-1 browsing history. + ImVector Commands; + + ExampleAppConsole() + { + ClearLog(); + memset(InputBuf, 0, sizeof(InputBuf)); + HistoryPos = -1; + Commands.push_back("HELP"); + Commands.push_back("HISTORY"); + Commands.push_back("CLEAR"); + Commands.push_back("CLASSIFY"); // "classify" is here to provide an example of "C"+[tab] completing to "CL" and displaying matches. + AddLog("Welcome to ImGui!"); + } + ~ExampleAppConsole() + { + ClearLog(); + for (int i = 0; i < History.Size; i++) + free(History[i]); + } + + // Portable helpers + static int Stricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } + static int Strnicmp(const char* str1, const char* str2, int n) { int d = 0; while (n > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; n--; } return d; } + static char* Strdup(const char *str) { size_t len = strlen(str) + 1; void* buff = malloc(len); return (char*)memcpy(buff, (const void*)str, len); } + + void ClearLog() + { + for (int i = 0; i < Items.Size; i++) + free(Items[i]); + Items.clear(); + ScrollToBottom = true; + } + + void AddLog(const char* fmt, ...) IM_PRINTFARGS(2) + { + char buf[1024]; + va_list args; + va_start(args, fmt); + vsnprintf(buf, IM_ARRAYSIZE(buf), fmt, args); + buf[IM_ARRAYSIZE(buf)-1] = 0; + va_end(args); + Items.push_back(Strdup(buf)); + ScrollToBottom = true; + } + + void Draw(const char* title, bool* p_open) + { + ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiSetCond_FirstUseEver); + if (!ImGui::Begin(title, p_open)) + { + ImGui::End(); + return; + } + + ImGui::TextWrapped("This example implements a console with basic coloring, completion and history. A more elaborate implementation may want to store entries along with extra data such as timestamp, emitter, etc."); + ImGui::TextWrapped("Enter 'HELP' for help, press TAB to use text completion."); + + // TODO: display items starting from the bottom + + if (ImGui::SmallButton("Add Dummy Text")) { AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message here!"); } ImGui::SameLine(); + if (ImGui::SmallButton("Add Dummy Error")) AddLog("[error] something went wrong"); ImGui::SameLine(); + if (ImGui::SmallButton("Clear")) ClearLog(); ImGui::SameLine(); + if (ImGui::SmallButton("Scroll to bottom")) ScrollToBottom = true; + //static float t = 0.0f; if (ImGui::GetTime() - t > 0.02f) { t = ImGui::GetTime(); AddLog("Spam %f", t); } + + ImGui::Separator(); + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0)); + static ImGuiTextFilter filter; + filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180); + ImGui::PopStyleVar(); + ImGui::Separator(); + + ImGui::BeginChild("ScrollingRegion", ImVec2(0,-ImGui::GetItemsLineHeightWithSpacing()), false, ImGuiWindowFlags_HorizontalScrollbar); + if (ImGui::BeginPopupContextWindow()) + { + if (ImGui::Selectable("Clear")) ClearLog(); + ImGui::EndPopup(); + } + + // Display every line as a separate entry so we can change their color or add custom widgets. If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end()); + // NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping to only process visible items. + // You can seek and display only the lines that are visible using the ImGuiListClipper helper, if your elements are evenly spaced and you have cheap random access to the elements. + // To use the clipper we could replace the 'for (int i = 0; i < Items.Size; i++)' loop with: + // ImGuiListClipper clipper(Items.Size); + // while (clipper.Step()) + // for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + // However take note that you can not use this code as is if a filter is active because it breaks the 'cheap random-access' property. We would need random-access on the post-filtered list. + // A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices that passed the filtering test, recomputing this array when user changes the filter, + // and appending newly elements as they are inserted. This is left as a task to the user until we can manage to improve this example code! + // If your items are of variable size you may want to implement code similar to what ImGuiListClipper does. Or split your data into fixed height items to allow random-seeking into your list. + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4,1)); // Tighten spacing + for (int i = 0; i < Items.Size; i++) + { + const char* item = Items[i]; + if (!filter.PassFilter(item)) + continue; + ImVec4 col = ImVec4(1.0f,1.0f,1.0f,1.0f); // A better implementation may store a type per-item. For the sample let's just parse the text. + if (strstr(item, "[error]")) col = ImColor(1.0f,0.4f,0.4f,1.0f); + else if (strncmp(item, "# ", 2) == 0) col = ImColor(1.0f,0.78f,0.58f,1.0f); + ImGui::PushStyleColor(ImGuiCol_Text, col); + ImGui::TextUnformatted(item); + ImGui::PopStyleColor(); + } + if (ScrollToBottom) + ImGui::SetScrollHere(); + ScrollToBottom = false; + ImGui::PopStyleVar(); + ImGui::EndChild(); + ImGui::Separator(); + + // Command-line + if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), ImGuiInputTextFlags_EnterReturnsTrue|ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_CallbackHistory, &TextEditCallbackStub, (void*)this)) + { + char* input_end = InputBuf+strlen(InputBuf); + while (input_end > InputBuf && input_end[-1] == ' ') input_end--; *input_end = 0; + if (InputBuf[0]) + ExecCommand(InputBuf); + strcpy(InputBuf, ""); + } + + // Demonstrate keeping auto focus on the input box + if (ImGui::IsItemHovered() || (ImGui::IsRootWindowOrAnyChildFocused() && !ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0))) + ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget + + ImGui::End(); + } + + void ExecCommand(const char* command_line) + { + AddLog("# %s\n", command_line); + + // Insert into history. First find match and delete it so it can be pushed to the back. This isn't trying to be smart or optimal. + HistoryPos = -1; + for (int i = History.Size-1; i >= 0; i--) + if (Stricmp(History[i], command_line) == 0) + { + free(History[i]); + History.erase(History.begin() + i); + break; + } + History.push_back(Strdup(command_line)); + + // Process command + if (Stricmp(command_line, "CLEAR") == 0) + { + ClearLog(); + } + else if (Stricmp(command_line, "HELP") == 0) + { + AddLog("Commands:"); + for (int i = 0; i < Commands.Size; i++) + AddLog("- %s", Commands[i]); + } + else if (Stricmp(command_line, "HISTORY") == 0) + { + for (int i = History.Size >= 10 ? History.Size - 10 : 0; i < History.Size; i++) + AddLog("%3d: %s\n", i, History[i]); + } + else + { + AddLog("Unknown command: '%s'\n", command_line); + } + } + + static int TextEditCallbackStub(ImGuiTextEditCallbackData* data) // In C++11 you are better off using lambdas for this sort of forwarding callbacks + { + ExampleAppConsole* console = (ExampleAppConsole*)data->UserData; + return console->TextEditCallback(data); + } + + int TextEditCallback(ImGuiTextEditCallbackData* data) + { + //AddLog("cursor: %d, selection: %d-%d", data->CursorPos, data->SelectionStart, data->SelectionEnd); + switch (data->EventFlag) + { + case ImGuiInputTextFlags_CallbackCompletion: + { + // Example of TEXT COMPLETION + + // Locate beginning of current word + const char* word_end = data->Buf + data->CursorPos; + const char* word_start = word_end; + while (word_start > data->Buf) + { + const char c = word_start[-1]; + if (c == ' ' || c == '\t' || c == ',' || c == ';') + break; + word_start--; + } + + // Build a list of candidates + ImVector candidates; + for (int i = 0; i < Commands.Size; i++) + if (Strnicmp(Commands[i], word_start, (int)(word_end-word_start)) == 0) + candidates.push_back(Commands[i]); + + if (candidates.Size == 0) + { + // No match + AddLog("No match for \"%.*s\"!\n", (int)(word_end-word_start), word_start); + } + else if (candidates.Size == 1) + { + // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing + data->DeleteChars((int)(word_start-data->Buf), (int)(word_end-word_start)); + data->InsertChars(data->CursorPos, candidates[0]); + data->InsertChars(data->CursorPos, " "); + } + else + { + // Multiple matches. Complete as much as we can, so inputing "C" will complete to "CL" and display "CLEAR" and "CLASSIFY" + int match_len = (int)(word_end - word_start); + for (;;) + { + int c = 0; + bool all_candidates_matches = true; + for (int i = 0; i < candidates.Size && all_candidates_matches; i++) + if (i == 0) + c = toupper(candidates[i][match_len]); + else if (c != toupper(candidates[i][match_len])) + all_candidates_matches = false; + if (!all_candidates_matches) + break; + match_len++; + } + + if (match_len > 0) + { + data->DeleteChars((int)(word_start - data->Buf), (int)(word_end-word_start)); + data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len); + } + + // List matches + AddLog("Possible matches:\n"); + for (int i = 0; i < candidates.Size; i++) + AddLog("- %s\n", candidates[i]); + } + + break; + } + case ImGuiInputTextFlags_CallbackHistory: + { + // Example of HISTORY + const int prev_history_pos = HistoryPos; + if (data->EventKey == ImGuiKey_UpArrow) + { + if (HistoryPos == -1) + HistoryPos = History.Size - 1; + else if (HistoryPos > 0) + HistoryPos--; + } + else if (data->EventKey == ImGuiKey_DownArrow) + { + if (HistoryPos != -1) + if (++HistoryPos >= History.Size) + HistoryPos = -1; + } + + // A better implementation would preserve the data on the current input line along with cursor position. + if (prev_history_pos != HistoryPos) + { + data->CursorPos = data->SelectionStart = data->SelectionEnd = data->BufTextLen = (int)snprintf(data->Buf, (size_t)data->BufSize, "%s", (HistoryPos >= 0) ? History[HistoryPos] : ""); + data->BufDirty = true; + } + } + } + return 0; + } +}; + +static void ShowExampleAppConsole(bool* p_open) +{ + static ExampleAppConsole console; + console.Draw("Example: Console", p_open); +} + +// Usage: +// static ExampleAppLog my_log; +// my_log.AddLog("Hello %d world\n", 123); +// my_log.Draw("title"); +struct ExampleAppLog +{ + ImGuiTextBuffer Buf; + ImGuiTextFilter Filter; + ImVector LineOffsets; // Index to lines offset + bool ScrollToBottom; + + void Clear() { Buf.clear(); LineOffsets.clear(); } + + void AddLog(const char* fmt, ...) IM_PRINTFARGS(2) + { + int old_size = Buf.size(); + va_list args; + va_start(args, fmt); + Buf.appendv(fmt, args); + va_end(args); + for (int new_size = Buf.size(); old_size < new_size; old_size++) + if (Buf[old_size] == '\n') + LineOffsets.push_back(old_size); + ScrollToBottom = true; + } + + void Draw(const char* title, bool* p_open = NULL) + { + ImGui::SetNextWindowSize(ImVec2(500,400), ImGuiSetCond_FirstUseEver); + ImGui::Begin(title, p_open); + if (ImGui::Button("Clear")) Clear(); + ImGui::SameLine(); + bool copy = ImGui::Button("Copy"); + ImGui::SameLine(); + Filter.Draw("Filter", -100.0f); + ImGui::Separator(); + ImGui::BeginChild("scrolling", ImVec2(0,0), false, ImGuiWindowFlags_HorizontalScrollbar); + if (copy) ImGui::LogToClipboard(); + + if (Filter.IsActive()) + { + const char* buf_begin = Buf.begin(); + const char* line = buf_begin; + for (int line_no = 0; line != NULL; line_no++) + { + const char* line_end = (line_no < LineOffsets.Size) ? buf_begin + LineOffsets[line_no] : NULL; + if (Filter.PassFilter(line, line_end)) + ImGui::TextUnformatted(line, line_end); + line = line_end && line_end[1] ? line_end + 1 : NULL; + } + } + else + { + ImGui::TextUnformatted(Buf.begin()); + } + + if (ScrollToBottom) + ImGui::SetScrollHere(1.0f); + ScrollToBottom = false; + ImGui::EndChild(); + ImGui::End(); + } +}; + +static void ShowExampleAppLog(bool* p_open) +{ + static ExampleAppLog log; + + // Demo fill + static float last_time = -1.0f; + float time = ImGui::GetTime(); + if (time - last_time >= 0.3f) + { + const char* random_words[] = { "system", "info", "warning", "error", "fatal", "notice", "log" }; + log.AddLog("[%s] Hello, time is %.1f, rand() %d\n", random_words[rand() % IM_ARRAYSIZE(random_words)], time, (int)rand()); + last_time = time; + } + + log.Draw("Example: Log", p_open); +} + +static void ShowExampleAppLayout(bool* p_open) +{ + ImGui::SetNextWindowSize(ImVec2(500, 440), ImGuiSetCond_FirstUseEver); + if (ImGui::Begin("Example: Layout", p_open, ImGuiWindowFlags_MenuBar)) + { + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + if (ImGui::MenuItem("Close")) *p_open = false; + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + + // left + static int selected = 0; + ImGui::BeginChild("left pane", ImVec2(150, 0), true); + for (int i = 0; i < 100; i++) + { + char label[128]; + sprintf(label, "MyObject %d", i); + if (ImGui::Selectable(label, selected == i)) + selected = i; + } + ImGui::EndChild(); + ImGui::SameLine(); + + // right + ImGui::BeginGroup(); + ImGui::BeginChild("item view", ImVec2(0, -ImGui::GetItemsLineHeightWithSpacing())); // Leave room for 1 line below us + ImGui::Text("MyObject: %d", selected); + ImGui::Separator(); + ImGui::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "); + ImGui::EndChild(); + ImGui::BeginChild("buttons"); + if (ImGui::Button("Revert")) {} + ImGui::SameLine(); + if (ImGui::Button("Save")) {} + ImGui::EndChild(); + ImGui::EndGroup(); + } + ImGui::End(); +} + +static void ShowExampleAppPropertyEditor(bool* p_open) +{ + ImGui::SetNextWindowSize(ImVec2(430,450), ImGuiSetCond_FirstUseEver); + if (!ImGui::Begin("Example: Property editor", p_open)) + { + ImGui::End(); + return; + } + + ShowHelpMarker("This example shows how you may implement a property editor using two columns.\nAll objects/fields data are dummies here.\nRemember that in many simple cases, you can use ImGui::SameLine(xxx) to position\nyour cursor horizontally instead of using the Columns() API."); + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2,2)); + ImGui::Columns(2); + ImGui::Separator(); + + struct funcs + { + static void ShowDummyObject(const char* prefix, int uid) + { + ImGui::PushID(uid); // Use object uid as identifier. Most commonly you could also use the object pointer as a base ID. + ImGui::AlignFirstTextHeightToWidgets(); // Text and Tree nodes are less high than regular widgets, here we add vertical spacing to make the tree lines equal high. + bool node_open = ImGui::TreeNode("Object", "%s_%u", prefix, uid); + ImGui::NextColumn(); + ImGui::AlignFirstTextHeightToWidgets(); + ImGui::Text("my sailor is rich"); + ImGui::NextColumn(); + if (node_open) + { + static float dummy_members[8] = { 0.0f,0.0f,1.0f,3.1416f,100.0f,999.0f }; + for (int i = 0; i < 8; i++) + { + ImGui::PushID(i); // Use field index as identifier. + if (i < 2) + { + ShowDummyObject("Child", 424242); + } + else + { + ImGui::AlignFirstTextHeightToWidgets(); + // Here we use a Selectable (instead of Text) to highlight on hover + //ImGui::Text("Field_%d", i); + char label[32]; + sprintf(label, "Field_%d", i); + ImGui::Bullet(); + ImGui::Selectable(label); + ImGui::NextColumn(); + ImGui::PushItemWidth(-1); + if (i >= 5) + ImGui::InputFloat("##value", &dummy_members[i], 1.0f); + else + ImGui::DragFloat("##value", &dummy_members[i], 0.01f); + ImGui::PopItemWidth(); + ImGui::NextColumn(); + } + ImGui::PopID(); + } + ImGui::TreePop(); + } + ImGui::PopID(); + } + }; + + // Iterate dummy objects with dummy members (all the same data) + for (int obj_i = 0; obj_i < 3; obj_i++) + funcs::ShowDummyObject("Object", obj_i); + + ImGui::Columns(1); + ImGui::Separator(); + ImGui::PopStyleVar(); + ImGui::End(); +} + +static void ShowExampleAppLongText(bool* p_open) +{ + ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiSetCond_FirstUseEver); + if (!ImGui::Begin("Example: Long text display", p_open)) + { + ImGui::End(); + return; + } + + static int test_type = 0; + static ImGuiTextBuffer log; + static int lines = 0; + ImGui::Text("Printing unusually long amount of text."); + ImGui::Combo("Test type", &test_type, "Single call to TextUnformatted()\0Multiple calls to Text(), clipped manually\0Multiple calls to Text(), not clipped\0"); + ImGui::Text("Buffer contents: %d lines, %d bytes", lines, log.size()); + if (ImGui::Button("Clear")) { log.clear(); lines = 0; } + ImGui::SameLine(); + if (ImGui::Button("Add 1000 lines")) + { + for (int i = 0; i < 1000; i++) + log.append("%i The quick brown fox jumps over the lazy dog\n", lines+i); + lines += 1000; + } + ImGui::BeginChild("Log"); + switch (test_type) + { + case 0: + // Single call to TextUnformatted() with a big buffer + ImGui::TextUnformatted(log.begin(), log.end()); + break; + case 1: + { + // Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the ImGuiListClipper helper. + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); + ImGuiListClipper clipper(lines); + while (clipper.Step()) + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + ImGui::Text("%i The quick brown fox jumps over the lazy dog", i); + ImGui::PopStyleVar(); + break; + } + case 2: + // Multiple calls to Text(), not clipped (slow) + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); + for (int i = 0; i < lines; i++) + ImGui::Text("%i The quick brown fox jumps over the lazy dog", i); + ImGui::PopStyleVar(); + break; + } + ImGui::EndChild(); + ImGui::End(); +} + +// End of Demo code +#else + +void ImGui::ShowTestWindow(bool*) {} +void ImGui::ShowUserGuide() {} +void ImGui::ShowStyleEditor(ImGuiStyle*) {} + +#endif diff --git a/modules/onscreengui/ext/imgui/imgui_draw.cpp b/modules/onscreengui/ext/imgui/imgui_draw.cpp new file mode 100644 index 0000000000..63cf882a93 --- /dev/null +++ b/modules/onscreengui/ext/imgui/imgui_draw.cpp @@ -0,0 +1,2377 @@ +// dear imgui, v1.49 +// (drawing and font code) + +// Contains implementation for +// - ImDrawList +// - ImDrawData +// - ImFontAtlas +// - ImFont +// - Default font data + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#define IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_PLACEMENT_NEW +#include "imgui_internal.h" + +#include // vsnprintf, sscanf, printf +#if !defined(alloca) && !defined(__FreeBSD__) && !defined(__DragonFly__) +#ifdef _WIN32 +#include // alloca +#else +#include // alloca +#endif +#endif + +#ifdef _MSC_VER +#pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#define snprintf _snprintf +#endif + +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants ok. +#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // +#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier // +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value +#endif + +//------------------------------------------------------------------------- +// STB libraries implementation +//------------------------------------------------------------------------- + +//#define IMGUI_STB_NAMESPACE ImGuiStb +//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION +//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION + +#ifdef IMGUI_STB_NAMESPACE +namespace IMGUI_STB_NAMESPACE +{ +#endif + +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable: 4456) // declaration of 'xx' hides previous local declaration +#endif + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wunused-function" +#pragma clang diagnostic ignored "-Wmissing-prototypes" +#endif + +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wtype-limits" // warning: comparison is always true due to limited range of data type [-Wtype-limits] +#endif + +#define STBRP_ASSERT(x) IM_ASSERT(x) +#ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION +#define STBRP_STATIC +#define STB_RECT_PACK_IMPLEMENTATION +#endif +#include "stb_rect_pack.h" + +#define STBTT_malloc(x,u) ((void)(u), ImGui::MemAlloc(x)) +#define STBTT_free(x,u) ((void)(u), ImGui::MemFree(x)) +#define STBTT_assert(x) IM_ASSERT(x) +#ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION +#define STBTT_STATIC +#define STB_TRUETYPE_IMPLEMENTATION +#else +#define STBTT_DEF extern +#endif +#include "stb_truetype.h" + +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#ifdef _MSC_VER +#pragma warning (pop) +#endif + +#ifdef IMGUI_STB_NAMESPACE +} // namespace ImGuiStb +using namespace IMGUI_STB_NAMESPACE; +#endif + +//----------------------------------------------------------------------------- +// ImDrawList +//----------------------------------------------------------------------------- + +static const ImVec4 GNullClipRect(-8192.0f, -8192.0f, +8192.0f, +8192.0f); // Large values that are easy to encode in a few bits+shift + +void ImDrawList::Clear() +{ + CmdBuffer.resize(0); + IdxBuffer.resize(0); + VtxBuffer.resize(0); + _VtxCurrentIdx = 0; + _VtxWritePtr = NULL; + _IdxWritePtr = NULL; + _ClipRectStack.resize(0); + _TextureIdStack.resize(0); + _Path.resize(0); + _ChannelsCurrent = 0; + _ChannelsCount = 1; + // NB: Do not clear channels so our allocations are re-used after the first frame. +} + +void ImDrawList::ClearFreeMemory() +{ + CmdBuffer.clear(); + IdxBuffer.clear(); + VtxBuffer.clear(); + _VtxCurrentIdx = 0; + _VtxWritePtr = NULL; + _IdxWritePtr = NULL; + _ClipRectStack.clear(); + _TextureIdStack.clear(); + _Path.clear(); + _ChannelsCurrent = 0; + _ChannelsCount = 1; + for (int i = 0; i < _Channels.Size; i++) + { + if (i == 0) memset(&_Channels[0], 0, sizeof(_Channels[0])); // channel 0 is a copy of CmdBuffer/IdxBuffer, don't destruct again + _Channels[i].CmdBuffer.clear(); + _Channels[i].IdxBuffer.clear(); + } + _Channels.clear(); +} + +// Use macros because C++ is a terrible language, we want guaranteed inline, no code in header, and no overhead in Debug mode +#define GetCurrentClipRect() (_ClipRectStack.Size ? _ClipRectStack.Data[_ClipRectStack.Size-1] : GNullClipRect) +#define GetCurrentTextureId() (_TextureIdStack.Size ? _TextureIdStack.Data[_TextureIdStack.Size-1] : NULL) + +void ImDrawList::AddDrawCmd() +{ + ImDrawCmd draw_cmd; + draw_cmd.ClipRect = GetCurrentClipRect(); + draw_cmd.TextureId = GetCurrentTextureId(); + + IM_ASSERT(draw_cmd.ClipRect.x <= draw_cmd.ClipRect.z && draw_cmd.ClipRect.y <= draw_cmd.ClipRect.w); + CmdBuffer.push_back(draw_cmd); +} + +void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) +{ + ImDrawCmd* current_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL; + if (!current_cmd || current_cmd->ElemCount != 0 || current_cmd->UserCallback != NULL) + { + AddDrawCmd(); + current_cmd = &CmdBuffer.back(); + } + current_cmd->UserCallback = callback; + current_cmd->UserCallbackData = callback_data; + + AddDrawCmd(); // Force a new command after us (see comment below) +} + +// Our scheme may appears a bit unusual, basically we want the most-common calls AddLine AddRect etc. to not have to perform any check so we always have a command ready in the stack. +// The cost of figuring out if a new command has to be added or if we can merge is paid in those Update** functions only. +void ImDrawList::UpdateClipRect() +{ + // If current command is used with different settings we need to add a new command + const ImVec4 curr_clip_rect = GetCurrentClipRect(); + ImDrawCmd* curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size-1] : NULL; + if (!curr_cmd || (curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) != 0) || curr_cmd->UserCallback != NULL) + { + AddDrawCmd(); + return; + } + + // Try to merge with previous command if it matches, else use current command + ImDrawCmd* prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL; + if (prev_cmd && memcmp(&prev_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) == 0 && prev_cmd->TextureId == GetCurrentTextureId() && prev_cmd->UserCallback == NULL) + CmdBuffer.pop_back(); + else + curr_cmd->ClipRect = curr_clip_rect; +} + +void ImDrawList::UpdateTextureID() +{ + // If current command is used with different settings we need to add a new command + const ImTextureID curr_texture_id = GetCurrentTextureId(); + ImDrawCmd* curr_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL; + if (!curr_cmd || (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != curr_texture_id) || curr_cmd->UserCallback != NULL) + { + AddDrawCmd(); + return; + } + + // Try to merge with previous command if it matches, else use current command + ImDrawCmd* prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL; + if (prev_cmd && prev_cmd->TextureId == curr_texture_id && memcmp(&prev_cmd->ClipRect, &GetCurrentClipRect(), sizeof(ImVec4)) == 0 && prev_cmd->UserCallback == NULL) + CmdBuffer.pop_back(); + else + curr_cmd->TextureId = curr_texture_id; +} + +#undef GetCurrentClipRect +#undef GetCurrentTextureId + +// Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) +void ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_current_clip_rect) +{ + ImVec4 cr(cr_min.x, cr_min.y, cr_max.x, cr_max.y); + if (intersect_with_current_clip_rect && _ClipRectStack.Size) + { + ImVec4 current = _ClipRectStack.Data[_ClipRectStack.Size-1]; + if (cr.x < current.x) cr.x = current.x; + if (cr.y < current.y) cr.y = current.y; + if (cr.z > current.z) cr.z = current.z; + if (cr.w > current.w) cr.w = current.w; + } + cr.z = ImMax(cr.x, cr.z); + cr.w = ImMax(cr.y, cr.w); + + _ClipRectStack.push_back(cr); + UpdateClipRect(); +} + +void ImDrawList::PushClipRectFullScreen() +{ + PushClipRect(ImVec2(GNullClipRect.x, GNullClipRect.y), ImVec2(GNullClipRect.z, GNullClipRect.w)); + //PushClipRect(GetVisibleRect()); // FIXME-OPT: This would be more correct but we're not supposed to access ImGuiContext from here? +} + +void ImDrawList::PopClipRect() +{ + IM_ASSERT(_ClipRectStack.Size > 0); + _ClipRectStack.pop_back(); + UpdateClipRect(); +} + +void ImDrawList::PushTextureID(const ImTextureID& texture_id) +{ + _TextureIdStack.push_back(texture_id); + UpdateTextureID(); +} + +void ImDrawList::PopTextureID() +{ + IM_ASSERT(_TextureIdStack.Size > 0); + _TextureIdStack.pop_back(); + UpdateTextureID(); +} + +void ImDrawList::ChannelsSplit(int channels_count) +{ + IM_ASSERT(_ChannelsCurrent == 0 && _ChannelsCount == 1); + int old_channels_count = _Channels.Size; + if (old_channels_count < channels_count) + _Channels.resize(channels_count); + _ChannelsCount = channels_count; + + // _Channels[] (24 bytes each) hold storage that we'll swap with this->_CmdBuffer/_IdxBuffer + // The content of _Channels[0] at this point doesn't matter. We clear it to make state tidy in a debugger but we don't strictly need to. + // When we switch to the next channel, we'll copy _CmdBuffer/_IdxBuffer into _Channels[0] and then _Channels[1] into _CmdBuffer/_IdxBuffer + memset(&_Channels[0], 0, sizeof(ImDrawChannel)); + for (int i = 1; i < channels_count; i++) + { + if (i >= old_channels_count) + { + IM_PLACEMENT_NEW(&_Channels[i]) ImDrawChannel(); + } + else + { + _Channels[i].CmdBuffer.resize(0); + _Channels[i].IdxBuffer.resize(0); + } + if (_Channels[i].CmdBuffer.Size == 0) + { + ImDrawCmd draw_cmd; + draw_cmd.ClipRect = _ClipRectStack.back(); + draw_cmd.TextureId = _TextureIdStack.back(); + _Channels[i].CmdBuffer.push_back(draw_cmd); + } + } +} + +void ImDrawList::ChannelsMerge() +{ + // Note that we never use or rely on channels.Size because it is merely a buffer that we never shrink back to 0 to keep all sub-buffers ready for use. + if (_ChannelsCount <= 1) + return; + + ChannelsSetCurrent(0); + if (CmdBuffer.Size && CmdBuffer.back().ElemCount == 0) + CmdBuffer.pop_back(); + + int new_cmd_buffer_count = 0, new_idx_buffer_count = 0; + for (int i = 1; i < _ChannelsCount; i++) + { + ImDrawChannel& ch = _Channels[i]; + if (ch.CmdBuffer.Size && ch.CmdBuffer.back().ElemCount == 0) + ch.CmdBuffer.pop_back(); + new_cmd_buffer_count += ch.CmdBuffer.Size; + new_idx_buffer_count += ch.IdxBuffer.Size; + } + CmdBuffer.resize(CmdBuffer.Size + new_cmd_buffer_count); + IdxBuffer.resize(IdxBuffer.Size + new_idx_buffer_count); + + ImDrawCmd* cmd_write = CmdBuffer.Data + CmdBuffer.Size - new_cmd_buffer_count; + _IdxWritePtr = IdxBuffer.Data + IdxBuffer.Size - new_idx_buffer_count; + for (int i = 1; i < _ChannelsCount; i++) + { + ImDrawChannel& ch = _Channels[i]; + if (int sz = ch.CmdBuffer.Size) { memcpy(cmd_write, ch.CmdBuffer.Data, sz * sizeof(ImDrawCmd)); cmd_write += sz; } + if (int sz = ch.IdxBuffer.Size) { memcpy(_IdxWritePtr, ch.IdxBuffer.Data, sz * sizeof(ImDrawIdx)); _IdxWritePtr += sz; } + } + AddDrawCmd(); + _ChannelsCount = 1; +} + +void ImDrawList::ChannelsSetCurrent(int idx) +{ + IM_ASSERT(idx < _ChannelsCount); + if (_ChannelsCurrent == idx) return; + memcpy(&_Channels.Data[_ChannelsCurrent].CmdBuffer, &CmdBuffer, sizeof(CmdBuffer)); // copy 12 bytes, four times + memcpy(&_Channels.Data[_ChannelsCurrent].IdxBuffer, &IdxBuffer, sizeof(IdxBuffer)); + _ChannelsCurrent = idx; + memcpy(&CmdBuffer, &_Channels.Data[_ChannelsCurrent].CmdBuffer, sizeof(CmdBuffer)); + memcpy(&IdxBuffer, &_Channels.Data[_ChannelsCurrent].IdxBuffer, sizeof(IdxBuffer)); + _IdxWritePtr = IdxBuffer.Data + IdxBuffer.Size; +} + +// NB: this can be called with negative count for removing primitives (as long as the result does not underflow) +void ImDrawList::PrimReserve(int idx_count, int vtx_count) +{ + ImDrawCmd& draw_cmd = CmdBuffer.Data[CmdBuffer.Size-1]; + draw_cmd.ElemCount += idx_count; + + int vtx_buffer_size = VtxBuffer.Size; + VtxBuffer.resize(vtx_buffer_size + vtx_count); + _VtxWritePtr = VtxBuffer.Data + vtx_buffer_size; + + int idx_buffer_size = IdxBuffer.Size; + IdxBuffer.resize(idx_buffer_size + idx_count); + _IdxWritePtr = IdxBuffer.Data + idx_buffer_size; +} + +// Fully unrolled with inline call to keep our debug builds decently fast. +void ImDrawList::PrimRect(const ImVec2& a, const ImVec2& c, ImU32 col) +{ + ImVec2 b(c.x, a.y), d(a.x, c.y), uv(GImGui->FontTexUvWhitePixel); + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); + _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); + _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + _VtxCurrentIdx += 4; + _IdxWritePtr += 6; +} + +void ImDrawList::PrimRectUV(const ImVec2& a, const ImVec2& c, const ImVec2& uv_a, const ImVec2& uv_c, ImU32 col) +{ + ImVec2 b(c.x, a.y), d(a.x, c.y), uv_b(uv_c.x, uv_a.y), uv_d(uv_a.x, uv_c.y); + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); + _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); + _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv_a; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv_b; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv_c; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv_d; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + _VtxCurrentIdx += 4; + _IdxWritePtr += 6; +} + +void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col) +{ + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); + _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); + _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv_a; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv_b; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv_c; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv_d; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + _VtxCurrentIdx += 4; + _IdxWritePtr += 6; +} + +// TODO: Thickness anti-aliased lines cap are missing their AA fringe. +void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, bool closed, float thickness, bool anti_aliased) +{ + if (points_count < 2) + return; + + const ImVec2 uv = GImGui->FontTexUvWhitePixel; + anti_aliased &= GImGui->Style.AntiAliasedLines; + //if (ImGui::GetIO().KeyCtrl) anti_aliased = false; // Debug + + int count = points_count; + if (!closed) + count = points_count-1; + + const bool thick_line = thickness > 1.0f; + if (anti_aliased) + { + // Anti-aliased stroke + const float AA_SIZE = 1.0f; + const ImU32 col_trans = col & 0x00ffffff; + + const int idx_count = thick_line ? count*18 : count*12; + const int vtx_count = thick_line ? points_count*4 : points_count*3; + PrimReserve(idx_count, vtx_count); + + // Temporary buffer + ImVec2* temp_normals = (ImVec2*)alloca(points_count * (thick_line ? 5 : 3) * sizeof(ImVec2)); + ImVec2* temp_points = temp_normals + points_count; + + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1+1) == points_count ? 0 : i1+1; + ImVec2 diff = points[i2] - points[i1]; + diff *= ImInvLength(diff, 1.0f); + temp_normals[i1].x = diff.y; + temp_normals[i1].y = -diff.x; + } + if (!closed) + temp_normals[points_count-1] = temp_normals[points_count-2]; + + if (!thick_line) + { + if (!closed) + { + temp_points[0] = points[0] + temp_normals[0] * AA_SIZE; + temp_points[1] = points[0] - temp_normals[0] * AA_SIZE; + temp_points[(points_count-1)*2+0] = points[points_count-1] + temp_normals[points_count-1] * AA_SIZE; + temp_points[(points_count-1)*2+1] = points[points_count-1] - temp_normals[points_count-1] * AA_SIZE; + } + + // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. + unsigned int idx1 = _VtxCurrentIdx; + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1+1) == points_count ? 0 : i1+1; + unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+3; + + // Average normals + ImVec2 dm = (temp_normals[i1] + temp_normals[i2]) * 0.5f; + float dmr2 = dm.x*dm.x + dm.y*dm.y; + if (dmr2 > 0.000001f) + { + float scale = 1.0f / dmr2; + if (scale > 100.0f) scale = 100.0f; + dm *= scale; + } + dm *= AA_SIZE; + temp_points[i2*2+0] = points[i2] + dm; + temp_points[i2*2+1] = points[i2] - dm; + + // Add indexes + _IdxWritePtr[0] = (ImDrawIdx)(idx2+0); _IdxWritePtr[1] = (ImDrawIdx)(idx1+0); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2); + _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+0); + _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0); + _IdxWritePtr[9] = (ImDrawIdx)(idx1+0); _IdxWritePtr[10]= (ImDrawIdx)(idx2+0); _IdxWritePtr[11]= (ImDrawIdx)(idx2+1); + _IdxWritePtr += 12; + + idx1 = idx2; + } + + // Add vertexes + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = temp_points[i*2+0]; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; + _VtxWritePtr[2].pos = temp_points[i*2+1]; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col_trans; + _VtxWritePtr += 3; + } + } + else + { + const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f; + if (!closed) + { + temp_points[0] = points[0] + temp_normals[0] * (half_inner_thickness + AA_SIZE); + temp_points[1] = points[0] + temp_normals[0] * (half_inner_thickness); + temp_points[2] = points[0] - temp_normals[0] * (half_inner_thickness); + temp_points[3] = points[0] - temp_normals[0] * (half_inner_thickness + AA_SIZE); + temp_points[(points_count-1)*4+0] = points[points_count-1] + temp_normals[points_count-1] * (half_inner_thickness + AA_SIZE); + temp_points[(points_count-1)*4+1] = points[points_count-1] + temp_normals[points_count-1] * (half_inner_thickness); + temp_points[(points_count-1)*4+2] = points[points_count-1] - temp_normals[points_count-1] * (half_inner_thickness); + temp_points[(points_count-1)*4+3] = points[points_count-1] - temp_normals[points_count-1] * (half_inner_thickness + AA_SIZE); + } + + // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. + unsigned int idx1 = _VtxCurrentIdx; + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1+1) == points_count ? 0 : i1+1; + unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+4; + + // Average normals + ImVec2 dm = (temp_normals[i1] + temp_normals[i2]) * 0.5f; + float dmr2 = dm.x*dm.x + dm.y*dm.y; + if (dmr2 > 0.000001f) + { + float scale = 1.0f / dmr2; + if (scale > 100.0f) scale = 100.0f; + dm *= scale; + } + ImVec2 dm_out = dm * (half_inner_thickness + AA_SIZE); + ImVec2 dm_in = dm * half_inner_thickness; + temp_points[i2*4+0] = points[i2] + dm_out; + temp_points[i2*4+1] = points[i2] + dm_in; + temp_points[i2*4+2] = points[i2] - dm_in; + temp_points[i2*4+3] = points[i2] - dm_out; + + // Add indexes + _IdxWritePtr[0] = (ImDrawIdx)(idx2+1); _IdxWritePtr[1] = (ImDrawIdx)(idx1+1); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2); + _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+1); + _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0); + _IdxWritePtr[9] = (ImDrawIdx)(idx1+0); _IdxWritePtr[10] = (ImDrawIdx)(idx2+0); _IdxWritePtr[11] = (ImDrawIdx)(idx2+1); + _IdxWritePtr[12] = (ImDrawIdx)(idx2+2); _IdxWritePtr[13] = (ImDrawIdx)(idx1+2); _IdxWritePtr[14] = (ImDrawIdx)(idx1+3); + _IdxWritePtr[15] = (ImDrawIdx)(idx1+3); _IdxWritePtr[16] = (ImDrawIdx)(idx2+3); _IdxWritePtr[17] = (ImDrawIdx)(idx2+2); + _IdxWritePtr += 18; + + idx1 = idx2; + } + + // Add vertexes + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = temp_points[i*4+0]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col_trans; + _VtxWritePtr[1].pos = temp_points[i*4+1]; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = temp_points[i*4+2]; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = temp_points[i*4+3]; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col_trans; + _VtxWritePtr += 4; + } + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } + else + { + // Non Anti-aliased Stroke + const int idx_count = count*6; + const int vtx_count = count*4; // FIXME-OPT: Not sharing edges + PrimReserve(idx_count, vtx_count); + + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1+1) == points_count ? 0 : i1+1; + const ImVec2& p1 = points[i1]; + const ImVec2& p2 = points[i2]; + ImVec2 diff = p2 - p1; + diff *= ImInvLength(diff, 1.0f); + + const float dx = diff.x * (thickness * 0.5f); + const float dy = diff.y * (thickness * 0.5f); + _VtxWritePtr[0].pos.x = p1.x + dy; _VtxWritePtr[0].pos.y = p1.y - dx; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos.x = p2.x + dy; _VtxWritePtr[1].pos.y = p2.y - dx; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos.x = p2.x - dy; _VtxWritePtr[2].pos.y = p2.y + dx; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos.x = p1.x - dy; _VtxWritePtr[3].pos.y = p1.y + dx; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + + _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+2); + _IdxWritePtr[3] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[4] = (ImDrawIdx)(_VtxCurrentIdx+2); _IdxWritePtr[5] = (ImDrawIdx)(_VtxCurrentIdx+3); + _IdxWritePtr += 6; + _VtxCurrentIdx += 4; + } + } +} + +void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_count, ImU32 col, bool anti_aliased) +{ + const ImVec2 uv = GImGui->FontTexUvWhitePixel; + anti_aliased &= GImGui->Style.AntiAliasedShapes; + //if (ImGui::GetIO().KeyCtrl) anti_aliased = false; // Debug + + if (anti_aliased) + { + // Anti-aliased Fill + const float AA_SIZE = 1.0f; + const ImU32 col_trans = col & 0x00ffffff; + const int idx_count = (points_count-2)*3 + points_count*6; + const int vtx_count = (points_count*2); + PrimReserve(idx_count, vtx_count); + + // Add indexes for fill + unsigned int vtx_inner_idx = _VtxCurrentIdx; + unsigned int vtx_outer_idx = _VtxCurrentIdx+1; + for (int i = 2; i < points_count; i++) + { + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx+((i-1)<<1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx+(i<<1)); + _IdxWritePtr += 3; + } + + // Compute normals + ImVec2* temp_normals = (ImVec2*)alloca(points_count * sizeof(ImVec2)); + for (int i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) + { + const ImVec2& p0 = points[i0]; + const ImVec2& p1 = points[i1]; + ImVec2 diff = p1 - p0; + diff *= ImInvLength(diff, 1.0f); + temp_normals[i0].x = diff.y; + temp_normals[i0].y = -diff.x; + } + + for (int i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) + { + // Average normals + const ImVec2& n0 = temp_normals[i0]; + const ImVec2& n1 = temp_normals[i1]; + ImVec2 dm = (n0 + n1) * 0.5f; + float dmr2 = dm.x*dm.x + dm.y*dm.y; + if (dmr2 > 0.000001f) + { + float scale = 1.0f / dmr2; + if (scale > 100.0f) scale = 100.0f; + dm *= scale; + } + dm *= AA_SIZE * 0.5f; + + // Add vertices + _VtxWritePtr[0].pos = (points[i1] - dm); _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; // Inner + _VtxWritePtr[1].pos = (points[i1] + dm); _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; // Outer + _VtxWritePtr += 2; + + // Add indexes for fringes + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx+(i1<<1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx+(i0<<1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_outer_idx+(i0<<1)); + _IdxWritePtr[3] = (ImDrawIdx)(vtx_outer_idx+(i0<<1)); _IdxWritePtr[4] = (ImDrawIdx)(vtx_outer_idx+(i1<<1)); _IdxWritePtr[5] = (ImDrawIdx)(vtx_inner_idx+(i1<<1)); + _IdxWritePtr += 6; + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } + else + { + // Non Anti-aliased Fill + const int idx_count = (points_count-2)*3; + const int vtx_count = points_count; + PrimReserve(idx_count, vtx_count); + for (int i = 0; i < vtx_count; i++) + { + _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr++; + } + for (int i = 2; i < points_count; i++) + { + _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+i-1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+i); + _IdxWritePtr += 3; + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } +} + +void ImDrawList::PathArcToFast(const ImVec2& centre, float radius, int amin, int amax) +{ + static ImVec2 circle_vtx[12]; + static bool circle_vtx_builds = false; + const int circle_vtx_count = IM_ARRAYSIZE(circle_vtx); + if (!circle_vtx_builds) + { + for (int i = 0; i < circle_vtx_count; i++) + { + const float a = ((float)i / (float)circle_vtx_count) * 2*IM_PI; + circle_vtx[i].x = cosf(a); + circle_vtx[i].y = sinf(a); + } + circle_vtx_builds = true; + } + + if (amin > amax) return; + if (radius == 0.0f) + { + _Path.push_back(centre); + } + else + { + _Path.reserve(_Path.Size + (amax - amin + 1)); + for (int a = amin; a <= amax; a++) + { + const ImVec2& c = circle_vtx[a % circle_vtx_count]; + _Path.push_back(ImVec2(centre.x + c.x * radius, centre.y + c.y * radius)); + } + } +} + +void ImDrawList::PathArcTo(const ImVec2& centre, float radius, float amin, float amax, int num_segments) +{ + if (radius == 0.0f) + _Path.push_back(centre); + _Path.reserve(_Path.Size + (num_segments + 1)); + for (int i = 0; i <= num_segments; i++) + { + const float a = amin + ((float)i / (float)num_segments) * (amax - amin); + _Path.push_back(ImVec2(centre.x + cosf(a) * radius, centre.y + sinf(a) * radius)); + } +} + +static void PathBezierToCasteljau(ImVector* path, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level) +{ + float dx = x4 - x1; + float dy = y4 - y1; + float d2 = ((x2 - x4) * dy - (y2 - y4) * dx); + float d3 = ((x3 - x4) * dy - (y3 - y4) * dx); + d2 = (d2 >= 0) ? d2 : -d2; + d3 = (d3 >= 0) ? d3 : -d3; + if ((d2+d3) * (d2+d3) < tess_tol * (dx*dx + dy*dy)) + { + path->push_back(ImVec2(x4, y4)); + } + else if (level < 10) + { + float x12 = (x1+x2)*0.5f, y12 = (y1+y2)*0.5f; + float x23 = (x2+x3)*0.5f, y23 = (y2+y3)*0.5f; + float x34 = (x3+x4)*0.5f, y34 = (y3+y4)*0.5f; + float x123 = (x12+x23)*0.5f, y123 = (y12+y23)*0.5f; + float x234 = (x23+x34)*0.5f, y234 = (y23+y34)*0.5f; + float x1234 = (x123+x234)*0.5f, y1234 = (y123+y234)*0.5f; + + PathBezierToCasteljau(path, x1,y1, x12,y12, x123,y123, x1234,y1234, tess_tol, level+1); + PathBezierToCasteljau(path, x1234,y1234, x234,y234, x34,y34, x4,y4, tess_tol, level+1); + } +} + +void ImDrawList::PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments) +{ + ImVec2 p1 = _Path.back(); + if (num_segments == 0) + { + // Auto-tessellated + PathBezierToCasteljau(&_Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, GImGui->Style.CurveTessellationTol, 0); + } + else + { + float t_step = 1.0f / (float)num_segments; + for (int i_step = 1; i_step <= num_segments; i_step++) + { + float t = t_step * i_step; + float u = 1.0f - t; + float w1 = u*u*u; + float w2 = 3*u*u*t; + float w3 = 3*u*t*t; + float w4 = t*t*t; + _Path.push_back(ImVec2(w1*p1.x + w2*p2.x + w3*p3.x + w4*p4.x, w1*p1.y + w2*p2.y + w3*p3.y + w4*p4.y)); + } + } +} + +void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, int rounding_corners) +{ + float r = rounding; + r = ImMin(r, fabsf(b.x-a.x) * ( ((rounding_corners&(1|2))==(1|2)) || ((rounding_corners&(4|8))==(4|8)) ? 0.5f : 1.0f ) - 1.0f); + r = ImMin(r, fabsf(b.y-a.y) * ( ((rounding_corners&(1|8))==(1|8)) || ((rounding_corners&(2|4))==(2|4)) ? 0.5f : 1.0f ) - 1.0f); + + if (r <= 0.0f || rounding_corners == 0) + { + PathLineTo(a); + PathLineTo(ImVec2(b.x,a.y)); + PathLineTo(b); + PathLineTo(ImVec2(a.x,b.y)); + } + else + { + const float r0 = (rounding_corners & 1) ? r : 0.0f; + const float r1 = (rounding_corners & 2) ? r : 0.0f; + const float r2 = (rounding_corners & 4) ? r : 0.0f; + const float r3 = (rounding_corners & 8) ? r : 0.0f; + PathArcToFast(ImVec2(a.x+r0,a.y+r0), r0, 6, 9); + PathArcToFast(ImVec2(b.x-r1,a.y+r1), r1, 9, 12); + PathArcToFast(ImVec2(b.x-r2,b.y-r2), r2, 0, 3); + PathArcToFast(ImVec2(a.x+r3,b.y-r3), r3, 3, 6); + } +} + +void ImDrawList::AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness) +{ + if ((col >> 24) == 0) + return; + PathLineTo(a + ImVec2(0.5f,0.5f)); + PathLineTo(b + ImVec2(0.5f,0.5f)); + PathStroke(col, false, thickness); +} + +// a: upper-left, b: lower-right. we don't render 1 px sized rectangles properly. +void ImDrawList::AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners, float thickness) +{ + if ((col >> 24) == 0) + return; + PathRect(a + ImVec2(0.5f,0.5f), b - ImVec2(0.5f,0.5f), rounding, rounding_corners); + PathStroke(col, true, thickness); +} + +void ImDrawList::AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners) +{ + if ((col >> 24) == 0) + return; + if (rounding > 0.0f) + { + PathRect(a, b, rounding, rounding_corners); + PathFill(col); + } + else + { + PrimReserve(6, 4); + PrimRect(a, b, col); + } +} + +void ImDrawList::AddRectFilledMultiColor(const ImVec2& a, const ImVec2& c, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left) +{ + if (((col_upr_left | col_upr_right | col_bot_right | col_bot_left) >> 24) == 0) + return; + + const ImVec2 uv = GImGui->FontTexUvWhitePixel; + PrimReserve(6, 4); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+1)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+2)); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+2)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+3)); + PrimWriteVtx(a, uv, col_upr_left); + PrimWriteVtx(ImVec2(c.x, a.y), uv, col_upr_right); + PrimWriteVtx(c, uv, col_bot_right); + PrimWriteVtx(ImVec2(a.x, c.y), uv, col_bot_left); +} + +void ImDrawList::AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness) +{ + if ((col >> 24) == 0) + return; + + PathLineTo(a); + PathLineTo(b); + PathLineTo(c); + PathLineTo(d); + PathStroke(col, true, thickness); +} + +void ImDrawList::AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col) +{ + if ((col >> 24) == 0) + return; + + PathLineTo(a); + PathLineTo(b); + PathLineTo(c); + PathLineTo(d); + PathFill(col); +} + +void ImDrawList::AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness) +{ + if ((col >> 24) == 0) + return; + + PathLineTo(a); + PathLineTo(b); + PathLineTo(c); + PathStroke(col, true, thickness); +} + +void ImDrawList::AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col) +{ + if ((col >> 24) == 0) + return; + + PathLineTo(a); + PathLineTo(b); + PathLineTo(c); + PathFill(col); +} + +void ImDrawList::AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments, float thickness) +{ + if ((col >> 24) == 0) + return; + + const float a_max = IM_PI*2.0f * ((float)num_segments - 1.0f) / (float)num_segments; + PathArcTo(centre, radius-0.5f, 0.0f, a_max, num_segments); + PathStroke(col, true, thickness); +} + +void ImDrawList::AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments) +{ + if ((col >> 24) == 0) + return; + + const float a_max = IM_PI*2.0f * ((float)num_segments - 1.0f) / (float)num_segments; + PathArcTo(centre, radius, 0.0f, a_max, num_segments); + PathFill(col); +} + +void ImDrawList::AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments) +{ + if ((col >> 24) == 0) + return; + + PathLineTo(pos0); + PathBezierCurveTo(cp0, cp1, pos1, num_segments); + PathStroke(col, false, thickness); +} + +void ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end, float wrap_width, const ImVec4* cpu_fine_clip_rect) +{ + if ((col >> 24) == 0) + return; + + if (text_end == NULL) + text_end = text_begin + strlen(text_begin); + if (text_begin == text_end) + return; + + // Note: This is one of the few instance of breaking the encapsulation of ImDrawList, as we pull this from ImGui state, but it is just SO useful. + // Might just move Font/FontSize to ImDrawList? + if (font == NULL) + font = GImGui->Font; + if (font_size == 0.0f) + font_size = GImGui->FontSize; + + IM_ASSERT(font->ContainerAtlas->TexID == _TextureIdStack.back()); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font. + + ImVec4 clip_rect = _ClipRectStack.back(); + if (cpu_fine_clip_rect) + { + clip_rect.x = ImMax(clip_rect.x, cpu_fine_clip_rect->x); + clip_rect.y = ImMax(clip_rect.y, cpu_fine_clip_rect->y); + clip_rect.z = ImMin(clip_rect.z, cpu_fine_clip_rect->z); + clip_rect.w = ImMin(clip_rect.w, cpu_fine_clip_rect->w); + } + font->RenderText(this, font_size, pos, col, clip_rect, text_begin, text_end, wrap_width, cpu_fine_clip_rect != NULL); +} + +void ImDrawList::AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end) +{ + AddText(GImGui->Font, GImGui->FontSize, pos, col, text_begin, text_end); +} + +void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv0, const ImVec2& uv1, ImU32 col) +{ + if ((col >> 24) == 0) + return; + + // FIXME-OPT: This is wasting draw calls. + const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back(); + if (push_texture_id) + PushTextureID(user_texture_id); + + PrimReserve(6, 4); + PrimRectUV(a, b, uv0, uv1, col); + + if (push_texture_id) + PopTextureID(); +} + +//----------------------------------------------------------------------------- +// ImDrawData +//----------------------------------------------------------------------------- + +// For backward compatibility: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! +void ImDrawData::DeIndexAllBuffers() +{ + ImVector new_vtx_buffer; + TotalVtxCount = TotalIdxCount = 0; + for (int i = 0; i < CmdListsCount; i++) + { + ImDrawList* cmd_list = CmdLists[i]; + if (cmd_list->IdxBuffer.empty()) + continue; + new_vtx_buffer.resize(cmd_list->IdxBuffer.Size); + for (int j = 0; j < cmd_list->IdxBuffer.Size; j++) + new_vtx_buffer[j] = cmd_list->VtxBuffer[cmd_list->IdxBuffer[j]]; + cmd_list->VtxBuffer.swap(new_vtx_buffer); + cmd_list->IdxBuffer.resize(0); + TotalVtxCount += cmd_list->VtxBuffer.Size; + } +} + +// Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. +void ImDrawData::ScaleClipRects(const ImVec2& scale) +{ + for (int i = 0; i < CmdListsCount; i++) + { + ImDrawList* cmd_list = CmdLists[i]; + for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) + { + ImDrawCmd* cmd = &cmd_list->CmdBuffer[cmd_i]; + cmd->ClipRect = ImVec4(cmd->ClipRect.x * scale.x, cmd->ClipRect.y * scale.y, cmd->ClipRect.z * scale.x, cmd->ClipRect.w * scale.y); + } + } +} + +//----------------------------------------------------------------------------- +// ImFontAtlas +//----------------------------------------------------------------------------- + +ImFontConfig::ImFontConfig() +{ + FontData = NULL; + FontDataSize = 0; + FontDataOwnedByAtlas = true; + FontNo = 0; + SizePixels = 0.0f; + OversampleH = 3; + OversampleV = 1; + PixelSnapH = false; + GlyphExtraSpacing = ImVec2(0.0f, 0.0f); + GlyphRanges = NULL; + MergeMode = false; + MergeGlyphCenterV = false; + DstFont = NULL; + memset(Name, 0, sizeof(Name)); +} + +ImFontAtlas::ImFontAtlas() +{ + TexID = NULL; + TexPixelsAlpha8 = NULL; + TexPixelsRGBA32 = NULL; + TexWidth = TexHeight = TexDesiredWidth = 0; + TexUvWhitePixel = ImVec2(0, 0); +} + +ImFontAtlas::~ImFontAtlas() +{ + Clear(); +} + +void ImFontAtlas::ClearInputData() +{ + for (int i = 0; i < ConfigData.Size; i++) + if (ConfigData[i].FontData && ConfigData[i].FontDataOwnedByAtlas) + { + ImGui::MemFree(ConfigData[i].FontData); + ConfigData[i].FontData = NULL; + } + + // When clearing this we lose access to the font name and other information used to build the font. + for (int i = 0; i < Fonts.Size; i++) + if (Fonts[i]->ConfigData >= ConfigData.Data && Fonts[i]->ConfigData < ConfigData.Data + ConfigData.Size) + { + Fonts[i]->ConfigData = NULL; + Fonts[i]->ConfigDataCount = 0; + } + ConfigData.clear(); +} + +void ImFontAtlas::ClearTexData() +{ + if (TexPixelsAlpha8) + ImGui::MemFree(TexPixelsAlpha8); + if (TexPixelsRGBA32) + ImGui::MemFree(TexPixelsRGBA32); + TexPixelsAlpha8 = NULL; + TexPixelsRGBA32 = NULL; +} + +void ImFontAtlas::ClearFonts() +{ + for (int i = 0; i < Fonts.Size; i++) + { + Fonts[i]->~ImFont(); + ImGui::MemFree(Fonts[i]); + } + Fonts.clear(); +} + +void ImFontAtlas::Clear() +{ + ClearInputData(); + ClearTexData(); + ClearFonts(); +} + +void ImFontAtlas::GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) +{ + // Build atlas on demand + if (TexPixelsAlpha8 == NULL) + { + if (ConfigData.empty()) + AddFontDefault(); + Build(); + } + + *out_pixels = TexPixelsAlpha8; + if (out_width) *out_width = TexWidth; + if (out_height) *out_height = TexHeight; + if (out_bytes_per_pixel) *out_bytes_per_pixel = 1; +} + +void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) +{ + // Convert to RGBA32 format on demand + // Although it is likely to be the most commonly used format, our font rendering is 1 channel / 8 bpp + if (!TexPixelsRGBA32) + { + unsigned char* pixels; + GetTexDataAsAlpha8(&pixels, NULL, NULL); + TexPixelsRGBA32 = (unsigned int*)ImGui::MemAlloc((size_t)(TexWidth * TexHeight * 4)); + const unsigned char* src = pixels; + unsigned int* dst = TexPixelsRGBA32; + for (int n = TexWidth * TexHeight; n > 0; n--) + *dst++ = ((unsigned int)(*src++) << 24) | 0x00FFFFFF; + } + + *out_pixels = (unsigned char*)TexPixelsRGBA32; + if (out_width) *out_width = TexWidth; + if (out_height) *out_height = TexHeight; + if (out_bytes_per_pixel) *out_bytes_per_pixel = 4; +} + +ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) +{ + IM_ASSERT(font_cfg->FontData != NULL && font_cfg->FontDataSize > 0); + IM_ASSERT(font_cfg->SizePixels > 0.0f); + + // Create new font + if (!font_cfg->MergeMode) + { + ImFont* font = (ImFont*)ImGui::MemAlloc(sizeof(ImFont)); + IM_PLACEMENT_NEW(font) ImFont(); + Fonts.push_back(font); + } + + ConfigData.push_back(*font_cfg); + ImFontConfig& new_font_cfg = ConfigData.back(); + if (!new_font_cfg.DstFont) + new_font_cfg.DstFont = Fonts.back(); + if (!new_font_cfg.FontDataOwnedByAtlas) + { + new_font_cfg.FontData = ImGui::MemAlloc(new_font_cfg.FontDataSize); + new_font_cfg.FontDataOwnedByAtlas = true; + memcpy(new_font_cfg.FontData, font_cfg->FontData, (size_t)new_font_cfg.FontDataSize); + } + + // Invalidate texture + ClearTexData(); + return new_font_cfg.DstFont; +} + +// Default font TTF is compressed with stb_compress then base85 encoded (see extra_fonts/binary_to_compressed_c.cpp for encoder) +static unsigned int stb_decompress_length(unsigned char *input); +static unsigned int stb_decompress(unsigned char *output, unsigned char *i, unsigned int length); +static const char* GetDefaultCompressedFontDataTTFBase85(); +static unsigned int Decode85Byte(char c) { return c >= '\\' ? c-36 : c-35; } +static void Decode85(const unsigned char* src, unsigned char* dst) +{ + while (*src) + { + unsigned int tmp = Decode85Byte(src[0]) + 85*(Decode85Byte(src[1]) + 85*(Decode85Byte(src[2]) + 85*(Decode85Byte(src[3]) + 85*Decode85Byte(src[4])))); + dst[0] = ((tmp >> 0) & 0xFF); dst[1] = ((tmp >> 8) & 0xFF); dst[2] = ((tmp >> 16) & 0xFF); dst[3] = ((tmp >> 24) & 0xFF); // We can't assume little-endianess. + src += 5; + dst += 4; + } +} + +// Load embedded ProggyClean.ttf at size 13, disable oversampling +ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template) +{ + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + if (!font_cfg_template) + { + font_cfg.OversampleH = font_cfg.OversampleV = 1; + font_cfg.PixelSnapH = true; + } + if (font_cfg.Name[0] == '\0') strcpy(font_cfg.Name, ""); + + const char* ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85(); + ImFont* font = AddFontFromMemoryCompressedBase85TTF(ttf_compressed_base85, 13.0f, &font_cfg, GetGlyphRangesDefault()); + return font; +} + +ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) +{ + int data_size = 0; + void* data = ImLoadFileToMemory(filename, "rb", &data_size, 0); + if (!data) + { + IM_ASSERT(0); // Could not load file. + return NULL; + } + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + if (font_cfg.Name[0] == '\0') + { + // Store a short copy of filename into into the font name for convenience + const char* p; + for (p = filename + strlen(filename); p > filename && p[-1] != '/' && p[-1] != '\\'; p--) {} + snprintf(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "%s", p); + } + return AddFontFromMemoryTTF(data, data_size, size_pixels, &font_cfg, glyph_ranges); +} + +// NBM Transfer ownership of 'ttf_data' to ImFontAtlas, unless font_cfg_template->FontDataOwnedByAtlas == false. Owned TTF buffer will be deleted after Build(). +ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) +{ + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + IM_ASSERT(font_cfg.FontData == NULL); + font_cfg.FontData = ttf_data; + font_cfg.FontDataSize = ttf_size; + font_cfg.SizePixels = size_pixels; + if (glyph_ranges) + font_cfg.GlyphRanges = glyph_ranges; + return AddFont(&font_cfg); +} + +ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) +{ + const unsigned int buf_decompressed_size = stb_decompress_length((unsigned char*)compressed_ttf_data); + unsigned char* buf_decompressed_data = (unsigned char *)ImGui::MemAlloc(buf_decompressed_size); + stb_decompress(buf_decompressed_data, (unsigned char*)compressed_ttf_data, (unsigned int)compressed_ttf_size); + + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + IM_ASSERT(font_cfg.FontData == NULL); + font_cfg.FontDataOwnedByAtlas = true; + return AddFontFromMemoryTTF(buf_decompressed_data, (int)buf_decompressed_size, size_pixels, &font_cfg, glyph_ranges); +} + +ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg, const ImWchar* glyph_ranges) +{ + int compressed_ttf_size = (((int)strlen(compressed_ttf_data_base85) + 4) / 5) * 4; + void* compressed_ttf = ImGui::MemAlloc((size_t)compressed_ttf_size); + Decode85((const unsigned char*)compressed_ttf_data_base85, (unsigned char*)compressed_ttf); + ImFont* font = AddFontFromMemoryCompressedTTF(compressed_ttf, compressed_ttf_size, size_pixels, font_cfg, glyph_ranges); + ImGui::MemFree(compressed_ttf); + return font; +} + +bool ImFontAtlas::Build() +{ + IM_ASSERT(ConfigData.Size > 0); + + TexID = NULL; + TexWidth = TexHeight = 0; + TexUvWhitePixel = ImVec2(0, 0); + ClearTexData(); + + struct ImFontTempBuildData + { + stbtt_fontinfo FontInfo; + stbrp_rect* Rects; + stbtt_pack_range* Ranges; + int RangesCount; + }; + ImFontTempBuildData* tmp_array = (ImFontTempBuildData*)ImGui::MemAlloc((size_t)ConfigData.Size * sizeof(ImFontTempBuildData)); + + // Initialize font information early (so we can error without any cleanup) + count glyphs + int total_glyph_count = 0; + int total_glyph_range_count = 0; + for (int input_i = 0; input_i < ConfigData.Size; input_i++) + { + ImFontConfig& cfg = ConfigData[input_i]; + ImFontTempBuildData& tmp = tmp_array[input_i]; + + IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == this)); + const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)cfg.FontData, cfg.FontNo); + IM_ASSERT(font_offset >= 0); + if (!stbtt_InitFont(&tmp.FontInfo, (unsigned char*)cfg.FontData, font_offset)) + return false; + + // Count glyphs + if (!cfg.GlyphRanges) + cfg.GlyphRanges = GetGlyphRangesDefault(); + for (const ImWchar* in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2) + { + total_glyph_count += (in_range[1] - in_range[0]) + 1; + total_glyph_range_count++; + } + } + + // Start packing. We need a known width for the skyline algorithm. Using a cheap heuristic here to decide of width. User can override TexDesiredWidth if they wish. + // After packing is done, width shouldn't matter much, but some API/GPU have texture size limitations and increasing width can decrease height. + TexWidth = (TexDesiredWidth > 0) ? TexDesiredWidth : (total_glyph_count > 4000) ? 4096 : (total_glyph_count > 2000) ? 2048 : (total_glyph_count > 1000) ? 1024 : 512; + TexHeight = 0; + const int max_tex_height = 1024*32; + stbtt_pack_context spc; + stbtt_PackBegin(&spc, NULL, TexWidth, max_tex_height, 0, 1, NULL); + + // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values). + ImVector extra_rects; + RenderCustomTexData(0, &extra_rects); + stbtt_PackSetOversampling(&spc, 1, 1); + stbrp_pack_rects((stbrp_context*)spc.pack_info, &extra_rects[0], extra_rects.Size); + for (int i = 0; i < extra_rects.Size; i++) + if (extra_rects[i].was_packed) + TexHeight = ImMax(TexHeight, extra_rects[i].y + extra_rects[i].h); + + // Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0) + int buf_packedchars_n = 0, buf_rects_n = 0, buf_ranges_n = 0; + stbtt_packedchar* buf_packedchars = (stbtt_packedchar*)ImGui::MemAlloc(total_glyph_count * sizeof(stbtt_packedchar)); + stbrp_rect* buf_rects = (stbrp_rect*)ImGui::MemAlloc(total_glyph_count * sizeof(stbrp_rect)); + stbtt_pack_range* buf_ranges = (stbtt_pack_range*)ImGui::MemAlloc(total_glyph_range_count * sizeof(stbtt_pack_range)); + memset(buf_packedchars, 0, total_glyph_count * sizeof(stbtt_packedchar)); + memset(buf_rects, 0, total_glyph_count * sizeof(stbrp_rect)); // Unnecessary but let's clear this for the sake of sanity. + memset(buf_ranges, 0, total_glyph_range_count * sizeof(stbtt_pack_range)); + + // First font pass: pack all glyphs (no rendering at this point, we are working with rectangles in an infinitely tall texture at this point) + for (int input_i = 0; input_i < ConfigData.Size; input_i++) + { + ImFontConfig& cfg = ConfigData[input_i]; + ImFontTempBuildData& tmp = tmp_array[input_i]; + + // Setup ranges + int glyph_count = 0; + int glyph_ranges_count = 0; + for (const ImWchar* in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2) + { + glyph_count += (in_range[1] - in_range[0]) + 1; + glyph_ranges_count++; + } + tmp.Ranges = buf_ranges + buf_ranges_n; + tmp.RangesCount = glyph_ranges_count; + buf_ranges_n += glyph_ranges_count; + for (int i = 0; i < glyph_ranges_count; i++) + { + const ImWchar* in_range = &cfg.GlyphRanges[i * 2]; + stbtt_pack_range& range = tmp.Ranges[i]; + range.font_size = cfg.SizePixels; + range.first_unicode_codepoint_in_range = in_range[0]; + range.num_chars = (in_range[1] - in_range[0]) + 1; + range.chardata_for_range = buf_packedchars + buf_packedchars_n; + buf_packedchars_n += range.num_chars; + } + + // Pack + tmp.Rects = buf_rects + buf_rects_n; + buf_rects_n += glyph_count; + stbtt_PackSetOversampling(&spc, cfg.OversampleH, cfg.OversampleV); + int n = stbtt_PackFontRangesGatherRects(&spc, &tmp.FontInfo, tmp.Ranges, tmp.RangesCount, tmp.Rects); + stbrp_pack_rects((stbrp_context*)spc.pack_info, tmp.Rects, n); + + // Extend texture height + for (int i = 0; i < n; i++) + if (tmp.Rects[i].was_packed) + TexHeight = ImMax(TexHeight, tmp.Rects[i].y + tmp.Rects[i].h); + } + IM_ASSERT(buf_rects_n == total_glyph_count); + IM_ASSERT(buf_packedchars_n == total_glyph_count); + IM_ASSERT(buf_ranges_n == total_glyph_range_count); + + // Create texture + TexHeight = ImUpperPowerOfTwo(TexHeight); + TexPixelsAlpha8 = (unsigned char*)ImGui::MemAlloc(TexWidth * TexHeight); + memset(TexPixelsAlpha8, 0, TexWidth * TexHeight); + spc.pixels = TexPixelsAlpha8; + spc.height = TexHeight; + + // Second pass: render characters + for (int input_i = 0; input_i < ConfigData.Size; input_i++) + { + ImFontConfig& cfg = ConfigData[input_i]; + ImFontTempBuildData& tmp = tmp_array[input_i]; + stbtt_PackSetOversampling(&spc, cfg.OversampleH, cfg.OversampleV); + stbtt_PackFontRangesRenderIntoRects(&spc, &tmp.FontInfo, tmp.Ranges, tmp.RangesCount, tmp.Rects); + tmp.Rects = NULL; + } + + // End packing + stbtt_PackEnd(&spc); + ImGui::MemFree(buf_rects); + buf_rects = NULL; + + // Third pass: setup ImFont and glyphs for runtime + for (int input_i = 0; input_i < ConfigData.Size; input_i++) + { + ImFontConfig& cfg = ConfigData[input_i]; + ImFontTempBuildData& tmp = tmp_array[input_i]; + ImFont* dst_font = cfg.DstFont; + + float font_scale = stbtt_ScaleForPixelHeight(&tmp.FontInfo, cfg.SizePixels); + int unscaled_ascent, unscaled_descent, unscaled_line_gap; + stbtt_GetFontVMetrics(&tmp.FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); + + float ascent = unscaled_ascent * font_scale; + float descent = unscaled_descent * font_scale; + if (!cfg.MergeMode) + { + dst_font->ContainerAtlas = this; + dst_font->ConfigData = &cfg; + dst_font->ConfigDataCount = 0; + dst_font->FontSize = cfg.SizePixels; + dst_font->Ascent = ascent; + dst_font->Descent = descent; + dst_font->Glyphs.resize(0); + } + dst_font->ConfigDataCount++; + float off_y = (cfg.MergeMode && cfg.MergeGlyphCenterV) ? (ascent - dst_font->Ascent) * 0.5f : 0.0f; + + dst_font->FallbackGlyph = NULL; // Always clear fallback so FindGlyph can return NULL. It will be set again in BuildLookupTable() + for (int i = 0; i < tmp.RangesCount; i++) + { + stbtt_pack_range& range = tmp.Ranges[i]; + for (int char_idx = 0; char_idx < range.num_chars; char_idx += 1) + { + const stbtt_packedchar& pc = range.chardata_for_range[char_idx]; + if (!pc.x0 && !pc.x1 && !pc.y0 && !pc.y1) + continue; + + const int codepoint = range.first_unicode_codepoint_in_range + char_idx; + if (cfg.MergeMode && dst_font->FindGlyph((unsigned short)codepoint)) + continue; + + stbtt_aligned_quad q; + float dummy_x = 0.0f, dummy_y = 0.0f; + stbtt_GetPackedQuad(range.chardata_for_range, TexWidth, TexHeight, char_idx, &dummy_x, &dummy_y, &q, 0); + + dst_font->Glyphs.resize(dst_font->Glyphs.Size + 1); + ImFont::Glyph& glyph = dst_font->Glyphs.back(); + glyph.Codepoint = (ImWchar)codepoint; + glyph.X0 = q.x0; glyph.Y0 = q.y0; glyph.X1 = q.x1; glyph.Y1 = q.y1; + glyph.U0 = q.s0; glyph.V0 = q.t0; glyph.U1 = q.s1; glyph.V1 = q.t1; + glyph.Y0 += (float)(int)(dst_font->Ascent + off_y + 0.5f); + glyph.Y1 += (float)(int)(dst_font->Ascent + off_y + 0.5f); + glyph.XAdvance = (pc.xadvance + cfg.GlyphExtraSpacing.x); // Bake spacing into XAdvance + if (cfg.PixelSnapH) + glyph.XAdvance = (float)(int)(glyph.XAdvance + 0.5f); + } + } + cfg.DstFont->BuildLookupTable(); + } + + // Cleanup temporaries + ImGui::MemFree(buf_packedchars); + ImGui::MemFree(buf_ranges); + ImGui::MemFree(tmp_array); + + // Render into our custom data block + RenderCustomTexData(1, &extra_rects); + + return true; +} + +void ImFontAtlas::RenderCustomTexData(int pass, void* p_rects) +{ + // A work of art lies ahead! (. = white layer, X = black layer, others are blank) + // The white texels on the top left are the ones we'll use everywhere in ImGui to render filled shapes. + const int TEX_DATA_W = 90; + const int TEX_DATA_H = 27; + const char texture_data[TEX_DATA_W*TEX_DATA_H+1] = + { + "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX" + "..- -X.....X- X.X - X.X -X.....X - X.....X" + "--- -XXX.XXX- X...X - X...X -X....X - X....X" + "X - X.X - X.....X - X.....X -X...X - X...X" + "XX - X.X -X.......X- X.......X -X..X.X - X.X..X" + "X.X - X.X -XXXX.XXXX- XXXX.XXXX -X.X X.X - X.X X.X" + "X..X - X.X - X.X - X.X -XX X.X - X.X XX" + "X...X - X.X - X.X - XX X.X XX - X.X - X.X " + "X....X - X.X - X.X - X.X X.X X.X - X.X - X.X " + "X.....X - X.X - X.X - X..X X.X X..X - X.X - X.X " + "X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-XX X.X " + "X.......X - X.X - X.X -X.....................X- X.X X.X-X.X X.X " + "X........X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X..X-X..X.X " + "X.........X -XXX.XXX- X.X - X..X X.X X..X - X...X-X...X " + "X..........X-X.....X- X.X - X.X X.X X.X - X....X-X....X " + "X......XXXXX-XXXXXXX- X.X - XX X.X XX - X.....X-X.....X " + "X...X..X --------- X.X - X.X - XXXXXXX-XXXXXXX " + "X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------" + "X.X X..X - -X.......X- X.......X - XX XX - " + "XX X..X - - X.....X - X.....X - X.X X.X - " + " X..X - X...X - X...X - X..X X..X - " + " XX - X.X - X.X - X...XXXXXXXXXXXXX...X - " + "------------ - X - X -X.....................X- " + " ----------------------------------- X...XXXXXXXXXXXXX...X - " + " - X..X X..X - " + " - X.X X.X - " + " - XX XX - " + }; + + ImVector& rects = *(ImVector*)p_rects; + if (pass == 0) + { + // Request rectangles + stbrp_rect r; + memset(&r, 0, sizeof(r)); + r.w = (TEX_DATA_W*2)+1; + r.h = TEX_DATA_H+1; + rects.push_back(r); + } + else if (pass == 1) + { + // Render/copy pixels + const stbrp_rect& r = rects[0]; + for (int y = 0, n = 0; y < TEX_DATA_H; y++) + for (int x = 0; x < TEX_DATA_W; x++, n++) + { + const int offset0 = (int)(r.x + x) + (int)(r.y + y) * TexWidth; + const int offset1 = offset0 + 1 + TEX_DATA_W; + TexPixelsAlpha8[offset0] = texture_data[n] == '.' ? 0xFF : 0x00; + TexPixelsAlpha8[offset1] = texture_data[n] == 'X' ? 0xFF : 0x00; + } + const ImVec2 tex_uv_scale(1.0f / TexWidth, 1.0f / TexHeight); + TexUvWhitePixel = ImVec2((r.x + 0.5f) * tex_uv_scale.x, (r.y + 0.5f) * tex_uv_scale.y); + + // Setup mouse cursors + const ImVec2 cursor_datas[ImGuiMouseCursor_Count_][3] = + { + // Pos ........ Size ......... Offset ...... + { ImVec2(0,3), ImVec2(12,19), ImVec2( 0, 0) }, // ImGuiMouseCursor_Arrow + { ImVec2(13,0), ImVec2(7,16), ImVec2( 4, 8) }, // ImGuiMouseCursor_TextInput + { ImVec2(31,0), ImVec2(23,23), ImVec2(11,11) }, // ImGuiMouseCursor_Move + { ImVec2(21,0), ImVec2( 9,23), ImVec2( 5,11) }, // ImGuiMouseCursor_ResizeNS + { ImVec2(55,18),ImVec2(23, 9), ImVec2(11, 5) }, // ImGuiMouseCursor_ResizeEW + { ImVec2(73,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNESW + { ImVec2(55,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNWSE + }; + + for (int type = 0; type < ImGuiMouseCursor_Count_; type++) + { + ImGuiMouseCursorData& cursor_data = GImGui->MouseCursorData[type]; + ImVec2 pos = cursor_datas[type][0] + ImVec2((float)r.x, (float)r.y); + const ImVec2 size = cursor_datas[type][1]; + cursor_data.Type = type; + cursor_data.Size = size; + cursor_data.HotOffset = cursor_datas[type][2]; + cursor_data.TexUvMin[0] = (pos) * tex_uv_scale; + cursor_data.TexUvMax[0] = (pos + size) * tex_uv_scale; + pos.x += TEX_DATA_W+1; + cursor_data.TexUvMin[1] = (pos) * tex_uv_scale; + cursor_data.TexUvMax[1] = (pos + size) * tex_uv_scale; + } + } +} + +// Retrieve list of range (2 int per range, values are inclusive) +const ImWchar* ImFontAtlas::GetGlyphRangesDefault() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesKorean() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x3131, 0x3163, // Korean alphabets + 0xAC00, 0xD79D, // Korean characters + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesChinese() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x3000, 0x30FF, // Punctuations, Hiragana, Katakana + 0x31F0, 0x31FF, // Katakana Phonetic Extensions + 0xFF00, 0xFFEF, // Half-width characters + 0x4e00, 0x9FAF, // CJK Ideograms + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesJapanese() +{ + // Store the 1946 ideograms code points as successive offsets from the initial unicode codepoint 0x4E00. Each offset has an implicit +1. + // This encoding helps us reduce the source code size. + static const short offsets_from_0x4E00[] = + { + -1,0,1,3,0,0,0,0,1,0,5,1,1,0,7,4,6,10,0,1,9,9,7,1,3,19,1,10,7,1,0,1,0,5,1,0,6,4,2,6,0,0,12,6,8,0,3,5,0,1,0,9,0,0,8,1,1,3,4,5,13,0,0,8,2,17, + 4,3,1,1,9,6,0,0,0,2,1,3,2,22,1,9,11,1,13,1,3,12,0,5,9,2,0,6,12,5,3,12,4,1,2,16,1,1,4,6,5,3,0,6,13,15,5,12,8,14,0,0,6,15,3,6,0,18,8,1,6,14,1, + 5,4,12,24,3,13,12,10,24,0,0,0,1,0,1,1,2,9,10,2,2,0,0,3,3,1,0,3,8,0,3,2,4,4,1,6,11,10,14,6,15,3,4,15,1,0,0,5,2,2,0,0,1,6,5,5,6,0,3,6,5,0,0,1,0, + 11,2,2,8,4,7,0,10,0,1,2,17,19,3,0,2,5,0,6,2,4,4,6,1,1,11,2,0,3,1,2,1,2,10,7,6,3,16,0,8,24,0,0,3,1,1,3,0,1,6,0,0,0,2,0,1,5,15,0,1,0,0,2,11,19, + 1,4,19,7,6,5,1,0,0,0,0,5,1,0,1,9,0,0,5,0,2,0,1,0,3,0,11,3,0,2,0,0,0,0,0,9,3,6,4,12,0,14,0,0,29,10,8,0,14,37,13,0,31,16,19,0,8,30,1,20,8,3,48, + 21,1,0,12,0,10,44,34,42,54,11,18,82,0,2,1,2,12,1,0,6,2,17,2,12,7,0,7,17,4,2,6,24,23,8,23,39,2,16,23,1,0,5,1,2,15,14,5,6,2,11,0,8,6,2,2,2,14, + 20,4,15,3,4,11,10,10,2,5,2,1,30,2,1,0,0,22,5,5,0,3,1,5,4,1,0,0,2,2,21,1,5,1,2,16,2,1,3,4,0,8,4,0,0,5,14,11,2,16,1,13,1,7,0,22,15,3,1,22,7,14, + 22,19,11,24,18,46,10,20,64,45,3,2,0,4,5,0,1,4,25,1,0,0,2,10,0,0,0,1,0,1,2,0,0,9,1,2,0,0,0,2,5,2,1,1,5,5,8,1,1,1,5,1,4,9,1,3,0,1,0,1,1,2,0,0, + 2,0,1,8,22,8,1,0,0,0,0,4,2,1,0,9,8,5,0,9,1,30,24,2,6,4,39,0,14,5,16,6,26,179,0,2,1,1,0,0,0,5,2,9,6,0,2,5,16,7,5,1,1,0,2,4,4,7,15,13,14,0,0, + 3,0,1,0,0,0,2,1,6,4,5,1,4,9,0,3,1,8,0,0,10,5,0,43,0,2,6,8,4,0,2,0,0,9,6,0,9,3,1,6,20,14,6,1,4,0,7,2,3,0,2,0,5,0,3,1,0,3,9,7,0,3,4,0,4,9,1,6,0, + 9,0,0,2,3,10,9,28,3,6,2,4,1,2,32,4,1,18,2,0,3,1,5,30,10,0,2,2,2,0,7,9,8,11,10,11,7,2,13,7,5,10,0,3,40,2,0,1,6,12,0,4,5,1,5,11,11,21,4,8,3,7, + 8,8,33,5,23,0,0,19,8,8,2,3,0,6,1,1,1,5,1,27,4,2,5,0,3,5,6,3,1,0,3,1,12,5,3,3,2,0,7,7,2,1,0,4,0,1,1,2,0,10,10,6,2,5,9,7,5,15,15,21,6,11,5,20, + 4,3,5,5,2,5,0,2,1,0,1,7,28,0,9,0,5,12,5,5,18,30,0,12,3,3,21,16,25,32,9,3,14,11,24,5,66,9,1,2,0,5,9,1,5,1,8,0,8,3,3,0,1,15,1,4,8,1,2,7,0,7,2, + 8,3,7,5,3,7,10,2,1,0,0,2,25,0,6,4,0,10,0,4,2,4,1,12,5,38,4,0,4,1,10,5,9,4,0,14,4,2,5,18,20,21,1,3,0,5,0,7,0,3,7,1,3,1,1,8,1,0,0,0,3,2,5,2,11, + 6,0,13,1,3,9,1,12,0,16,6,2,1,0,2,1,12,6,13,11,2,0,28,1,7,8,14,13,8,13,0,2,0,5,4,8,10,2,37,42,19,6,6,7,4,14,11,18,14,80,7,6,0,4,72,12,36,27, + 7,7,0,14,17,19,164,27,0,5,10,7,3,13,6,14,0,2,2,5,3,0,6,13,0,0,10,29,0,4,0,3,13,0,3,1,6,51,1,5,28,2,0,8,0,20,2,4,0,25,2,10,13,10,0,16,4,0,1,0, + 2,1,7,0,1,8,11,0,0,1,2,7,2,23,11,6,6,4,16,2,2,2,0,22,9,3,3,5,2,0,15,16,21,2,9,20,15,15,5,3,9,1,0,0,1,7,7,5,4,2,2,2,38,24,14,0,0,15,5,6,24,14, + 5,5,11,0,21,12,0,3,8,4,11,1,8,0,11,27,7,2,4,9,21,59,0,1,39,3,60,62,3,0,12,11,0,3,30,11,0,13,88,4,15,5,28,13,1,4,48,17,17,4,28,32,46,0,16,0, + 18,11,1,8,6,38,11,2,6,11,38,2,0,45,3,11,2,7,8,4,30,14,17,2,1,1,65,18,12,16,4,2,45,123,12,56,33,1,4,3,4,7,0,0,0,3,2,0,16,4,2,4,2,0,7,4,5,2,26, + 2,25,6,11,6,1,16,2,6,17,77,15,3,35,0,1,0,5,1,0,38,16,6,3,12,3,3,3,0,9,3,1,3,5,2,9,0,18,0,25,1,3,32,1,72,46,6,2,7,1,3,14,17,0,28,1,40,13,0,20, + 15,40,6,38,24,12,43,1,1,9,0,12,6,0,6,2,4,19,3,7,1,48,0,9,5,0,5,6,9,6,10,15,2,11,19,3,9,2,0,1,10,1,27,8,1,3,6,1,14,0,26,0,27,16,3,4,9,6,2,23, + 9,10,5,25,2,1,6,1,1,48,15,9,15,14,3,4,26,60,29,13,37,21,1,6,4,0,2,11,22,23,16,16,2,2,1,3,0,5,1,6,4,0,0,4,0,0,8,3,0,2,5,0,7,1,7,3,13,2,4,10, + 3,0,2,31,0,18,3,0,12,10,4,1,0,7,5,7,0,5,4,12,2,22,10,4,2,15,2,8,9,0,23,2,197,51,3,1,1,4,13,4,3,21,4,19,3,10,5,40,0,4,1,1,10,4,1,27,34,7,21, + 2,17,2,9,6,4,2,3,0,4,2,7,8,2,5,1,15,21,3,4,4,2,2,17,22,1,5,22,4,26,7,0,32,1,11,42,15,4,1,2,5,0,19,3,1,8,6,0,10,1,9,2,13,30,8,2,24,17,19,1,4, + 4,25,13,0,10,16,11,39,18,8,5,30,82,1,6,8,18,77,11,13,20,75,11,112,78,33,3,0,0,60,17,84,9,1,1,12,30,10,49,5,32,158,178,5,5,6,3,3,1,3,1,4,7,6, + 19,31,21,0,2,9,5,6,27,4,9,8,1,76,18,12,1,4,0,3,3,6,3,12,2,8,30,16,2,25,1,5,5,4,3,0,6,10,2,3,1,0,5,1,19,3,0,8,1,5,2,6,0,0,0,19,1,2,0,5,1,2,5, + 1,3,7,0,4,12,7,3,10,22,0,9,5,1,0,2,20,1,1,3,23,30,3,9,9,1,4,191,14,3,15,6,8,50,0,1,0,0,4,0,0,1,0,2,4,2,0,2,3,0,2,0,2,2,8,7,0,1,1,1,3,3,17,11, + 91,1,9,3,2,13,4,24,15,41,3,13,3,1,20,4,125,29,30,1,0,4,12,2,21,4,5,5,19,11,0,13,11,86,2,18,0,7,1,8,8,2,2,22,1,2,6,5,2,0,1,2,8,0,2,0,5,2,1,0, + 2,10,2,0,5,9,2,1,2,0,1,0,4,0,0,10,2,5,3,0,6,1,0,1,4,4,33,3,13,17,3,18,6,4,7,1,5,78,0,4,1,13,7,1,8,1,0,35,27,15,3,0,0,0,1,11,5,41,38,15,22,6, + 14,14,2,1,11,6,20,63,5,8,27,7,11,2,2,40,58,23,50,54,56,293,8,8,1,5,1,14,0,1,12,37,89,8,8,8,2,10,6,0,0,0,4,5,2,1,0,1,1,2,7,0,3,3,0,4,6,0,3,2, + 19,3,8,0,0,0,4,4,16,0,4,1,5,1,3,0,3,4,6,2,17,10,10,31,6,4,3,6,10,126,7,3,2,2,0,9,0,0,5,20,13,0,15,0,6,0,2,5,8,64,50,3,2,12,2,9,0,0,11,8,20, + 109,2,18,23,0,0,9,61,3,0,28,41,77,27,19,17,81,5,2,14,5,83,57,252,14,154,263,14,20,8,13,6,57,39,38, + }; + static ImWchar base_ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x3000, 0x30FF, // Punctuations, Hiragana, Katakana + 0x31F0, 0x31FF, // Katakana Phonetic Extensions + 0xFF00, 0xFFEF, // Half-width characters + }; + static bool full_ranges_unpacked = false; + static ImWchar full_ranges[IM_ARRAYSIZE(base_ranges) + IM_ARRAYSIZE(offsets_from_0x4E00)*2 + 1]; + if (!full_ranges_unpacked) + { + // Unpack + int codepoint = 0x4e00; + memcpy(full_ranges, base_ranges, sizeof(base_ranges)); + ImWchar* dst = full_ranges + IM_ARRAYSIZE(base_ranges);; + for (int n = 0; n < IM_ARRAYSIZE(offsets_from_0x4E00); n++, dst += 2) + dst[0] = dst[1] = (ImWchar)(codepoint += (offsets_from_0x4E00[n] + 1)); + dst[0] = 0; + full_ranges_unpacked = true; + } + return &full_ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesCyrillic() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x0400, 0x052F, // Cyrillic + Cyrillic Supplement + 0x2DE0, 0x2DFF, // Cyrillic Extended-A + 0xA640, 0xA69F, // Cyrillic Extended-B + 0, + }; + return &ranges[0]; +} + +//----------------------------------------------------------------------------- +// ImFont +//----------------------------------------------------------------------------- + +ImFont::ImFont() +{ + Scale = 1.0f; + FallbackChar = (ImWchar)'?'; + Clear(); +} + +ImFont::~ImFont() +{ + // Invalidate active font so that the user gets a clear crash instead of a dangling pointer. + // If you want to delete fonts you need to do it between Render() and NewFrame(). + // FIXME-CLEANUP + /* + ImGuiContext& g = *GImGui; + if (g.Font == this) + g.Font = NULL; + */ + Clear(); +} + +void ImFont::Clear() +{ + FontSize = 0.0f; + DisplayOffset = ImVec2(0.0f, 1.0f); + ConfigData = NULL; + ConfigDataCount = 0; + Ascent = Descent = 0.0f; + ContainerAtlas = NULL; + Glyphs.clear(); + FallbackGlyph = NULL; + FallbackXAdvance = 0.0f; + IndexXAdvance.clear(); + IndexLookup.clear(); +} + +void ImFont::BuildLookupTable() +{ + int max_codepoint = 0; + for (int i = 0; i != Glyphs.Size; i++) + max_codepoint = ImMax(max_codepoint, (int)Glyphs[i].Codepoint); + + IM_ASSERT(Glyphs.Size < 32*1024); + IndexXAdvance.clear(); + IndexLookup.clear(); + GrowIndex(max_codepoint + 1); + for (int i = 0; i < Glyphs.Size; i++) + { + int codepoint = (int)Glyphs[i].Codepoint; + IndexXAdvance[codepoint] = Glyphs[i].XAdvance; + IndexLookup[codepoint] = (short)i; + } + + // Create a glyph to handle TAB + // FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?) + if (FindGlyph((unsigned short)' ')) + { + if (Glyphs.back().Codepoint != '\t') // So we can call this function multiple times + Glyphs.resize(Glyphs.Size + 1); + ImFont::Glyph& tab_glyph = Glyphs.back(); + tab_glyph = *FindGlyph((unsigned short)' '); + tab_glyph.Codepoint = '\t'; + tab_glyph.XAdvance *= 4; + IndexXAdvance[(int)tab_glyph.Codepoint] = (float)tab_glyph.XAdvance; + IndexLookup[(int)tab_glyph.Codepoint] = (short)(Glyphs.Size-1); + } + + FallbackGlyph = NULL; + FallbackGlyph = FindGlyph(FallbackChar); + FallbackXAdvance = FallbackGlyph ? FallbackGlyph->XAdvance : 0.0f; + for (int i = 0; i < max_codepoint + 1; i++) + if (IndexXAdvance[i] < 0.0f) + IndexXAdvance[i] = FallbackXAdvance; +} + +void ImFont::SetFallbackChar(ImWchar c) +{ + FallbackChar = c; + BuildLookupTable(); +} + +void ImFont::GrowIndex(int new_size) +{ + IM_ASSERT(IndexXAdvance.Size == IndexLookup.Size); + int old_size = IndexLookup.Size; + if (new_size <= old_size) + return; + IndexXAdvance.resize(new_size); + IndexLookup.resize(new_size); + for (int i = old_size; i < new_size; i++) + { + IndexXAdvance[i] = -1.0f; + IndexLookup[i] = (short)-1; + } +} + +void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst) +{ + IM_ASSERT(IndexLookup.Size > 0); // Currently this can only be called AFTER the font has been built, aka after calling ImFontAtlas::GetTexDataAs*() function. + int index_size = IndexLookup.Size; + + if (dst < index_size && IndexLookup.Data[dst] == -1 && !overwrite_dst) // 'dst' already exists + return; + if (src >= index_size && dst >= index_size) // both 'dst' and 'src' don't exist -> no-op + return; + + GrowIndex(dst + 1); + IndexLookup[dst] = (src < index_size) ? IndexLookup.Data[src] : -1; + IndexXAdvance[dst] = (src < index_size) ? IndexXAdvance.Data[src] : 1.0f; +} + +const ImFont::Glyph* ImFont::FindGlyph(unsigned short c) const +{ + if (c < IndexLookup.Size) + { + const short i = IndexLookup[c]; + if (i != -1) + return &Glyphs.Data[i]; + } + return FallbackGlyph; +} + +const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const +{ + // Simple word-wrapping for English, not full-featured. Please submit failing cases! + // FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.) + + // For references, possible wrap point marked with ^ + // "aaa bbb, ccc,ddd. eee fff. ggg!" + // ^ ^ ^ ^ ^__ ^ ^ + + // List of hardcoded separators: .,;!?'" + + // Skip extra blanks after a line returns (that includes not counting them in width computation) + // e.g. "Hello world" --> "Hello" "World" + + // Cut words that cannot possibly fit within one line. + // e.g.: "The tropical fish" with ~5 characters worth of width --> "The tr" "opical" "fish" + + float line_width = 0.0f; + float word_width = 0.0f; + float blank_width = 0.0f; + + const char* word_end = text; + const char* prev_word_end = NULL; + bool inside_word = true; + + const char* s = text; + while (s < text_end) + { + unsigned int c = (unsigned int)*s; + const char* next_s; + if (c < 0x80) + next_s = s + 1; + else + next_s = s + ImTextCharFromUtf8(&c, s, text_end); + if (c == 0) + break; + + if (c < 32) + { + if (c == '\n') + { + line_width = word_width = blank_width = 0.0f; + inside_word = true; + s = next_s; + continue; + } + if (c == '\r') + { + s = next_s; + continue; + } + } + + const float char_width = ((int)c < IndexXAdvance.Size) ? IndexXAdvance[(int)c] * scale : FallbackXAdvance; + if (ImCharIsSpace(c)) + { + if (inside_word) + { + line_width += blank_width; + blank_width = 0.0f; + } + blank_width += char_width; + inside_word = false; + } + else + { + word_width += char_width; + if (inside_word) + { + word_end = next_s; + } + else + { + prev_word_end = word_end; + line_width += word_width + blank_width; + word_width = blank_width = 0.0f; + } + + // Allow wrapping after punctuation. + inside_word = !(c == '.' || c == ',' || c == ';' || c == '!' || c == '?' || c == '\"'); + } + + // We ignore blank width at the end of the line (they can be skipped) + if (line_width + word_width >= wrap_width) + { + // Words that cannot possibly fit within an entire line will be cut anywhere. + if (word_width < wrap_width) + s = prev_word_end ? prev_word_end : word_end; + break; + } + + s = next_s; + } + + return s; +} + +ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** remaining) const +{ + if (!text_end) + text_end = text_begin + strlen(text_begin); // FIXME-OPT: Need to avoid this. + + const float line_height = size; + const float scale = size / FontSize; + + ImVec2 text_size = ImVec2(0,0); + float line_width = 0.0f; + + const bool word_wrap_enabled = (wrap_width > 0.0f); + const char* word_wrap_eol = NULL; + + const char* s = text_begin; + while (s < text_end) + { + if (word_wrap_enabled) + { + // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. + if (!word_wrap_eol) + { + word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - line_width); + if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. + word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below + } + + if (s >= word_wrap_eol) + { + if (text_size.x < line_width) + text_size.x = line_width; + text_size.y += line_height; + line_width = 0.0f; + word_wrap_eol = NULL; + + // Wrapping skips upcoming blanks + while (s < text_end) + { + const char c = *s; + if (ImCharIsSpace(c)) { s++; } else if (c == '\n') { s++; break; } else { break; } + } + continue; + } + } + + // Decode and advance source + const char* prev_s = s; + unsigned int c = (unsigned int)*s; + if (c < 0x80) + { + s += 1; + } + else + { + s += ImTextCharFromUtf8(&c, s, text_end); + if (c == 0) + break; + } + + if (c < 32) + { + if (c == '\n') + { + text_size.x = ImMax(text_size.x, line_width); + text_size.y += line_height; + line_width = 0.0f; + continue; + } + if (c == '\r') + continue; + } + + const float char_width = ((int)c < IndexXAdvance.Size ? IndexXAdvance[(int)c] : FallbackXAdvance) * scale; + if (line_width + char_width >= max_width) + { + s = prev_s; + break; + } + + line_width += char_width; + } + + if (text_size.x < line_width) + text_size.x = line_width; + + if (line_width > 0 || text_size.y == 0.0f) + text_size.y += line_height; + + if (remaining) + *remaining = s; + + return text_size; +} + +void ImFont::RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, unsigned short c) const +{ + if (c == ' ' || c == '\t' || c == '\n' || c == '\r') // Match behavior of RenderText(), those 4 codepoints are hard-coded. + return; + if (const Glyph* glyph = FindGlyph(c)) + { + float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f; + pos.x = (float)(int)pos.x + DisplayOffset.x; + pos.y = (float)(int)pos.y + DisplayOffset.y; + ImVec2 pos_tl(pos.x + glyph->X0 * scale, pos.y + glyph->Y0 * scale); + ImVec2 pos_br(pos.x + glyph->X1 * scale, pos.y + glyph->Y1 * scale); + draw_list->PrimReserve(6, 4); + draw_list->PrimRectUV(pos_tl, pos_br, ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1), col); + } +} + +void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width, bool cpu_fine_clip) const +{ + if (!text_end) + text_end = text_begin + strlen(text_begin); + + // Align to be pixel perfect + pos.x = (float)(int)pos.x + DisplayOffset.x; + pos.y = (float)(int)pos.y + DisplayOffset.y; + float x = pos.x; + float y = pos.y; + if (y > clip_rect.w) + return; + + const float scale = size / FontSize; + const float line_height = FontSize * scale; + const bool word_wrap_enabled = (wrap_width > 0.0f); + const char* word_wrap_eol = NULL; + + // Skip non-visible lines + const char* s = text_begin; + if (!word_wrap_enabled && y + line_height < clip_rect.y) + while (s < text_end && *s != '\n') // Fast-forward to next line + s++; + + // Reserve vertices for remaining worse case (over-reserving is useful and easily amortized) + const int vtx_count_max = (int)(text_end - s) * 4; + const int idx_count_max = (int)(text_end - s) * 6; + const int idx_expected_size = draw_list->IdxBuffer.Size + idx_count_max; + draw_list->PrimReserve(idx_count_max, vtx_count_max); + + ImDrawVert* vtx_write = draw_list->_VtxWritePtr; + ImDrawIdx* idx_write = draw_list->_IdxWritePtr; + unsigned int vtx_current_idx = draw_list->_VtxCurrentIdx; + + while (s < text_end) + { + if (word_wrap_enabled) + { + // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. + if (!word_wrap_eol) + { + word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - (x - pos.x)); + if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. + word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below + } + + if (s >= word_wrap_eol) + { + x = pos.x; + y += line_height; + word_wrap_eol = NULL; + + // Wrapping skips upcoming blanks + while (s < text_end) + { + const char c = *s; + if (ImCharIsSpace(c)) { s++; } else if (c == '\n') { s++; break; } else { break; } + } + continue; + } + } + + // Decode and advance source + unsigned int c = (unsigned int)*s; + if (c < 0x80) + { + s += 1; + } + else + { + s += ImTextCharFromUtf8(&c, s, text_end); + if (c == 0) + break; + } + + if (c < 32) + { + if (c == '\n') + { + x = pos.x; + y += line_height; + + if (y > clip_rect.w) + break; + if (!word_wrap_enabled && y + line_height < clip_rect.y) + while (s < text_end && *s != '\n') // Fast-forward to next line + s++; + continue; + } + if (c == '\r') + continue; + } + + float char_width = 0.0f; + if (const Glyph* glyph = FindGlyph((unsigned short)c)) + { + char_width = glyph->XAdvance * scale; + + // Arbitrarily assume that both space and tabs are empty glyphs as an optimization + if (c != ' ' && c != '\t') + { + // We don't do a second finer clipping test on the Y axis as we've already skipped anything before clip_rect.y and exit once we pass clip_rect.w + float x1 = x + glyph->X0 * scale; + float x2 = x + glyph->X1 * scale; + float y1 = y + glyph->Y0 * scale; + float y2 = y + glyph->Y1 * scale; + if (x1 <= clip_rect.z && x2 >= clip_rect.x) + { + // Render a character + float u1 = glyph->U0; + float v1 = glyph->V0; + float u2 = glyph->U1; + float v2 = glyph->V1; + + // CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads. + if (cpu_fine_clip) + { + if (x1 < clip_rect.x) + { + u1 = u1 + (1.0f - (x2 - clip_rect.x) / (x2 - x1)) * (u2 - u1); + x1 = clip_rect.x; + } + if (y1 < clip_rect.y) + { + v1 = v1 + (1.0f - (y2 - clip_rect.y) / (y2 - y1)) * (v2 - v1); + y1 = clip_rect.y; + } + if (x2 > clip_rect.z) + { + u2 = u1 + ((clip_rect.z - x1) / (x2 - x1)) * (u2 - u1); + x2 = clip_rect.z; + } + if (y2 > clip_rect.w) + { + v2 = v1 + ((clip_rect.w - y1) / (y2 - y1)) * (v2 - v1); + y2 = clip_rect.w; + } + if (y1 >= y2) + { + x += char_width; + continue; + } + } + + // We are NOT calling PrimRectUV() here because non-inlined causes too much overhead in a debug build. + // Inlined here: + { + idx_write[0] = (ImDrawIdx)(vtx_current_idx); idx_write[1] = (ImDrawIdx)(vtx_current_idx+1); idx_write[2] = (ImDrawIdx)(vtx_current_idx+2); + idx_write[3] = (ImDrawIdx)(vtx_current_idx); idx_write[4] = (ImDrawIdx)(vtx_current_idx+2); idx_write[5] = (ImDrawIdx)(vtx_current_idx+3); + vtx_write[0].pos.x = x1; vtx_write[0].pos.y = y1; vtx_write[0].col = col; vtx_write[0].uv.x = u1; vtx_write[0].uv.y = v1; + vtx_write[1].pos.x = x2; vtx_write[1].pos.y = y1; vtx_write[1].col = col; vtx_write[1].uv.x = u2; vtx_write[1].uv.y = v1; + vtx_write[2].pos.x = x2; vtx_write[2].pos.y = y2; vtx_write[2].col = col; vtx_write[2].uv.x = u2; vtx_write[2].uv.y = v2; + vtx_write[3].pos.x = x1; vtx_write[3].pos.y = y2; vtx_write[3].col = col; vtx_write[3].uv.x = u1; vtx_write[3].uv.y = v2; + vtx_write += 4; + vtx_current_idx += 4; + idx_write += 6; + } + } + } + } + + x += char_width; + } + + // Give back unused vertices + draw_list->VtxBuffer.resize((int)(vtx_write - draw_list->VtxBuffer.Data)); + draw_list->IdxBuffer.resize((int)(idx_write - draw_list->IdxBuffer.Data)); + draw_list->CmdBuffer[draw_list->CmdBuffer.Size-1].ElemCount -= (idx_expected_size - draw_list->IdxBuffer.Size); + draw_list->_VtxWritePtr = vtx_write; + draw_list->_IdxWritePtr = idx_write; + draw_list->_VtxCurrentIdx = (unsigned int)draw_list->VtxBuffer.Size; +} + +//----------------------------------------------------------------------------- +// DEFAULT FONT DATA +//----------------------------------------------------------------------------- +// Compressed with stb_compress() then converted to a C array. +// Use the program in extra_fonts/binary_to_compressed_c.cpp to create the array from a TTF file. +// Decompression from stb.h (public domain) by Sean Barrett https://github.com/nothings/stb/blob/master/stb.h +//----------------------------------------------------------------------------- + +static unsigned int stb_decompress_length(unsigned char *input) +{ + return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11]; +} + +static unsigned char *stb__barrier, *stb__barrier2, *stb__barrier3, *stb__barrier4; +static unsigned char *stb__dout; +static void stb__match(unsigned char *data, unsigned int length) +{ + // INVERSE of memmove... write each byte before copying the next... + IM_ASSERT (stb__dout + length <= stb__barrier); + if (stb__dout + length > stb__barrier) { stb__dout += length; return; } + if (data < stb__barrier4) { stb__dout = stb__barrier+1; return; } + while (length--) *stb__dout++ = *data++; +} + +static void stb__lit(unsigned char *data, unsigned int length) +{ + IM_ASSERT (stb__dout + length <= stb__barrier); + if (stb__dout + length > stb__barrier) { stb__dout += length; return; } + if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; } + memcpy(stb__dout, data, length); + stb__dout += length; +} + +#define stb__in2(x) ((i[x] << 8) + i[(x)+1]) +#define stb__in3(x) ((i[x] << 16) + stb__in2((x)+1)) +#define stb__in4(x) ((i[x] << 24) + stb__in3((x)+1)) + +static unsigned char *stb_decompress_token(unsigned char *i) +{ + if (*i >= 0x20) { // use fewer if's for cases that expand small + if (*i >= 0x80) stb__match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2; + else if (*i >= 0x40) stb__match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3; + else /* *i >= 0x20 */ stb__lit(i+1, i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1); + } else { // more ifs for cases that expand large, since overhead is amortized + if (*i >= 0x18) stb__match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4; + else if (*i >= 0x10) stb__match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5; + else if (*i >= 0x08) stb__lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2 + (stb__in2(0) - 0x0800 + 1); + else if (*i == 0x07) stb__lit(i+3, stb__in2(1) + 1), i += 3 + (stb__in2(1) + 1); + else if (*i == 0x06) stb__match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5; + else if (*i == 0x04) stb__match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6; + } + return i; +} + +static unsigned int stb_adler32(unsigned int adler32, unsigned char *buffer, unsigned int buflen) +{ + const unsigned long ADLER_MOD = 65521; + unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16; + unsigned long blocklen, i; + + blocklen = buflen % 5552; + while (buflen) { + for (i=0; i + 7 < blocklen; i += 8) { + s1 += buffer[0], s2 += s1; + s1 += buffer[1], s2 += s1; + s1 += buffer[2], s2 += s1; + s1 += buffer[3], s2 += s1; + s1 += buffer[4], s2 += s1; + s1 += buffer[5], s2 += s1; + s1 += buffer[6], s2 += s1; + s1 += buffer[7], s2 += s1; + + buffer += 8; + } + + for (; i < blocklen; ++i) + s1 += *buffer++, s2 += s1; + + s1 %= ADLER_MOD, s2 %= ADLER_MOD; + buflen -= blocklen; + blocklen = 5552; + } + return (unsigned int)(s2 << 16) + (unsigned int)s1; +} + +static unsigned int stb_decompress(unsigned char *output, unsigned char *i, unsigned int length) +{ + unsigned int olen; + if (stb__in4(0) != 0x57bC0000) return 0; + if (stb__in4(4) != 0) return 0; // error! stream is > 4GB + olen = stb_decompress_length(i); + stb__barrier2 = i; + stb__barrier3 = i+length; + stb__barrier = output + olen; + stb__barrier4 = output; + i += 16; + + stb__dout = output; + for (;;) { + unsigned char *old_i = i; + i = stb_decompress_token(i); + if (i == old_i) { + if (*i == 0x05 && i[1] == 0xfa) { + IM_ASSERT(stb__dout == output + olen); + if (stb__dout != output + olen) return 0; + if (stb_adler32(1, output, olen) != (unsigned int) stb__in4(2)) + return 0; + return olen; + } else { + IM_ASSERT(0); /* NOTREACHED */ + return 0; + } + } + IM_ASSERT(stb__dout <= output + olen); + if (stb__dout > output + olen) + return 0; + } +} + +//----------------------------------------------------------------------------- +// ProggyClean.ttf +// Copyright (c) 2004, 2005 Tristan Grimmer +// MIT license (see License.txt in http://www.upperbounds.net/download/ProggyClean.ttf.zip) +// Download and more information at http://upperbounds.net +//----------------------------------------------------------------------------- +// File: 'ProggyClean.ttf' (41208 bytes) +// Exported using binary_to_compressed_c.cpp +//----------------------------------------------------------------------------- +static const char proggy_clean_ttf_compressed_data_base85[11980+1] = + "7])#######hV0qs'/###[),##/l:$#Q6>##5[n42>c-TH`->>#/e>11NNV=Bv(*:.F?uu#(gRU.o0XGH`$vhLG1hxt9?W`#,5LsCp#-i>.r$<$6pD>Lb';9Crc6tgXmKVeU2cD4Eo3R/" + "2*>]b(MC;$jPfY.;h^`IWM9Qo#t'X#(v#Y9w0#1D$CIf;W'#pWUPXOuxXuU(H9M(1=Ke$$'5F%)]0^#0X@U.a$FBjVQTSDgEKnIS7EM9>ZY9w0#L;>>#Mx&4Mvt//L[MkA#W@lK.N'[0#7RL_&#w+F%HtG9M#XL`N&.,GM4Pg;--VsM.M0rJfLH2eTM`*oJMHRC`N" + "kfimM2J,W-jXS:)r0wK#@Fge$U>`w'N7G#$#fB#$E^$#:9:hk+eOe--6x)F7*E%?76%^GMHePW-Z5l'&GiF#$956:rS?dA#fiK:)Yr+`�j@'DbG&#^$PG.Ll+DNa&VZ>1i%h1S9u5o@YaaW$e+bROPOpxTO7Stwi1::iB1q)C_=dV26J;2,]7op$]uQr@_V7$q^%lQwtuHY]=DX,n3L#0PHDO4f9>dC@O>HBuKPpP*E,N+b3L#lpR/MrTEH.IAQk.a>D[.e;mc." + "x]Ip.PH^'/aqUO/$1WxLoW0[iLAw=4h(9.`G" + "CRUxHPeR`5Mjol(dUWxZa(>STrPkrJiWx`5U7F#.g*jrohGg`cg:lSTvEY/EV_7H4Q9[Z%cnv;JQYZ5q.l7Zeas:HOIZOB?Ggv:[7MI2k).'2($5FNP&EQ(,)" + "U]W]+fh18.vsai00);D3@4ku5P?DP8aJt+;qUM]=+b'8@;mViBKx0DE[-auGl8:PJ&Dj+M6OC]O^((##]`0i)drT;-7X`=-H3[igUnPG-NZlo.#k@h#=Ork$m>a>$-?Tm$UV(?#P6YY#" + "'/###xe7q.73rI3*pP/$1>s9)W,JrM7SN]'/4C#v$U`0#V.[0>xQsH$fEmPMgY2u7Kh(G%siIfLSoS+MK2eTM$=5,M8p`A.;_R%#u[K#$x4AG8.kK/HSB==-'Ie/QTtG?-.*^N-4B/ZM" + "_3YlQC7(p7q)&](`6_c)$/*JL(L-^(]$wIM`dPtOdGA,U3:w2M-0+WomX2u7lqM2iEumMTcsF?-aT=Z-97UEnXglEn1K-bnEO`gu" + "Ft(c%=;Am_Qs@jLooI&NX;]0#j4#F14;gl8-GQpgwhrq8'=l_f-b49'UOqkLu7-##oDY2L(te+Mch&gLYtJ,MEtJfLh'x'M=$CS-ZZ%P]8bZ>#S?YY#%Q&q'3^Fw&?D)UDNrocM3A76/" + "/oL?#h7gl85[qW/NDOk%16ij;+:1a'iNIdb-ou8.P*w,v5#EI$TWS>Pot-R*H'-SEpA:g)f+O$%%`kA#G=8RMmG1&O`>to8bC]T&$,n.LoO>29sp3dt-52U%VM#q7'DHpg+#Z9%H[Ket`e;)f#Km8&+DC$I46>#Kr]]u-[=99tts1.qb#q72g1WJO81q+eN'03'eM>&1XxY-caEnO" + "j%2n8)),?ILR5^.Ibn<-X-Mq7[a82Lq:F&#ce+S9wsCK*x`569E8ew'He]h:sI[2LM$[guka3ZRd6:t%IG:;$%YiJ:Nq=?eAw;/:nnDq0(CYcMpG)qLN4$##&J-XTt,%OVU4)S1+R-#dg0/Nn?Ku1^0f$B*P:Rowwm-`0PKjYDDM'3]d39VZHEl4,.j']Pk-M.h^&:0FACm$maq-&sgw0t7/6(^xtk%" + "LuH88Fj-ekm>GA#_>568x6(OFRl-IZp`&b,_P'$MhLbxfc$mj`,O;&%W2m`Zh:/)Uetw:aJ%]K9h:TcF]u_-Sj9,VK3M.*'&0D[Ca]J9gp8,kAW]" + "%(?A%R$f<->Zts'^kn=-^@c4%-pY6qI%J%1IGxfLU9CP8cbPlXv);C=b),<2mOvP8up,UVf3839acAWAW-W?#ao/^#%KYo8fRULNd2.>%m]UK:n%r$'sw]J;5pAoO_#2mO3n,'=H5(et" + "Hg*`+RLgv>=4U8guD$I%D:W>-r5V*%j*W:Kvej.Lp$'?;++O'>()jLR-^u68PHm8ZFWe+ej8h:9r6L*0//c&iH&R8pRbA#Kjm%upV1g:" + "a_#Ur7FuA#(tRh#.Y5K+@?3<-8m0$PEn;J:rh6?I6uG<-`wMU'ircp0LaE_OtlMb&1#6T.#FDKu#1Lw%u%+GM+X'e?YLfjM[VO0MbuFp7;>Q&#WIo)0@F%q7c#4XAXN-U&VBpqB>0ie&jhZ[?iLR@@_AvA-iQC(=ksRZRVp7`.=+NpBC%rh&3]R:8XDmE5^V8O(x<-+k?'(^](H.aREZSi,#1:[IXaZFOm<-ui#qUq2$##Ri;u75OK#(RtaW-K-F`S+cF]uN`-KMQ%rP/Xri.LRcB##=YL3BgM/3M" + "D?@f&1'BW-)Ju#bmmWCMkk&#TR`C,5d>g)F;t,4:@_l8G/5h4vUd%&%950:VXD'QdWoY-F$BtUwmfe$YqL'8(PWX(" + "P?^@Po3$##`MSs?DWBZ/S>+4%>fX,VWv/w'KD`LP5IbH;rTV>n3cEK8U#bX]l-/V+^lj3;vlMb&[5YQ8#pekX9JP3XUC72L,,?+Ni&co7ApnO*5NK,((W-i:$,kp'UDAO(G0Sq7MVjJs" + "bIu)'Z,*[>br5fX^:FPAWr-m2KgLQ_nN6'8uTGT5g)uLv:873UpTLgH+#FgpH'_o1780Ph8KmxQJ8#H72L4@768@Tm&Q" + "h4CB/5OvmA&,Q&QbUoi$a_%3M01H)4x7I^&KQVgtFnV+;[Pc>[m4k//,]1?#`VY[Jr*3&&slRfLiVZJ:]?=K3Sw=[$=uRB?3xk48@aege0jT6'N#(q%.O=?2S]u*(m<-" + "V8J'(1)G][68hW$5'q[GC&5j`TE?m'esFGNRM)j,ffZ?-qx8;->g4t*:CIP/[Qap7/9'#(1sao7w-.qNUdkJ)tCF&#B^;xGvn2r9FEPFFFcL@.iFNkTve$m%#QvQS8U@)2Z+3K:AKM5i" + "sZ88+dKQ)W6>J%CL`.d*(B`-n8D9oK-XV1q['-5k'cAZ69e;D_?$ZPP&s^+7])$*$#@QYi9,5P r+$%CE=68>K8r0=dSC%%(@p7" + ".m7jilQ02'0-VWAgTlGW'b)Tq7VT9q^*^$$.:&N@@" + "$&)WHtPm*5_rO0&e%K&#-30j(E4#'Zb.o/(Tpm$>K'f@[PvFl,hfINTNU6u'0pao7%XUp9]5.>%h`8_=VYbxuel.NTSsJfLacFu3B'lQSu/m6-Oqem8T+oE--$0a/k]uj9EwsG>%veR*" + "hv^BFpQj:K'#SJ,sB-'#](j.Lg92rTw-*n%@/;39rrJF,l#qV%OrtBeC6/,;qB3ebNW[?,Hqj2L.1NP&GjUR=1D8QaS3Up&@*9wP?+lo7b?@%'k4`p0Z$22%K3+iCZj?XJN4Nm&+YF]u" + "@-W$U%VEQ/,,>>#)D#%8cY#YZ?=,`Wdxu/ae&#" + "w6)R89tI#6@s'(6Bf7a&?S=^ZI_kS&ai`&=tE72L_D,;^R)7[$so8lKN%5/$(vdfq7+ebA#" + "u1p]ovUKW&Y%q]'>$1@-[xfn$7ZTp7mM,G,Ko7a&Gu%G[RMxJs[0MM%wci.LFDK)(%:_i2B5CsR8&9Z&#=mPEnm0f`<&c)QL5uJ#%u%lJj+D-r;BoFDoS97h5g)E#o:&S4weDF,9^Hoe`h*L+_a*NrLW-1pG_&2UdB8" + "6e%B/:=>)N4xeW.*wft-;$'58-ESqr#U`'6AQ]m&6/`Z>#S?YY#Vc;r7U2&326d=w&H####?TZ`*4?&.MK?LP8Vxg>$[QXc%QJv92.(Db*B)gb*BM9dM*hJMAo*c&#" + "b0v=Pjer]$gG&JXDf->'StvU7505l9$AFvgYRI^&<^b68?j#q9QX4SM'RO#&sL1IM.rJfLUAj221]d##DW=m83u5;'bYx,*Sl0hL(W;;$doB&O/TQ:(Z^xBdLjLV#*8U_72Lh+2Q8Cj0i:6hp&$C/:p(HK>T8Y[gHQ4`4)'$Ab(Nof%V'8hL&#SfD07&6D@M.*J:;$-rv29'M]8qMv-tLp,'886iaC=Hb*YJoKJ,(j%K=H`K.v9HggqBIiZu'QvBT.#=)0ukruV&.)3=(^1`o*Pj4<-#MJ+gLq9-##@HuZPN0]u:h7.T..G:;$/Usj(T7`Q8tT72LnYl<-qx8;-HV7Q-&Xdx%1a,hC=0u+HlsV>nuIQL-5" + "_>@kXQtMacfD.m-VAb8;IReM3$wf0''hra*so568'Ip&vRs849'MRYSp%:t:h5qSgwpEr$B>Q,;s(C#$)`svQuF$##-D,##,g68@2[T;.XSdN9Qe)rpt._K-#5wF)sP'##p#C0c%-Gb%" + "hd+<-j'Ai*x&&HMkT]C'OSl##5RG[JXaHN;d'uA#x._U;.`PU@(Z3dt4r152@:v,'R.Sj'w#0<-;kPI)FfJ&#AYJ&#//)>-k=m=*XnK$>=)72L]0I%>.G690a:$##<,);?;72#?x9+d;" + "^V'9;jY@;)br#q^YQpx:X#Te$Z^'=-=bGhLf:D6&bNwZ9-ZD#n^9HhLMr5G;']d&6'wYmTFmLq9wI>P(9mI[>kC-ekLC/R&CH+s'B;K-M6$EB%is00:" + "+A4[7xks.LrNk0&E)wILYF@2L'0Nb$+pv<(2.768/FrY&h$^3i&@+G%JT'<-,v`3;_)I9M^AE]CN?Cl2AZg+%4iTpT3$U4O]GKx'm9)b@p7YsvK3w^YR-" + "CdQ*:Ir<($u&)#(&?L9Rg3H)4fiEp^iI9O8KnTj,]H?D*r7'M;PwZ9K0E^k&-cpI;.p/6_vwoFMV<->#%Xi.LxVnrU(4&8/P+:hLSKj$#U%]49t'I:rgMi'FL@a:0Y-uA[39',(vbma*" + "hU%<-SRF`Tt:542R_VV$p@[p8DV[A,?1839FWdFTi1O*H&#(AL8[_P%.M>v^-))qOT*F5Cq0`Ye%+$B6i:7@0IXSsDiWP,##P`%/L-" + "S(qw%sf/@%#B6;/U7K]uZbi^Oc^2n%t<)'mEVE''n`WnJra$^TKvX5B>;_aSEK',(hwa0:i4G?.Bci.(X[?b*($,=-n<.Q%`(X=?+@Am*Js0&=3bh8K]mL69=Lb,OcZV/);TTm8VI;?%OtJ<(b4mq7M6:u?KRdFl*:xP?Yb.5)%w_I?7uk5JC+FS(m#i'k.'a0i)9<7b'fs'59hq$*5Uhv##pi^8+hIEBF`nvo`;'l0.^S1<-wUK2/Coh58KKhLj" + "M=SO*rfO`+qC`W-On.=AJ56>>i2@2LH6A:&5q`?9I3@@'04&p2/LVa*T-4<-i3;M9UvZd+N7>b*eIwg:CC)c<>nO&#$(>.Z-I&J(Q0Hd5Q%7Co-b`-cP)hI;*_F]u`Rb[.j8_Q/<&>uu+VsH$sM9TA%?)(vmJ80),P7E>)tjD%2L=-t#fK[%`v=Q8WlA2);Sa" + ">gXm8YB`1d@K#n]76-a$U,mF%Ul:#/'xoFM9QX-$.QN'>" + "[%$Z$uF6pA6Ki2O5:8w*vP1<-1`[G,)-m#>0`P&#eb#.3i)rtB61(o'$?X3B2Qft^ae_5tKL9MUe9b*sLEQ95C&`=G?@Mj=wh*'3E>=-<)Gt*Iw)'QG:`@I" + "wOf7&]1i'S01B+Ev/Nac#9S;=;YQpg_6U`*kVY39xK,[/6Aj7:'1Bm-_1EYfa1+o&o4hp7KN_Q(OlIo@S%;jVdn0'1h19w,WQhLI)3S#f$2(eb,jr*b;3Vw]*7NH%$c4Vs,eD9>XW8?N]o+(*pgC%/72LV-uW%iewS8W6m2rtCpo'RS1R84=@paTKt)>=%&1[)*vp'u+x,VrwN;&]kuO9JDbg=pO$J*.jVe;u'm0dr9l,<*wMK*Oe=g8lV_KEBFkO'oU]^=[-792#ok,)" + "i]lR8qQ2oA8wcRCZ^7w/Njh;?.stX?Q1>S1q4Bn$)K1<-rGdO'$Wr.Lc.CG)$/*JL4tNR/,SVO3,aUw'DJN:)Ss;wGn9A32ijw%FL+Z0Fn.U9;reSq)bmI32U==5ALuG&#Vf1398/pVo" + "1*c-(aY168o<`JsSbk-,1N;$>0:OUas(3:8Z972LSfF8eb=c-;>SPw7.6hn3m`9^Xkn(r.qS[0;T%&Qc=+STRxX'q1BNk3&*eu2;&8q$&x>Q#Q7^Tf+6<(d%ZVmj2bDi%.3L2n+4W'$P" + "iDDG)g,r%+?,$@?uou5tSe2aN_AQU*'IAO" + "URQ##V^Fv-XFbGM7Fl(N<3DhLGF%q.1rC$#:T__&Pi68%0xi_&[qFJ(77j_&JWoF.V735&T,[R*:xFR*K5>>#`bW-?4Ne_&6Ne_&6Ne_&n`kr-#GJcM6X;uM6X;uM(.a..^2TkL%oR(#" + ";u.T%fAr%4tJ8&><1=GHZ_+m9/#H1F^R#SC#*N=BA9(D?v[UiFY>>^8p,KKF.W]L29uLkLlu/+4T" + "w$)F./^n3+rlo+DB;5sIYGNk+i1t-69Jg--0pao7Sm#K)pdHW&;LuDNH@H>#/X-TI(;P>#,Gc>#0Su>#4`1?#8lC?#xL$#B.`$#F:r$#JF.%#NR@%#R_R%#Vke%#Zww%#_-4^Rh%Sflr-k'MS.o?.5/sWel/wpEM0%3'/1)K^f1-d>G21&v(35>V`39V7A4=onx4" + "A1OY5EI0;6Ibgr6M$HS7Q<)58C5w,;WoA*#[%T*#`1g*#d=#+#hI5+#lUG+#pbY+#tnl+#x$),#&1;,#*=M,#.I`,#2Ur,#6b.-#;w[H#iQtA#m^0B#qjBB#uvTB##-hB#'9$C#+E6C#" + "/QHC#3^ZC#7jmC#;v)D#?,)4kMYD4lVu`4m`:&5niUA5@(A5BA1]PBB:xlBCC=2CDLXMCEUtiCf&0g2'tN?PGT4CPGT4CPGT4CPGT4CPGT4CPGT4CPGT4CP" + "GT4CPGT4CPGT4CPGT4CPGT4CPGT4CP-qekC`.9kEg^+F$kwViFJTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5o,^<-28ZI'O?;xp" + "O?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xp;7q-#lLYI:xvD=#"; + +static const char* GetDefaultCompressedFontDataTTFBase85() +{ + return proggy_clean_ttf_compressed_data_base85; +} diff --git a/modules/onscreengui/ext/imgui/imgui_internal.h b/modules/onscreengui/ext/imgui/imgui_internal.h new file mode 100644 index 0000000000..c641c45ea2 --- /dev/null +++ b/modules/onscreengui/ext/imgui/imgui_internal.h @@ -0,0 +1,754 @@ +// dear imgui, v1.49 +// (internals) + +// You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! +// Implement maths operators for ImVec2 (disabled by default to not collide with using IM_VEC2_CLASS_EXTRA along with your own math types+operators) +// #define IMGUI_DEFINE_MATH_OPERATORS + +#pragma once + +#ifndef IMGUI_VERSION +#error Must include imgui.h before imgui_internal.h +#endif + +#include // FILE* +#include // sqrtf() + +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable: 4251) // class 'xxx' needs to have dll-interface to be used by clients of struct 'xxx' // when IMGUI_API is set to__declspec(dllexport) +#endif + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-function" // for stb_textedit.h +#pragma clang diagnostic ignored "-Wmissing-prototypes" // for stb_textedit.h +#pragma clang diagnostic ignored "-Wold-style-cast" +#endif + +//----------------------------------------------------------------------------- +// Forward Declarations +//----------------------------------------------------------------------------- + +struct ImRect; +struct ImGuiColMod; +struct ImGuiStyleMod; +struct ImGuiGroupData; +struct ImGuiSimpleColumns; +struct ImGuiDrawContext; +struct ImGuiTextEditState; +struct ImGuiIniData; +struct ImGuiMouseCursorData; +struct ImGuiPopupRef; +struct ImGuiWindow; + +typedef int ImGuiLayoutType; // enum ImGuiLayoutType_ +typedef int ImGuiButtonFlags; // enum ImGuiButtonFlags_ +typedef int ImGuiTreeNodeFlags; // enum ImGuiTreeNodeFlags_ +typedef int ImGuiSliderFlags; // enum ImGuiSliderFlags_ + +//------------------------------------------------------------------------- +// STB libraries +//------------------------------------------------------------------------- + +namespace ImGuiStb +{ + +#undef STB_TEXTEDIT_STRING +#undef STB_TEXTEDIT_CHARTYPE +#define STB_TEXTEDIT_STRING ImGuiTextEditState +#define STB_TEXTEDIT_CHARTYPE ImWchar +#define STB_TEXTEDIT_GETWIDTH_NEWLINE -1.0f +#include "stb_textedit.h" + +} // namespace ImGuiStb + +//----------------------------------------------------------------------------- +// Context +//----------------------------------------------------------------------------- + +extern IMGUI_API ImGuiContext* GImGui; // current implicit ImGui context pointer + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) +#define IM_PI 3.14159265358979323846f + +// Helpers: UTF-8 <> wchar +IMGUI_API int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count +IMGUI_API int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end); // return input UTF-8 bytes count +IMGUI_API int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_remaining = NULL); // return input UTF-8 bytes count +IMGUI_API int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end); // return number of UTF-8 code-points (NOT bytes count) +IMGUI_API int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end); // return number of bytes to express string as UTF-8 code-points + +// Helpers: Misc +IMGUI_API ImU32 ImHash(const void* data, int data_size, ImU32 seed = 0); // Pass data_size==0 for zero-terminated strings +IMGUI_API void* ImLoadFileToMemory(const char* filename, const char* file_open_mode, int* out_file_size = NULL, int padding_bytes = 0); +IMGUI_API bool ImIsPointInTriangle(const ImVec2& p, const ImVec2& a, const ImVec2& b, const ImVec2& c); +static inline bool ImCharIsSpace(int c) { return c == ' ' || c == '\t' || c == 0x3000; } +static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } + +// Helpers: String +IMGUI_API int ImStricmp(const char* str1, const char* str2); +IMGUI_API int ImStrnicmp(const char* str1, const char* str2, int count); +IMGUI_API char* ImStrdup(const char* str); +IMGUI_API int ImStrlenW(const ImWchar* str); +IMGUI_API const ImWchar*ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin); // Find beginning-of-line +IMGUI_API const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end); +IMGUI_API int ImFormatString(char* buf, int buf_size, const char* fmt, ...) IM_PRINTFARGS(3); +IMGUI_API int ImFormatStringV(char* buf, int buf_size, const char* fmt, va_list args); + +// Helpers: Math +// We are keeping those not leaking to the user by default, in the case the user has implicit cast operators between ImVec2 and its own types (when IM_VEC2_CLASS_EXTRA is defined) +#ifdef IMGUI_DEFINE_MATH_OPERATORS +static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x*rhs, lhs.y*rhs); } +static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x/rhs, lhs.y/rhs); } +static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x+rhs.x, lhs.y+rhs.y); } +static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x-rhs.x, lhs.y-rhs.y); } +static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x*rhs.x, lhs.y*rhs.y); } +static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x/rhs.x, lhs.y/rhs.y); } +static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } +static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } +static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } +static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } +static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x-rhs.x, lhs.y-rhs.y, lhs.z-rhs.z, lhs.w-rhs.w); } +#endif + +static inline int ImMin(int lhs, int rhs) { return lhs < rhs ? lhs : rhs; } +static inline int ImMax(int lhs, int rhs) { return lhs >= rhs ? lhs : rhs; } +static inline float ImMin(float lhs, float rhs) { return lhs < rhs ? lhs : rhs; } +static inline float ImMax(float lhs, float rhs) { return lhs >= rhs ? lhs : rhs; } +static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMin(lhs.x,rhs.x), ImMin(lhs.y,rhs.y)); } +static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMax(lhs.x,rhs.x), ImMax(lhs.y,rhs.y)); } +static inline int ImClamp(int v, int mn, int mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } +static inline float ImClamp(float v, float mn, float mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } +static inline ImVec2 ImClamp(const ImVec2& f, const ImVec2& mn, ImVec2 mx) { return ImVec2(ImClamp(f.x,mn.x,mx.x), ImClamp(f.y,mn.y,mx.y)); } +static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; } +static inline float ImLerp(float a, float b, float t) { return a + (b - a) * t; } +static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t) { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); } +static inline float ImLengthSqr(const ImVec2& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y; } +static inline float ImLengthSqr(const ImVec4& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y + lhs.z*lhs.z + lhs.w*lhs.w; } +static inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = lhs.x*lhs.x + lhs.y*lhs.y; if (d > 0.0f) return 1.0f / sqrtf(d); return fail_value; } +static inline float ImFloor(float f) { return (float)(int)f; } +static inline ImVec2 ImFloor(ImVec2 v) { return ImVec2((float)(int)v.x, (float)(int)v.y); } + +// We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax. +// Defining a custom placement new() with a dummy parameter allows us to bypass including which on some platforms complains when user has disabled exceptions. +#ifdef IMGUI_DEFINE_PLACEMENT_NEW +struct ImPlacementNewDummy {}; +inline void* operator new(size_t, ImPlacementNewDummy, void* ptr) { return ptr; } +inline void operator delete(void*, ImPlacementNewDummy, void*) {} +#define IM_PLACEMENT_NEW(_PTR) new(ImPlacementNewDummy(), _PTR) +#endif + +//----------------------------------------------------------------------------- +// Types +//----------------------------------------------------------------------------- + +enum ImGuiButtonFlags_ +{ + ImGuiButtonFlags_Repeat = 1 << 0, // hold to repeat + ImGuiButtonFlags_PressedOnClickRelease = 1 << 1, // (default) return pressed on click+release on same item (default if no PressedOn** flag is set) + ImGuiButtonFlags_PressedOnClick = 1 << 2, // return pressed on click (default requires click+release) + ImGuiButtonFlags_PressedOnRelease = 1 << 3, // return pressed on release (default requires click+release) + ImGuiButtonFlags_PressedOnDoubleClick = 1 << 4, // return pressed on double-click (default requires click+release) + ImGuiButtonFlags_FlattenChilds = 1 << 5, // allow interaction even if a child window is overlapping + ImGuiButtonFlags_DontClosePopups = 1 << 6, // disable automatically closing parent popup on press + ImGuiButtonFlags_Disabled = 1 << 7, // disable interaction + ImGuiButtonFlags_AlignTextBaseLine = 1 << 8, // vertically align button to match text baseline - ButtonEx() only + ImGuiButtonFlags_NoKeyModifiers = 1 << 9, // disable interaction if a key modifier is held + ImGuiButtonFlags_AllowOverlapMode = 1 << 10 // require previous frame HoveredId to either match id or be null before being usable +}; + +enum ImGuiSliderFlags_ +{ + ImGuiSliderFlags_Vertical = 1 << 0 +}; + +enum ImGuiSelectableFlagsPrivate_ +{ + // NB: need to be in sync with last value of ImGuiSelectableFlags_ + ImGuiSelectableFlags_Menu = 1 << 3, + ImGuiSelectableFlags_MenuItem = 1 << 4, + ImGuiSelectableFlags_Disabled = 1 << 5, + ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 6 +}; + +// FIXME: this is in development, not exposed/functional as a generic feature yet. +enum ImGuiLayoutType_ +{ + ImGuiLayoutType_Vertical, + ImGuiLayoutType_Horizontal +}; + +enum ImGuiPlotType +{ + ImGuiPlotType_Lines, + ImGuiPlotType_Histogram +}; + +enum ImGuiDataType +{ + ImGuiDataType_Int, + ImGuiDataType_Float +}; + +// 2D axis aligned bounding-box +// NB: we can't rely on ImVec2 math operators being available here +struct IMGUI_API ImRect +{ + ImVec2 Min; // Upper-left + ImVec2 Max; // Lower-right + + ImRect() : Min(FLT_MAX,FLT_MAX), Max(-FLT_MAX,-FLT_MAX) {} + ImRect(const ImVec2& min, const ImVec2& max) : Min(min), Max(max) {} + ImRect(const ImVec4& v) : Min(v.x, v.y), Max(v.z, v.w) {} + ImRect(float x1, float y1, float x2, float y2) : Min(x1, y1), Max(x2, y2) {} + + ImVec2 GetCenter() const { return ImVec2((Min.x+Max.x)*0.5f, (Min.y+Max.y)*0.5f); } + ImVec2 GetSize() const { return ImVec2(Max.x-Min.x, Max.y-Min.y); } + float GetWidth() const { return Max.x-Min.x; } + float GetHeight() const { return Max.y-Min.y; } + ImVec2 GetTL() const { return Min; } // Top-left + ImVec2 GetTR() const { return ImVec2(Max.x, Min.y); } // Top-right + ImVec2 GetBL() const { return ImVec2(Min.x, Max.y); } // Bottom-left + ImVec2 GetBR() const { return Max; } // Bottom-right + bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; } + bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x < Max.x && r.Max.y < Max.y; } + bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; } + void Add(const ImVec2& rhs) { if (Min.x > rhs.x) Min.x = rhs.x; if (Min.y > rhs.y) Min.y = rhs.y; if (Max.x < rhs.x) Max.x = rhs.x; if (Max.y < rhs.y) Max.y = rhs.y; } + void Add(const ImRect& rhs) { if (Min.x > rhs.Min.x) Min.x = rhs.Min.x; if (Min.y > rhs.Min.y) Min.y = rhs.Min.y; if (Max.x < rhs.Max.x) Max.x = rhs.Max.x; if (Max.y < rhs.Max.y) Max.y = rhs.Max.y; } + void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; } + void Expand(const ImVec2& amount) { Min.x -= amount.x; Min.y -= amount.y; Max.x += amount.x; Max.y += amount.y; } + void Reduce(const ImVec2& amount) { Min.x += amount.x; Min.y += amount.y; Max.x -= amount.x; Max.y -= amount.y; } + void Clip(const ImRect& clip) { if (Min.x < clip.Min.x) Min.x = clip.Min.x; if (Min.y < clip.Min.y) Min.y = clip.Min.y; if (Max.x > clip.Max.x) Max.x = clip.Max.x; if (Max.y > clip.Max.y) Max.y = clip.Max.y; } + void Floor() { Min.x = (float)(int)Min.x; Min.y = (float)(int)Min.y; Max.x = (float)(int)Max.x; Max.y = (float)(int)Max.y; } + ImVec2 GetClosestPoint(ImVec2 p, bool on_edge) const + { + if (!on_edge && Contains(p)) + return p; + if (p.x > Max.x) p.x = Max.x; + else if (p.x < Min.x) p.x = Min.x; + if (p.y > Max.y) p.y = Max.y; + else if (p.y < Min.y) p.y = Min.y; + return p; + } +}; + +// Stacked color modifier, backup of modified data so we can restore it +struct ImGuiColMod +{ + ImGuiCol Col; + ImVec4 PreviousValue; +}; + +// Stacked style modifier, backup of modified data so we can restore it +struct ImGuiStyleMod +{ + ImGuiStyleVar Var; + ImVec2 PreviousValue; +}; + +// Stacked data for BeginGroup()/EndGroup() +struct ImGuiGroupData +{ + ImVec2 BackupCursorPos; + ImVec2 BackupCursorMaxPos; + float BackupIndentX; + float BackupCurrentLineHeight; + float BackupCurrentLineTextBaseOffset; + float BackupLogLinePosY; + bool AdvanceCursor; +}; + +// Per column data for Columns() +struct ImGuiColumnData +{ + float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right) + //float IndentX; +}; + +// Simple column measurement currently used for MenuItem() only. This is very short-sighted/throw-away code and NOT a generic helper. +struct IMGUI_API ImGuiSimpleColumns +{ + int Count; + float Spacing; + float Width, NextWidth; + float Pos[8], NextWidths[8]; + + ImGuiSimpleColumns(); + void Update(int count, float spacing, bool clear); + float DeclColumns(float w0, float w1, float w2); + float CalcExtraSpace(float avail_w); +}; + +// Internal state of the currently focused/edited text input box +struct IMGUI_API ImGuiTextEditState +{ + ImGuiID Id; // widget id owning the text state + ImVector Text; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer. + ImVector InitialText; // backup of end-user buffer at the time of focus (in UTF-8, unaltered) + ImVector TempTextBuffer; + int CurLenA, CurLenW; // we need to maintain our buffer length in both UTF-8 and wchar format. + int BufSizeA; // end-user buffer size + float ScrollX; + ImGuiStb::STB_TexteditState StbState; + float CursorAnim; + bool CursorFollow; + bool SelectedAllMouseLock; + + ImGuiTextEditState() { memset(this, 0, sizeof(*this)); } + void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking + void CursorClamp() { StbState.cursor = ImMin(StbState.cursor, CurLenW); StbState.select_start = ImMin(StbState.select_start, CurLenW); StbState.select_end = ImMin(StbState.select_end, CurLenW); } + bool HasSelection() const { return StbState.select_start != StbState.select_end; } + void ClearSelection() { StbState.select_start = StbState.select_end = StbState.cursor; } + void SelectAll() { StbState.select_start = 0; StbState.select_end = CurLenW; StbState.cursor = StbState.select_end; StbState.has_preferred_x = false; } + void OnKeyPressed(int key); +}; + +// Data saved in imgui.ini file +struct ImGuiIniData +{ + char* Name; + ImGuiID ID; + ImVec2 Pos; + ImVec2 Size; + bool Collapsed; +}; + +// Mouse cursor data (used when io.MouseDrawCursor is set) +struct ImGuiMouseCursorData +{ + ImGuiMouseCursor Type; + ImVec2 HotOffset; + ImVec2 Size; + ImVec2 TexUvMin[2]; + ImVec2 TexUvMax[2]; +}; + +// Storage for current popup stack +struct ImGuiPopupRef +{ + ImGuiID PopupID; // Set on OpenPopup() + ImGuiWindow* Window; // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup() + ImGuiWindow* ParentWindow; // Set on OpenPopup() + ImGuiID ParentMenuSet; // Set on OpenPopup() + ImVec2 MousePosOnOpen; // Copy of mouse position at the time of opening popup + + ImGuiPopupRef(ImGuiID id, ImGuiWindow* parent_window, ImGuiID parent_menu_set, const ImVec2& mouse_pos) { PopupID = id; Window = NULL; ParentWindow = parent_window; ParentMenuSet = parent_menu_set; MousePosOnOpen = mouse_pos; } +}; + +// Main state for ImGui +struct ImGuiContext +{ + bool Initialized; + ImGuiIO IO; + ImGuiStyle Style; + ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back() + float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize() + float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Size of characters. + ImVec2 FontTexUvWhitePixel; // (Shortcut) == Font->TexUvWhitePixel + + float Time; + int FrameCount; + int FrameCountEnded; + int FrameCountRendered; + ImVector Windows; + ImVector WindowsSortBuffer; + ImGuiWindow* CurrentWindow; // Being drawn into + ImVector CurrentWindowStack; + ImGuiWindow* FocusedWindow; // Will catch keyboard inputs + ImGuiWindow* HoveredWindow; // Will catch mouse inputs + ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only) + ImGuiID HoveredId; // Hovered widget + bool HoveredIdAllowOverlap; + ImGuiID HoveredIdPreviousFrame; + ImGuiID ActiveId; // Active widget + ImGuiID ActiveIdPreviousFrame; + bool ActiveIdIsAlive; + bool ActiveIdIsJustActivated; // Set at the time of activation for one frame + bool ActiveIdAllowOverlap; // Set only by active widget + ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior) + ImGuiWindow* ActiveIdWindow; + ImGuiWindow* MovedWindow; // Track the child window we clicked on to move a window. + ImGuiID MovedWindowMoveId; // == MovedWindow->RootWindow->MoveId + ImVector Settings; // .ini Settings + float SettingsDirtyTimer; // Save .ini Settings on disk when time reaches zero + ImVector ColorModifiers; // Stack for PushStyleColor()/PopStyleColor() + ImVector StyleModifiers; // Stack for PushStyleVar()/PopStyleVar() + ImVector FontStack; // Stack for PushFont()/PopFont() + ImVector OpenPopupStack; // Which popups are open (persistent) + ImVector CurrentPopupStack; // Which level of BeginPopup() we are in (reset every frame) + + // Storage for SetNexWindow** and SetNextTreeNode*** functions + ImVec2 SetNextWindowPosVal; + ImVec2 SetNextWindowSizeVal; + ImVec2 SetNextWindowContentSizeVal; + bool SetNextWindowCollapsedVal; + ImGuiSetCond SetNextWindowPosCond; + ImGuiSetCond SetNextWindowSizeCond; + ImGuiSetCond SetNextWindowContentSizeCond; + ImGuiSetCond SetNextWindowCollapsedCond; + ImRect SetNextWindowSizeConstraintRect; // Valid if 'SetNextWindowSizeConstraint' is true + ImGuiSizeConstraintCallback SetNextWindowSizeConstraintCallback; + void* SetNextWindowSizeConstraintCallbackUserData; + bool SetNextWindowSizeConstraint; + bool SetNextWindowFocus; + bool SetNextTreeNodeOpenVal; + ImGuiSetCond SetNextTreeNodeOpenCond; + + // Render + ImDrawData RenderDrawData; // Main ImDrawData instance to pass render information to the user + ImVector RenderDrawLists[3]; + float ModalWindowDarkeningRatio; + ImDrawList OverlayDrawList; // Optional software render of mouse cursors, if io.MouseDrawCursor is set + a few debug overlays + ImGuiMouseCursor MouseCursor; + ImGuiMouseCursorData MouseCursorData[ImGuiMouseCursor_Count_]; + + // Widget state + ImGuiTextEditState InputTextState; + ImFont InputTextPasswordFont; + ImGuiID ScalarAsInputTextId; // Temporary text input when CTRL+clicking on a slider, etc. + ImGuiStorage ColorEditModeStorage; // Store user selection of color edit mode + float DragCurrentValue; // Currently dragged value, always float, not rounded by end-user precision settings + ImVec2 DragLastMouseDelta; + float DragSpeedDefaultRatio; // If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio + float DragSpeedScaleSlow; + float DragSpeedScaleFast; + ImVec2 ScrollbarClickDeltaToGrabCenter; // Distance between mouse and center of grab box, normalized in parent space. Use storage? + char Tooltip[1024]; + char* PrivateClipboard; // If no custom clipboard handler is defined + ImVec2 OsImePosRequest, OsImePosSet; // Cursor position request & last passed to the OS Input Method Editor + + // Logging + bool LogEnabled; + FILE* LogFile; // If != NULL log to stdout/ file + ImGuiTextBuffer* LogClipboard; // Else log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators. + int LogStartDepth; + int LogAutoExpandMaxDepth; + + // Misc + float FramerateSecPerFrame[120]; // calculate estimate of framerate for user + int FramerateSecPerFrameIdx; + float FramerateSecPerFrameAccum; + int CaptureMouseNextFrame; // explicit capture via CaptureInputs() sets those flags + int CaptureKeyboardNextFrame; + char TempBuffer[1024*3+1]; // temporary text buffer + + ImGuiContext() + { + Initialized = false; + Font = NULL; + FontSize = FontBaseSize = 0.0f; + FontTexUvWhitePixel = ImVec2(0.0f, 0.0f); + + Time = 0.0f; + FrameCount = 0; + FrameCountEnded = FrameCountRendered = -1; + CurrentWindow = NULL; + FocusedWindow = NULL; + HoveredWindow = NULL; + HoveredRootWindow = NULL; + HoveredId = 0; + HoveredIdAllowOverlap = false; + HoveredIdPreviousFrame = 0; + ActiveId = 0; + ActiveIdPreviousFrame = 0; + ActiveIdIsAlive = false; + ActiveIdIsJustActivated = false; + ActiveIdAllowOverlap = false; + ActiveIdClickOffset = ImVec2(-1,-1); + ActiveIdWindow = NULL; + MovedWindow = NULL; + MovedWindowMoveId = 0; + SettingsDirtyTimer = 0.0f; + + SetNextWindowPosVal = ImVec2(0.0f, 0.0f); + SetNextWindowSizeVal = ImVec2(0.0f, 0.0f); + SetNextWindowCollapsedVal = false; + SetNextWindowPosCond = 0; + SetNextWindowSizeCond = 0; + SetNextWindowContentSizeCond = 0; + SetNextWindowCollapsedCond = 0; + SetNextWindowFocus = false; + SetNextWindowSizeConstraintCallback = NULL; + SetNextWindowSizeConstraintCallbackUserData = NULL; + SetNextTreeNodeOpenVal = false; + SetNextTreeNodeOpenCond = 0; + + ScalarAsInputTextId = 0; + DragCurrentValue = 0.0f; + DragLastMouseDelta = ImVec2(0.0f, 0.0f); + DragSpeedDefaultRatio = 0.01f; + DragSpeedScaleSlow = 0.01f; + DragSpeedScaleFast = 10.0f; + ScrollbarClickDeltaToGrabCenter = ImVec2(0.0f, 0.0f); + memset(Tooltip, 0, sizeof(Tooltip)); + PrivateClipboard = NULL; + OsImePosRequest = OsImePosSet = ImVec2(-1.0f, -1.0f); + + ModalWindowDarkeningRatio = 0.0f; + OverlayDrawList._OwnerName = "##Overlay"; // Give it a name for debugging + MouseCursor = ImGuiMouseCursor_Arrow; + memset(MouseCursorData, 0, sizeof(MouseCursorData)); + + LogEnabled = false; + LogFile = NULL; + LogClipboard = NULL; + LogStartDepth = 0; + LogAutoExpandMaxDepth = 2; + + memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame)); + FramerateSecPerFrameIdx = 0; + FramerateSecPerFrameAccum = 0.0f; + CaptureMouseNextFrame = CaptureKeyboardNextFrame = -1; + memset(TempBuffer, 0, sizeof(TempBuffer)); + } +}; + +// Transient per-window data, reset at the beginning of the frame +// FIXME: That's theory, in practice the delimitation between ImGuiWindow and ImGuiDrawContext is quite tenuous and could be reconsidered. +struct IMGUI_API ImGuiDrawContext +{ + ImVec2 CursorPos; + ImVec2 CursorPosPrevLine; + ImVec2 CursorStartPos; + ImVec2 CursorMaxPos; // Implicitly calculate the size of our contents, always extending. Saved into window->SizeContents at the end of the frame + float CurrentLineHeight; + float CurrentLineTextBaseOffset; + float PrevLineHeight; + float PrevLineTextBaseOffset; + float LogLinePosY; + int TreeDepth; + ImGuiID LastItemID; + ImRect LastItemRect; + bool LastItemHoveredAndUsable; // Item rectangle is hovered, and its window is currently interactable with (not blocked by a popup preventing access to the window) + bool LastItemHoveredRect; // Item rectangle is hovered, but its window may or not be currently interactable with (might be blocked by a popup preventing access to the window) + bool MenuBarAppending; + float MenuBarOffsetX; + ImVector ChildWindows; + ImGuiStorage* StateStorage; + ImGuiLayoutType LayoutType; + + // We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings. + float ItemWidth; // == ItemWidthStack.back(). 0.0: default, >0.0: width in pixels, <0.0: align xx pixels to the right of window + float TextWrapPos; // == TextWrapPosStack.back() [empty == -1.0f] + bool AllowKeyboardFocus; // == AllowKeyboardFocusStack.back() [empty == true] + bool ButtonRepeat; // == ButtonRepeatStack.back() [empty == false] + ImVector ItemWidthStack; + ImVector TextWrapPosStack; + ImVector AllowKeyboardFocusStack; + ImVector ButtonRepeatStack; + ImVectorGroupStack; + ImGuiColorEditMode ColorEditMode; + int StackSizesBackup[6]; // Store size of various stacks for asserting + + float IndentX; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.) + float ColumnsOffsetX; // Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree->Column->Tree. Need revamp columns API. + int ColumnsCurrent; + int ColumnsCount; + float ColumnsMinX; + float ColumnsMaxX; + float ColumnsStartPosY; + float ColumnsCellMinY; + float ColumnsCellMaxY; + bool ColumnsShowBorders; + ImGuiID ColumnsSetID; + ImVector ColumnsData; + + ImGuiDrawContext() + { + CursorPos = CursorPosPrevLine = CursorStartPos = CursorMaxPos = ImVec2(0.0f, 0.0f); + CurrentLineHeight = PrevLineHeight = 0.0f; + CurrentLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f; + LogLinePosY = -1.0f; + TreeDepth = 0; + LastItemID = 0; + LastItemRect = ImRect(0.0f,0.0f,0.0f,0.0f); + LastItemHoveredAndUsable = LastItemHoveredRect = false; + MenuBarAppending = false; + MenuBarOffsetX = 0.0f; + StateStorage = NULL; + LayoutType = ImGuiLayoutType_Vertical; + ItemWidth = 0.0f; + ButtonRepeat = false; + AllowKeyboardFocus = true; + TextWrapPos = -1.0f; + ColorEditMode = ImGuiColorEditMode_RGB; + memset(StackSizesBackup, 0, sizeof(StackSizesBackup)); + + IndentX = 0.0f; + ColumnsOffsetX = 0.0f; + ColumnsCurrent = 0; + ColumnsCount = 1; + ColumnsMinX = ColumnsMaxX = 0.0f; + ColumnsStartPosY = 0.0f; + ColumnsCellMinY = ColumnsCellMaxY = 0.0f; + ColumnsShowBorders = true; + ColumnsSetID = 0; + } +}; + +// Windows data +struct IMGUI_API ImGuiWindow +{ + char* Name; + ImGuiID ID; // == ImHash(Name) + ImGuiWindowFlags Flags; // See enum ImGuiWindowFlags_ + int IndexWithinParent; // Order within immediate parent window, if we are a child window. Otherwise 0. + ImVec2 PosFloat; + ImVec2 Pos; // Position rounded-up to nearest pixel + ImVec2 Size; // Current size (==SizeFull or collapsed title bar size) + ImVec2 SizeFull; // Size when non collapsed + ImVec2 SizeContents; // Size of contents (== extents reach of the drawing cursor) from previous frame + ImVec2 SizeContentsExplicit; // Size of contents explicitly set by the user via SetNextWindowContentSize() + ImRect ContentsRegionRect; // Maximum visible content position in window coordinates. ~~ (SizeContentsExplicit ? SizeContentsExplicit : Size - ScrollbarSizes) - CursorStartPos, per axis + ImVec2 WindowPadding; // Window padding at the time of begin. We need to lock it, in particular manipulation of the ShowBorder would have an effect + ImGuiID MoveID; // == window->GetID("#MOVE") + ImVec2 Scroll; + ImVec2 ScrollTarget; // target scroll position. stored as cursor position with scrolling canceled out, so the highest point is always 0.0f. (FLT_MAX for no change) + ImVec2 ScrollTargetCenterRatio; // 0.0f = scroll so that target position is at top, 0.5f = scroll so that target position is centered + bool ScrollbarX, ScrollbarY; + ImVec2 ScrollbarSizes; + float BorderSize; + bool Active; // Set to true on Begin() + bool WasActive; + bool Accessed; // Set to true when any widget access the current window + bool Collapsed; // Set when collapsing window to become only title-bar + bool SkipItems; // == Visible && !Collapsed + int BeginCount; // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs) + ImGuiID PopupID; // ID in the popup stack when this window is used as a popup/menu (because we use generic Name/ID for recycling) + int AutoFitFramesX, AutoFitFramesY; + bool AutoFitOnlyGrows; + int AutoPosLastDirection; + int HiddenFrames; + int SetWindowPosAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowPos() call will succeed with this particular flag. + int SetWindowSizeAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowSize() call will succeed with this particular flag. + int SetWindowCollapsedAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowCollapsed() call will succeed with this particular flag. + bool SetWindowPosCenterWanted; + + ImGuiDrawContext DC; // Temporary per-window data, reset at the beginning of the frame + ImVector IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack + ImRect ClipRect; // = DrawList->clip_rect_stack.back(). Scissoring / clipping rectangle. x1, y1, x2, y2. + ImRect WindowRectClipped; // = WindowRect just after setup in Begin(). == window->Rect() for root window. + int LastFrameActive; + float ItemWidthDefault; + ImGuiSimpleColumns MenuColumns; // Simplified columns storage for menu items + ImGuiStorage StateStorage; + float FontWindowScale; // Scale multiplier per-window + ImDrawList* DrawList; + ImGuiWindow* RootWindow; // If we are a child window, this is pointing to the first non-child parent window. Else point to ourself. + ImGuiWindow* RootNonPopupWindow; // If we are a child window, this is pointing to the first non-child non-popup parent window. Else point to ourself. + ImGuiWindow* ParentWindow; // If we are a child window, this is pointing to our parent window. Else point to NULL. + + // Focus + int FocusIdxAllCounter; // Start at -1 and increase as assigned via FocusItemRegister() + int FocusIdxTabCounter; // (same, but only count widgets which you can Tab through) + int FocusIdxAllRequestCurrent; // Item being requested for focus + int FocusIdxTabRequestCurrent; // Tab-able item being requested for focus + int FocusIdxAllRequestNext; // Item being requested for focus, for next update (relies on layout to be stable between the frame pressing TAB and the next frame) + int FocusIdxTabRequestNext; // " + +public: + ImGuiWindow(const char* name); + ~ImGuiWindow(); + + ImGuiID GetID(const char* str, const char* str_end = NULL); + ImGuiID GetID(const void* ptr); + + ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x+Size.x, Pos.y+Size.y); } + float CalcFontSize() const { return GImGui->FontBaseSize * FontWindowScale; } + float TitleBarHeight() const { return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : CalcFontSize() + GImGui->Style.FramePadding.y * 2.0f; } + ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight())); } + float MenuBarHeight() const { return (Flags & ImGuiWindowFlags_MenuBar) ? CalcFontSize() + GImGui->Style.FramePadding.y * 2.0f : 0.0f; } + ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight(); return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight()); } +}; + +//----------------------------------------------------------------------------- +// Internal API +// No guarantee of forward compatibility here. +//----------------------------------------------------------------------------- + +namespace ImGui +{ + // We should always have a CurrentWindow in the stack (there is an implicit "Debug" window) + // If this ever crash because g.CurrentWindow is NULL it means that either + // - ImGui::NewFrame() has never been called, which is illegal. + // - You are calling ImGui functions after ImGui::Render() and before the next ImGui::NewFrame(), which is also illegal. + inline ImGuiWindow* GetCurrentWindowRead() { ImGuiContext& g = *GImGui; return g.CurrentWindow; } + inline ImGuiWindow* GetCurrentWindow() { ImGuiContext& g = *GImGui; g.CurrentWindow->Accessed = true; return g.CurrentWindow; } + IMGUI_API ImGuiWindow* GetParentWindow(); + IMGUI_API ImGuiWindow* FindWindowByName(const char* name); + IMGUI_API void FocusWindow(ImGuiWindow* window); + + IMGUI_API void EndFrame(); // Ends the ImGui frame. Automatically called by Render()! you most likely don't need to ever call that yourself directly. If you don't need to render you can call EndFrame() but you'll have wasted CPU already. If you don't need to render, don't create any windows instead! + + IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow* window); + IMGUI_API void SetHoveredID(ImGuiID id); + IMGUI_API void KeepAliveID(ImGuiID id); + + IMGUI_API void ItemSize(const ImVec2& size, float text_offset_y = 0.0f); + IMGUI_API void ItemSize(const ImRect& bb, float text_offset_y = 0.0f); + IMGUI_API bool ItemAdd(const ImRect& bb, const ImGuiID* id); + IMGUI_API bool IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged); + IMGUI_API bool IsHovered(const ImRect& bb, ImGuiID id, bool flatten_childs = false); + IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, bool is_active, bool tab_stop = true); // Return true if focus is requested + IMGUI_API void FocusableItemUnregister(ImGuiWindow* window); + IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_x, float default_y); + IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x); + + IMGUI_API void OpenPopupEx(const char* str_id, bool reopen_existing); + + inline IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul) { ImVec4 c = GImGui->Style.Colors[idx]; c.w *= GImGui->Style.Alpha * alpha_mul; return ImGui::ColorConvertFloat4ToU32(c); } + inline IMGUI_API ImU32 GetColorU32(const ImVec4& col) { ImVec4 c = col; c.w *= GImGui->Style.Alpha; return ImGui::ColorConvertFloat4ToU32(c); } + + // NB: All position are in absolute pixels coordinates (not window coordinates) + // FIXME: All those functions are a mess and needs to be refactored into something decent. Avoid use outside of imgui.cpp! + // We need: a sort of symbol library, preferably baked into font atlas when possible + decent text rendering helpers. + IMGUI_API void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true); + IMGUI_API void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width); + IMGUI_API void RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, ImGuiAlign align = ImGuiAlign_Default, const ImVec2* clip_min = NULL, const ImVec2* clip_max = NULL); + IMGUI_API void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f); + IMGUI_API void RenderCollapseTriangle(ImVec2 pos, bool is_open, float scale = 1.0f, bool shadow = false); + IMGUI_API void RenderBullet(ImVec2 pos); + IMGUI_API void RenderCheckMark(ImVec2 pos, ImU32 col); + IMGUI_API const char* FindRenderedTextEnd(const char* text, const char* text_end = NULL); // Find the optional ## from which we stop displaying text. + + IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0); + IMGUI_API bool ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0,0), ImGuiButtonFlags flags = 0); + IMGUI_API bool CloseButton(ImGuiID id, const ImVec2& pos, float radius); + + IMGUI_API bool SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power); + IMGUI_API bool SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format); + + IMGUI_API bool DragBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_speed, float v_min, float v_max, int decimal_precision, float power); + IMGUI_API bool DragFloatN(const char* label, float* v, int components, float v_speed, float v_min, float v_max, const char* display_format, float power); + IMGUI_API bool DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format); + + IMGUI_API bool InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags); + IMGUI_API bool InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags); + IMGUI_API bool InputScalarEx(const char* label, ImGuiDataType data_type, void* data_ptr, void* step_ptr, void* step_fast_ptr, const char* scalar_format, ImGuiInputTextFlags extra_flags); + IMGUI_API bool InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision); + + IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); + IMGUI_API bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0); // Consume previous SetNextTreeNodeOpened() data, if any. May return true when logging + IMGUI_API void TreePushRawID(ImGuiID id); + + IMGUI_API void PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size); + + IMGUI_API int ParseFormatPrecision(const char* fmt, int default_value); + IMGUI_API float RoundScalar(float value, int decimal_precision); + +} // namespace ImGui + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#ifdef _MSC_VER +#pragma warning (pop) +#endif diff --git a/modules/onscreengui/ext/imgui/stb_rect_pack.h b/modules/onscreengui/ext/imgui/stb_rect_pack.h index eb0ef2f268..fafd889716 100644 --- a/modules/onscreengui/ext/imgui/stb_rect_pack.h +++ b/modules/onscreengui/ext/imgui/stb_rect_pack.h @@ -1,4 +1,4 @@ -// stb_rect_pack.h - v0.05 - public domain - rectangle packing +// stb_rect_pack.h - v0.08 - public domain - rectangle packing // Sean Barrett 2014 // // Useful for e.g. packing rectangular textures into an atlas. @@ -13,6 +13,7 @@ // More docs to come. // // No memory allocations; uses qsort() and assert() from stdlib. +// Can override those by defining STBRP_SORT and STBRP_ASSERT. // // This library currently uses the Skyline Bottom-Left algorithm. // @@ -20,11 +21,29 @@ // implement them to the same API, but with a different init // function. // +// Credits +// +// Library +// Sean Barrett +// Minor features +// Martins Mozeiko +// Bugfixes / warning fixes +// Jeremy Jaussaud +// // Version history: // +// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0) +// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0) +// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort // 0.05: added STBRP_ASSERT to allow replacing assert // 0.04: fixed minor bug in STBRP_LARGE_RECTS support // 0.01: initial release +// +// LICENSE +// +// This software is in the public domain. Where that dedication is not +// recognized, you are granted a perpetual, irrevocable license to copy, +// distribute, and modify this file as you see fit. ////////////////////////////////////////////////////////////////////////////// // @@ -169,7 +188,10 @@ struct stbrp_context // #ifdef STB_RECT_PACK_IMPLEMENTATION +#ifndef STBRP_SORT #include +#define STBRP_SORT qsort +#endif #ifndef STBRP_ASSERT #include @@ -246,9 +268,9 @@ STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, } // find minimum y position if it starts at x1 -static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste) +static int stbrp__skyline_find_min_y(stbrp_context *, stbrp_node *first, int x0, int width, int *pwaste) { - (void)c; + //(void)c; stbrp_node *node = first; int x1 = x0 + width; int min_y, visited_width, waste_area; @@ -525,20 +547,24 @@ STBRP_DEF void stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int n } // sort according to heuristic - qsort(rects, num_rects, sizeof(rects[0]), rect_height_compare); + STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare); for (i=0; i < num_rects; ++i) { - stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h); - if (fr.prev_link) { - rects[i].x = (stbrp_coord) fr.x; - rects[i].y = (stbrp_coord) fr.y; + if (rects[i].w == 0 || rects[i].h == 0) { + rects[i].x = rects[i].y = 0; // empty rect needs no space } else { - rects[i].x = rects[i].y = STBRP__MAXVAL; + stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h); + if (fr.prev_link) { + rects[i].x = (stbrp_coord) fr.x; + rects[i].y = (stbrp_coord) fr.y; + } else { + rects[i].x = rects[i].y = STBRP__MAXVAL; + } } } // unsort - qsort(rects, num_rects, sizeof(rects[0]), rect_original_order); + STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order); // set was_packed flags for (i=0; i < num_rects; ++i) diff --git a/modules/onscreengui/ext/imgui/stb_textedit.h b/modules/onscreengui/ext/imgui/stb_textedit.h index 5aa79f02ad..3c3003252a 100644 --- a/modules/onscreengui/ext/imgui/stb_textedit.h +++ b/modules/onscreengui/ext/imgui/stb_textedit.h @@ -1,4 +1,8 @@ -// stb_textedit.h - v1.4 - public domain - Sean Barrett +// [ImGui] this is a slightly modified version of stb_truetype.h 1.8 +// [ImGui] - fixed some minor warnings +// [ImGui] - added STB_TEXTEDIT_MOVEWORDLEFT/STB_TEXTEDIT_MOVEWORDRIGHT custom handler (#473) + +// stb_textedit.h - v1.8 - public domain - Sean Barrett // Development of this library was sponsored by RAD Game Tools // // This C header file implements the guts of a multi-line text-editing @@ -17,19 +21,24 @@ // // LICENSE // -// This software has been placed in the public domain by its author. -// Where that dedication is not recognized, you are granted a perpetual, -// irrevocable license to copy and modify this file as you see fit. +// This software is dual-licensed to the public domain and under the following +// license: you are granted a perpetual, irrevocable license to copy, modify, +// publish, and distribute this file as you see fit. // // // DEPENDENCIES // -// Uses the C runtime function 'memmove'. Uses no other functions. -// Performs no runtime allocations. +// Uses the C runtime function 'memmove', which you can override +// by defining STB_TEXTEDIT_memmove before the implementation. +// Uses no other functions. Performs no runtime allocations. // // // VERSION HISTORY // +// 1.8 (2016-04-02) better keyboard handling when mouse button is down +// 1.7 (2015-09-13) change y range handling in case baseline is non-0 +// 1.6 (2015-04-15) allow STB_TEXTEDIT_memmove +// 1.5 (2014-09-10) add support for secondary keys for OS X // 1.4 (2014-08-17) fix signed/unsigned warnings // 1.3 (2014-06-19) fix mouse clicking to round to nearest char boundary // 1.2 (2014-05-27) fix some RAD types that had crept into the new code @@ -42,7 +51,13 @@ // ADDITIONAL CONTRIBUTORS // // Ulf Winklemann: move-by-word in 1.1 -// Scott Graham: mouse selection bugfix in 1.3 +// Fabian Giesen: secondary key inputs in 1.5 +// Martins Mozeiko: STB_TEXTEDIT_memmove +// +// Bugfixes: +// Scott Graham +// Daniel Keller +// Omar Cornut // // USAGE // @@ -137,11 +152,17 @@ // STB_TEXTEDIT_K_REDO keyboard input to perform redo // // Optional: -// STB_TEXTEDIT_K_INSERT keyboard input to toggle insert mode -// STB_TEXTEDIT_IS_SPACE(ch) true if character is whitespace (e.g. 'isspace'), -// required for WORDLEFT/WORDRIGHT -// STB_TEXTEDIT_K_WORDLEFT keyboard input to move cursor left one word // e.g. ctrl-LEFT -// STB_TEXTEDIT_K_WORDRIGHT keyboard input to move cursor right one word // e.g. ctrl-RIGHT +// STB_TEXTEDIT_K_INSERT keyboard input to toggle insert mode +// STB_TEXTEDIT_IS_SPACE(ch) true if character is whitespace (e.g. 'isspace'), +// required for default WORDLEFT/WORDRIGHT handlers +// STB_TEXTEDIT_MOVEWORDLEFT(obj,i) custom handler for WORDLEFT, returns index to move cursor to +// STB_TEXTEDIT_MOVEWORDRIGHT(obj,i) custom handler for WORDRIGHT, returns index to move cursor to +// STB_TEXTEDIT_K_WORDLEFT keyboard input to move cursor left one word // e.g. ctrl-LEFT +// STB_TEXTEDIT_K_WORDRIGHT keyboard input to move cursor right one word // e.g. ctrl-RIGHT +// STB_TEXTEDIT_K_LINESTART2 secondary keyboard input to move cursor to start of line +// STB_TEXTEDIT_K_LINEEND2 secondary keyboard input to move cursor to end of line +// STB_TEXTEDIT_K_TEXTSTART2 secondary keyboard input to move cursor to start of text +// STB_TEXTEDIT_K_TEXTEND2 secondary keyboard input to move cursor to end of text // // Todo: // STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page @@ -352,7 +373,10 @@ typedef struct // included just the "header" portion #ifdef STB_TEXTEDIT_IMPLEMENTATION -#include // memmove +#ifndef STB_TEXTEDIT_memmove +#include +#define STB_TEXTEDIT_memmove memmove +#endif ///////////////////////////////////////////////////////////////////////////// @@ -368,9 +392,6 @@ static int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y) float base_y = 0, prev_x; int i=0, k; - if (y < 0) - return 0; - r.x0 = r.x1 = 0; r.ymin = r.ymax = 0; r.num_chars = 0; @@ -381,6 +402,9 @@ static int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y) if (r.num_chars <= 0) return n; + if (i==0 && y < base_y + r.ymin) + return 0; + if (y < base_y + r.ymax) break; @@ -434,6 +458,8 @@ static void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *stat static void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) { int p = stb_text_locate_coord(str, x, y); + if (state->select_start == state->select_end) + state->select_start = state->cursor; state->cursor = state->select_end = p; } @@ -595,9 +621,9 @@ static int is_word_boundary( STB_TEXTEDIT_STRING *_str, int _idx ) return _idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(_str,_idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(_str, _idx) ) ) : 1; } -static int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *_str, STB_TexteditState *_state ) +#ifndef STB_TEXTEDIT_MOVEWORDLEFT +static int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *_str, int c ) { - int c = _state->cursor - 1; while( c >= 0 && !is_word_boundary( _str, c ) ) --c; @@ -606,11 +632,13 @@ static int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *_str, STB_Te return c; } +#define STB_TEXTEDIT_MOVEWORDLEFT stb_textedit_move_to_word_previous +#endif -static int stb_textedit_move_to_word_next( STB_TEXTEDIT_STRING *_str, STB_TexteditState *_state ) +#ifndef STB_TEXTEDIT_MOVEWORDRIGHT +static int stb_textedit_move_to_word_next( STB_TEXTEDIT_STRING *_str, int c ) { const int len = STB_TEXTEDIT_STRINGLEN(_str); - int c = _state->cursor+1; while( c < len && !is_word_boundary( _str, c ) ) ++c; @@ -619,6 +647,9 @@ static int stb_textedit_move_to_word_next( STB_TEXTEDIT_STRING *_str, STB_Texted return c; } +#define STB_TEXTEDIT_MOVEWORDRIGHT stb_textedit_move_to_word_next +#endif + #endif // update selection and cursor to match each other @@ -740,21 +771,12 @@ retry: state->has_preferred_x = 0; break; -#ifdef STB_TEXTEDIT_IS_SPACE +#ifdef STB_TEXTEDIT_MOVEWORDLEFT case STB_TEXTEDIT_K_WORDLEFT: if (STB_TEXT_HAS_SELECTION(state)) stb_textedit_move_to_first(state); else { - state->cursor = stb_textedit_move_to_word_previous(str, state); - stb_textedit_clamp( str, state ); - } - break; - - case STB_TEXTEDIT_K_WORDRIGHT: - if (STB_TEXT_HAS_SELECTION(state)) - stb_textedit_move_to_last(str, state); - else { - state->cursor = stb_textedit_move_to_word_next(str, state); + state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor-1); stb_textedit_clamp( str, state ); } break; @@ -763,17 +785,28 @@ retry: if( !STB_TEXT_HAS_SELECTION( state ) ) stb_textedit_prep_selection_at_cursor(state); - state->cursor = stb_textedit_move_to_word_previous(str, state); + state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor-1); state->select_end = state->cursor; stb_textedit_clamp( str, state ); break; +#endif + +#ifdef STB_TEXTEDIT_MOVEWORDRIGHT + case STB_TEXTEDIT_K_WORDRIGHT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_last(str, state); + else { + state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor+1); + stb_textedit_clamp( str, state ); + } + break; case STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT: if( !STB_TEXT_HAS_SELECTION( state ) ) stb_textedit_prep_selection_at_cursor(state); - state->cursor = stb_textedit_move_to_word_next(str, state); + state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor+1); state->select_end = state->cursor; stb_textedit_clamp( str, state ); @@ -917,23 +950,35 @@ retry: state->has_preferred_x = 0; break; +#ifdef STB_TEXTEDIT_K_TEXTSTART2 + case STB_TEXTEDIT_K_TEXTSTART2: +#endif case STB_TEXTEDIT_K_TEXTSTART: state->cursor = state->select_start = state->select_end = 0; state->has_preferred_x = 0; break; +#ifdef STB_TEXTEDIT_K_TEXTEND2 + case STB_TEXTEDIT_K_TEXTEND2: +#endif case STB_TEXTEDIT_K_TEXTEND: state->cursor = STB_TEXTEDIT_STRINGLEN(str); state->select_start = state->select_end = 0; state->has_preferred_x = 0; break; +#ifdef STB_TEXTEDIT_K_TEXTSTART2 + case STB_TEXTEDIT_K_TEXTSTART2 | STB_TEXTEDIT_K_SHIFT: +#endif case STB_TEXTEDIT_K_TEXTSTART | STB_TEXTEDIT_K_SHIFT: stb_textedit_prep_selection_at_cursor(state); state->cursor = state->select_end = 0; state->has_preferred_x = 0; break; +#ifdef STB_TEXTEDIT_K_TEXTEND2 + case STB_TEXTEDIT_K_TEXTEND2 | STB_TEXTEDIT_K_SHIFT: +#endif case STB_TEXTEDIT_K_TEXTEND | STB_TEXTEDIT_K_SHIFT: stb_textedit_prep_selection_at_cursor(state); state->cursor = state->select_end = STB_TEXTEDIT_STRINGLEN(str); @@ -941,6 +986,9 @@ retry: break; +#ifdef STB_TEXTEDIT_K_LINESTART2 + case STB_TEXTEDIT_K_LINESTART2: +#endif case STB_TEXTEDIT_K_LINESTART: { StbFindState find; stb_textedit_clamp(str, state); @@ -951,16 +999,25 @@ retry: break; } +#ifdef STB_TEXTEDIT_K_LINEEND2 + case STB_TEXTEDIT_K_LINEEND2: +#endif case STB_TEXTEDIT_K_LINEEND: { StbFindState find; stb_textedit_clamp(str, state); stb_textedit_move_to_first(state); stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); - state->cursor = find.first_char + find.length; + state->has_preferred_x = 0; + state->cursor = find.first_char + find.length; + if (find.length > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) == STB_TEXTEDIT_NEWLINE) + --state->cursor; break; } +#ifdef STB_TEXTEDIT_K_LINESTART2 + case STB_TEXTEDIT_K_LINESTART2 | STB_TEXTEDIT_K_SHIFT: +#endif case STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT: { StbFindState find; stb_textedit_clamp(str, state); @@ -971,13 +1028,19 @@ retry: break; } +#ifdef STB_TEXTEDIT_K_LINEEND2 + case STB_TEXTEDIT_K_LINEEND2 | STB_TEXTEDIT_K_SHIFT: +#endif case STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT: { StbFindState find; stb_textedit_clamp(str, state); stb_textedit_prep_selection_at_cursor(state); stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); - state->cursor = state->select_end = find.first_char + find.length; state->has_preferred_x = 0; + state->cursor = find.first_char + find.length; + if (find.length > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) == STB_TEXTEDIT_NEWLINE) + --state->cursor; + state->select_end = state->cursor; break; } @@ -1008,13 +1071,13 @@ static void stb_textedit_discard_undo(StbUndoState *state) int n = state->undo_rec[0].insert_length, i; // delete n characters from all other records state->undo_char_point = state->undo_char_point - (short) n; // vsnet05 - memmove(state->undo_char, state->undo_char + n, (size_t) ((size_t)state->undo_char_point*sizeof(STB_TEXTEDIT_CHARTYPE))); + STB_TEXTEDIT_memmove(state->undo_char, state->undo_char + n, (size_t) ((size_t)state->undo_char_point*sizeof(STB_TEXTEDIT_CHARTYPE))); for (i=0; i < state->undo_point; ++i) if (state->undo_rec[i].char_storage >= 0) state->undo_rec[i].char_storage = state->undo_rec[i].char_storage - (short) n; // vsnet05 // @OPTIMIZE: get rid of char_storage and infer it } --state->undo_point; - memmove(state->undo_rec, state->undo_rec+1, (size_t) ((size_t)state->undo_point*sizeof(state->undo_rec[0]))); + STB_TEXTEDIT_memmove(state->undo_rec, state->undo_rec+1, (size_t) ((size_t)state->undo_point*sizeof(state->undo_rec[0]))); } } @@ -1032,13 +1095,13 @@ static void stb_textedit_discard_redo(StbUndoState *state) int n = state->undo_rec[k].insert_length, i; // delete n characters from all other records state->redo_char_point = state->redo_char_point + (short) n; // vsnet05 - memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((size_t)(STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_char_point)*sizeof(STB_TEXTEDIT_CHARTYPE))); + STB_TEXTEDIT_memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((size_t)(STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_char_point)*sizeof(STB_TEXTEDIT_CHARTYPE))); for (i=state->redo_point; i < k; ++i) if (state->undo_rec[i].char_storage >= 0) state->undo_rec[i].char_storage = state->undo_rec[i].char_storage + (short) n; // vsnet05 } ++state->redo_point; - memmove(state->undo_rec + state->redo_point-1, state->undo_rec + state->redo_point, (size_t) ((size_t)(STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point)*sizeof(state->undo_rec[0]))); + STB_TEXTEDIT_memmove(state->undo_rec + state->redo_point-1, state->undo_rec + state->redo_point, (size_t) ((size_t)(STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point)*sizeof(state->undo_rec[0]))); } } diff --git a/modules/onscreengui/ext/imgui/stb_truetype.h b/modules/onscreengui/ext/imgui/stb_truetype.h index 3c5d6f304e..e6dae97515 100644 --- a/modules/onscreengui/ext/imgui/stb_truetype.h +++ b/modules/onscreengui/ext/imgui/stb_truetype.h @@ -1,8 +1,5 @@ -// [ImGui] this is a slightly modified version of stb_truetype.h 1.02 -// [ImGui] we added stbtt_PackFontRangesGatherRects() and stbtt_PackFontRangesRenderIntoRects() and modified stbtt_PackBegin() - -// stb_truetype.h - v1.02 - public domain -// authored from 2009-2014 by Sean Barrett / RAD Game Tools +// stb_truetype.h - v1.10 - public domain +// authored from 2009-2015 by Sean Barrett / RAD Game Tools // // This library processes TrueType files: // parse files @@ -24,6 +21,10 @@ // Mikko Mononen: compound shape support, more cmap formats // Tor Andersson: kerning, subpixel rendering // +// Misc other: +// Ryan Gordon +// Simon Glass +// // Bug/warning reports/fixes: // "Zer" on mollyrocket (with fix) // Cass Everitt @@ -37,46 +38,41 @@ // Johan Duparc // Hou Qiming // Fabian "ryg" Giesen -// -// Misc other: -// Ryan Gordon +// Martins Mozeiko +// Cap Petschulat +// Omar Cornut +// github:aloucks +// Peter LaValle +// Sergey Popov +// Giumo X. Clanjor +// Higor Euripedes +// Thomas Fields +// Derek Vinyard // // VERSION HISTORY // -// 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++ -// 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match -// non-oversampled; STBTT_POINT_SIZE for packed case only -// 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling -// 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg) -// 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID -// 0.8b (2014-07-07) fix a warning -// 0.8 (2014-05-25) fix a few more warnings -// 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back -// 0.6c (2012-07-24) improve documentation -// 0.6b (2012-07-20) fix a few more warnings -// 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels, -// stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty -// 0.5 (2011-12-09) bugfixes: -// subpixel glyph renderer computed wrong bounding box -// first vertex of shape can be off-curve (FreeSans) -// 0.4b (2011-12-03) fixed an error in the font baking example -// 0.4 (2011-12-01) kerning, subpixel rendering (tor) -// bugfixes for: -// codepoint-to-glyph conversion using table fmt=12 -// codepoint-to-glyph conversion using table fmt=4 -// stbtt_GetBakedQuad with non-square texture (Zer) -// updated Hello World! sample to use kerning and subpixel -// fixed some warnings -// 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM) -// userdata, malloc-from-userdata, non-zero fill (stb) -// 0.2 (2009-03-11) Fix unsigned/signed char warnings -// 0.1 (2009-03-09) First public release +// 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef +// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly +// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges +// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; +// variant PackFontRanges to pack and render in separate phases; +// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); +// fixed an assert() bug in the new rasterizer +// replace assert() with STBTT_assert() in new rasterizer +// 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine) +// also more precise AA rasterizer, except if shapes overlap +// remove need for STBTT_sort +// 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC +// 1.04 (2015-04-15) typo in example +// 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes +// +// Full history can be found at the end of this file. // // LICENSE // -// This software is in the public domain. Where that dedication is not -// recognized, you are granted a perpetual, irrevokable license to copy -// and modify this file as you see fit. +// This software is dual-licensed to the public domain and under the following +// license: you are granted a perpetual, irrevocable license to copy, modify, +// publish, and distribute this file as you see fit. // // USAGE // @@ -86,6 +82,9 @@ // before the #include of this file. This expands out the actual // implementation into that C/C++ file. // +// To make the implementation private to the file that generates the implementation, +// #define STBTT_STATIC +// // Simple 3D API (don't ship this, but it's fine for tools and quick start) // stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture // stbtt_GetBakedQuad() -- compute quad to draw for a given char @@ -112,6 +111,15 @@ // stbtt_GetFontVMetrics() // stbtt_GetCodepointKernAdvance() // +// Starting with version 1.06, the rasterizer was replaced with a new, +// faster and generally-more-precise rasterizer. The new rasterizer more +// accurately measures pixel coverage for anti-aliasing, except in the case +// where multiple shapes overlap, in which case it overestimates the AA pixel +// coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If +// this turns out to be a problem, you can re-enable the old rasterizer with +// #define STBTT_RASTERIZER_VERSION 1 +// which will incur about a 15% speed hit. +// // ADDITIONAL DOCUMENTATION // // Immediately after this block comment are a series of sample programs. @@ -211,7 +219,15 @@ // Baked bitmap interface 70 LOC / // Font name matching & access 150 LOC ---- 150 // C runtime library abstraction 60 LOC ---- 60 - +// +// +// PERFORMANCE MEASUREMENTS FOR 1.06: +// +// 32-bit 64-bit +// Previous release: 8.83 s 7.68 s +// Pool allocations: 7.72 s 6.34 s +// Inline sort : 6.54 s 5.65 s +// New rasterizer : 5.63 s 5.00 s ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// @@ -225,16 +241,16 @@ #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation #include "stb_truetype.h" -char ttf_buffer[1<<20]; +unsigned char ttf_buffer[1<<20]; unsigned char temp_bitmap[512*512]; stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs -GLstbtt_uint ftex; +GLuint ftex; void my_stbtt_initfont(void) { fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb")); - stbtt_BakeFontBitmap(data,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits! + stbtt_BakeFontBitmap(ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits! // can free ttf_buffer at this point glGenTextures(1, &ftex); glBindTexture(GL_TEXTURE_2D, ftex); @@ -246,6 +262,7 @@ void my_stbtt_initfont(void) void my_stbtt_print(float x, float y, char *text) { // assume orthographic projection with units = screen pixels, origin at top left + glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, ftex); glBegin(GL_QUADS); while (*text) { @@ -321,7 +338,7 @@ int main(int arg, char **argv) stbtt_fontinfo font; int i,j,ascent,baseline,ch=0; float scale, xpos=2; // leave a little padding in case the character extends left - char *text = "Heljo World!"; + char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb")); stbtt_InitFont(&font, buffer, 0); @@ -379,18 +396,6 @@ int main(int arg, char **argv) typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1]; typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1]; - #ifdef STBTT_STATIC - #define STBTT_DEF static - #else - #define STBTT_DEF extern - #endif - - // #define your own STBTT_sort() to override this to avoid qsort - #ifndef STBTT_sort - #include - #define STBTT_sort(data,num_items,item_size,compare_func) qsort(data,num_items,item_size,compare_func) - #endif - // #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h #ifndef STBTT_ifloor #include @@ -403,6 +408,11 @@ int main(int arg, char **argv) #define STBTT_sqrt(x) sqrt(x) #endif + #ifndef STBTT_fabs + #include + #define STBTT_fabs(x) fabs(x) + #endif + // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h #ifndef STBTT_malloc #include @@ -437,6 +447,12 @@ int main(int arg, char **argv) #ifndef __STB_INCLUDE_STB_TRUETYPE_H__ #define __STB_INCLUDE_STB_TRUETYPE_H__ +#ifdef STBTT_STATIC +#define STBTT_DEF static +#else +#define STBTT_DEF extern +#endif + #ifdef __cplusplus extern "C" { #endif @@ -512,7 +528,7 @@ STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, i // Future calls using this context will pack characters into the bitmap passed // in here: a 1-channel bitmap that is weight x height. stride_in_bytes is // the distance from one row to the next (or 0 to mean they are packed tightly -// together). "padding" is // the amount of padding to leave between each +// together). "padding" is the amount of padding to leave between each // character (normally you want '1' for bitmaps you'll use as textures with // bilinear filtering). // @@ -541,34 +557,34 @@ STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, unsigned char *fontd typedef struct { float font_size; - int first_unicode_char_in_range; - int num_chars_in_range; + int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint + int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints + int num_chars; stbtt_packedchar *chardata_for_range; // output + unsigned char h_oversample, v_oversample; // don't set these, they're used internally } stbtt_pack_range; STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges); // Creates character bitmaps from multiple ranges of characters stored in // ranges. This will usually create a better-packed bitmap than multiple -// calls to stbtt_PackFontRange. - -STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); -STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); -// Those functions are called by stbtt_PackFontRanges(). If you want to -// pack multiple fonts or custom data into a same texture, you may copy -// the contents of stbtt_PackFontRanges() and create a custom version -// using those functions. +// calls to stbtt_PackFontRange. Note that you can call this multiple +// times within a single PackBegin/PackEnd. STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample); // Oversampling a font increases the quality by allowing higher-quality subpixel // positioning, and is especially valuable at smaller text sizes. // // This function sets the amount of oversampling for all following calls to -// stbtt_PackFontRange(s). The default (no oversampling) is achieved by -// h_oversample=1, v_oversample=1. The total number of pixels required is +// stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given +// pack context. The default (no oversampling) is achieved by h_oversample=1 +// and v_oversample=1. The total number of pixels required is // h_oversample*v_oversample larger than the default; for example, 2x2 // oversampling requires 4x the storage of 1x1. For best results, render // oversampled textures with bilinear filtering. Look at the readme in // stb/tests/oversample for information about oversampled fonts +// +// To use with PackFontRangesGather etc., you must set it before calls +// call to PackFontRangesGatherRects. STBTT_DEF void stbtt_GetPackedQuad(stbtt_packedchar *chardata, int pw, int ph, // same data as above int char_index, // character to display @@ -576,6 +592,19 @@ STBTT_DEF void stbtt_GetPackedQuad(stbtt_packedchar *chardata, int pw, int ph, stbtt_aligned_quad *q, // output: quad to draw int align_to_integer); +STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); +STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects); +STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); +// Calling these functions in sequence is roughly equivalent to calling +// stbtt_PackFontRanges(). If you more control over the packing of multiple +// fonts, or if you want to pack custom data into a font texture, take a look +// at the source to of stbtt_PackFontRanges() and create a custom version +// using these functions, e.g. call GatherRects multiple times, +// building up a single array of rects, then call PackRects once, +// then call RenderIntoRects repeatedly. This may result in a +// better packing than calling PackFontRanges multiple times +// (or it may not). + // this is an opaque structure that you shouldn't mess with which holds // all the context needed from PackBegin to PackEnd. struct stbtt_pack_context { @@ -607,7 +636,7 @@ STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index); // The following structure is defined publically so you can declare one on // the stack or as a global or etc, but you should treat it as opaque. -typedef struct stbtt_fontinfo +struct stbtt_fontinfo { void * userdata; unsigned char * data; // pointer to .ttf file @@ -618,7 +647,7 @@ typedef struct stbtt_fontinfo int loca,head,glyf,hhea,hmtx,kern; // table locations as offset from start of .ttf int index_map; // a cmap mapping for our chosen character encoding int indexToLocFormat; // format needed to map from glyph index to glyph -} stbtt_fontinfo; +}; STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset); // Given an offset into the file that defines a font, this function builds @@ -786,7 +815,16 @@ typedef struct unsigned char *pixels; } stbtt__bitmap; -STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata); +// rasterize a shape with quadratic beziers into a bitmap +STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into + float flatness_in_pixels, // allowable error of curve in pixels + stbtt_vertex *vertices, // array of vertices defining shape + int num_verts, // number of vertices in above array + float scale_x, float scale_y, // scale applied to input vertices + float shift_x, float shift_y, // translation applied to input vertices + int x_off, int y_off, // another translation applied to input + int invert, // if non-zero, vertically flip shape + void *userdata); // context for to STBTT_MALLOC ////////////////////////////////////////////////////////////////////////////// // @@ -901,8 +939,16 @@ enum { // languageID for STBTT_PLATFORM_ID_MAC #define STBTT_MAX_OVERSAMPLE 8 #endif +#if STBTT_MAX_OVERSAMPLE > 255 +#error "STBTT_MAX_OVERSAMPLE cannot be > 255" +#endif + typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1]; +#ifndef STBTT_RASTERIZER_VERSION +#define STBTT_RASTERIZER_VERSION 2 +#endif + ////////////////////////////////////////////////////////////////////////// // // accessors to parse data from file @@ -971,7 +1017,7 @@ STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *font_collection, stbtt_int32 n = ttLONG(font_collection+8); if (index >= n) return -1; - return ttULONG(font_collection+12+index*14); + return ttULONG(font_collection+12+index*4); } } return -1; @@ -1059,7 +1105,6 @@ STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codep stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1; stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10); stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1; - stbtt_uint16 item, offset, start, end; // do a binary search of the segments stbtt_uint32 endCount = index_map + 14; @@ -1076,8 +1121,8 @@ STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codep // now decrement to bias correctly to find smallest search -= 2; while (entrySelector) { + stbtt_uint16 end; searchRange >>= 1; - start = ttUSHORT(data + search + searchRange*2 + segcount*2 + 2); end = ttUSHORT(data + search + searchRange*2); if (unicode_codepoint > end) search += searchRange*2; @@ -1085,19 +1130,21 @@ STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codep } search += 2; - item = (stbtt_uint16) ((search - endCount) >> 1); + { + stbtt_uint16 offset, start; + stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1); - STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item)); - start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); - end = ttUSHORT(data + index_map + 14 + 2 + 2*item); - if (unicode_codepoint < start) - return 0; + STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item)); + start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); + if (unicode_codepoint < start) + return 0; - offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); - if (offset == 0) - return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); + offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); + if (offset == 0) + return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); - return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); + return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); + } } else if (format == 12 || format == 13) { stbtt_uint32 ngroups = ttULONG(data+index_map+12); stbtt_int32 low,high; @@ -1519,7 +1566,7 @@ STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v) STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) { - int x0,y0,x1,y1; + int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) { // e.g. space character if (ix0) *ix0 = 0; @@ -1550,42 +1597,131 @@ STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codep stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1); } +////////////////////////////////////////////////////////////////////////////// +// +// Rasterizer + +typedef struct stbtt__hheap_chunk +{ + struct stbtt__hheap_chunk *next; +} stbtt__hheap_chunk; + +typedef struct stbtt__hheap +{ + struct stbtt__hheap_chunk *head; + void *first_free; + int num_remaining_in_head_chunk; +} stbtt__hheap; + +static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata) +{ + if (hh->first_free) { + void *p = hh->first_free; + hh->first_free = * (void **) p; + return p; + } else { + if (hh->num_remaining_in_head_chunk == 0) { + int count = (size < 32 ? 2000 : size < 128 ? 800 : 100); + stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata); + if (c == NULL) + return NULL; + c->next = hh->head; + hh->head = c; + hh->num_remaining_in_head_chunk = count; + } + --hh->num_remaining_in_head_chunk; + return (char *) (hh->head) + size * hh->num_remaining_in_head_chunk; + } +} + +static void stbtt__hheap_free(stbtt__hheap *hh, void *p) +{ + *(void **) p = hh->first_free; + hh->first_free = p; +} + +static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata) +{ + stbtt__hheap_chunk *c = hh->head; + while (c) { + stbtt__hheap_chunk *n = c->next; + STBTT_free(c, userdata); + c = n; + } +} + typedef struct stbtt__edge { float x0,y0, x1,y1; int invert; } stbtt__edge; + typedef struct stbtt__active_edge { + struct stbtt__active_edge *next; + #if STBTT_RASTERIZER_VERSION==1 int x,dx; float ey; - struct stbtt__active_edge *next; - int valid; + int direction; + #elif STBTT_RASTERIZER_VERSION==2 + float fx,fdx,fdy; + float direction; + float sy; + float ey; + #else + #error "Unrecognized value of STBTT_RASTERIZER_VERSION" + #endif } stbtt__active_edge; -#define FIXSHIFT 10 -#define FIX (1 << FIXSHIFT) -#define FIXMASK (FIX-1) +#if STBTT_RASTERIZER_VERSION == 1 +#define STBTT_FIXSHIFT 10 +#define STBTT_FIX (1 << STBTT_FIXSHIFT) +#define STBTT_FIXMASK (STBTT_FIX-1) -static stbtt__active_edge *new_active(stbtt__edge *e, int off_x, float start_point, void *userdata) +static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) { - stbtt__active_edge *z = (stbtt__active_edge *) STBTT_malloc(sizeof(*z), userdata); // @TODO: make a pool of these!!! + stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); - STBTT_assert(e->y0 <= start_point); + STBTT_assert(z != NULL); if (!z) return z; - // round dx down to avoid going too far + + // round dx down to avoid overshooting if (dxdy < 0) - z->dx = -STBTT_ifloor(FIX * -dxdy); + z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy); else - z->dx = STBTT_ifloor(FIX * dxdy); - z->x = STBTT_ifloor(FIX * (e->x0 + dxdy * (start_point - e->y0))); - z->x -= off_x * FIX; + z->dx = STBTT_ifloor(STBTT_FIX * dxdy); + + z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount + z->x -= off_x * STBTT_FIX; + z->ey = e->y1; z->next = 0; - z->valid = e->invert ? 1 : -1; + z->direction = e->invert ? 1 : -1; return z; } +#elif STBTT_RASTERIZER_VERSION == 2 +static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) +{ + stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); + float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); + STBTT_assert(z != NULL); + //STBTT_assert(e->y0 <= start_point); + if (!z) return z; + z->fdx = dxdy; + z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f; + z->fx = e->x0 + dxdy * (start_point - e->y0); + z->fx -= off_x; + z->direction = e->invert ? 1.0f : -1.0f; + z->sy = e->y0; + z->ey = e->y1; + z->next = 0; + return z; +} +#else +#error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif +#if STBTT_RASTERIZER_VERSION == 1 // note: this routine clips fills that extend off the edges... ideally this // wouldn't happen, but it could happen if the truetype glyph bounding boxes // are wrong, or if the user supplies a too-small bitmap @@ -1597,26 +1733,26 @@ static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__ac while (e) { if (w == 0) { // if we're currently at zero, we need to record the edge start point - x0 = e->x; w += e->valid; + x0 = e->x; w += e->direction; } else { - int x1 = e->x; w += e->valid; + int x1 = e->x; w += e->direction; // if we went to zero, we need to draw if (w == 0) { - int i = x0 >> FIXSHIFT; - int j = x1 >> FIXSHIFT; + int i = x0 >> STBTT_FIXSHIFT; + int j = x1 >> STBTT_FIXSHIFT; if (i < len && j >= 0) { if (i == j) { // x0,x1 are the same pixel, so compute combined coverage - scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> FIXSHIFT); + scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT); } else { if (i >= 0) // add antialiasing for x0 - scanline[i] = scanline[i] + (stbtt_uint8) (((FIX - (x0 & FIXMASK)) * max_weight) >> FIXSHIFT); + scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT); else i = -1; // clip if (j < len) // add antialiasing for x1 - scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & FIXMASK) * max_weight) >> FIXSHIFT); + scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT); else j = len; // clip @@ -1633,6 +1769,7 @@ static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__ac static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) { + stbtt__hheap hh = { 0, 0, 0 }; stbtt__active_edge *active = NULL; int y,j=0; int max_weight = (255 / vsubsample); // weight per vertical scanline @@ -1660,9 +1797,9 @@ static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, stbtt__active_edge * z = *step; if (z->ey <= scan_y) { *step = z->next; // delete from list - STBTT_assert(z->valid); - z->valid = 0; - STBTT_free(z, userdata); + STBTT_assert(z->direction); + z->direction = 0; + stbtt__hheap_free(&hh, z); } else { z->x += z->dx; // advance to position for current scanline step = &((*step)->next); // advance through list @@ -1691,22 +1828,24 @@ static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline while (e->y0 <= scan_y) { if (e->y1 > scan_y) { - stbtt__active_edge *z = new_active(e, off_x, scan_y, userdata); - // find insertion point - if (active == NULL) - active = z; - else if (z->x < active->x) { - // insert at front - z->next = active; - active = z; - } else { - // find thing to insert AFTER - stbtt__active_edge *p = active; - while (p->next && p->next->x < z->x) - p = p->next; - // at this point, p->next->x is NOT < z->x - z->next = p->next; - p->next = z; + stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata); + if (z != NULL) { + // find insertion point + if (active == NULL) + active = z; + else if (z->x < active->x) { + // insert at front + z->next = active; + active = z; + } else { + // find thing to insert AFTER + stbtt__active_edge *p = active; + while (p->next && p->next->x < z->x) + p = p->next; + // at this point, p->next->x is NOT < z->x + z->next = p->next; + p->next = z; + } } } ++e; @@ -1722,24 +1861,395 @@ static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, ++j; } - while (active) { - stbtt__active_edge *z = active; - active = active->next; - STBTT_free(z, userdata); - } + stbtt__hheap_cleanup(&hh, userdata); if (scanline != scanline_data) STBTT_free(scanline, userdata); } -static int stbtt__edge_compare(const void *p, const void *q) -{ - stbtt__edge *a = (stbtt__edge *) p; - stbtt__edge *b = (stbtt__edge *) q; +#elif STBTT_RASTERIZER_VERSION == 2 - if (a->y0 < b->y0) return -1; - if (a->y0 > b->y0) return 1; - return 0; +// the edge passed in here does not cross the vertical line at x or the vertical line at x+1 +// (i.e. it has already been clipped to those) +static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1) +{ + if (y0 == y1) return; + STBTT_assert(y0 < y1); + STBTT_assert(e->sy <= e->ey); + if (y0 > e->ey) return; + if (y1 < e->sy) return; + if (y0 < e->sy) { + x0 += (x1-x0) * (e->sy - y0) / (y1-y0); + y0 = e->sy; + } + if (y1 > e->ey) { + x1 += (x1-x0) * (e->ey - y1) / (y1-y0); + y1 = e->ey; + } + + if (x0 == x) + STBTT_assert(x1 <= x+1); + else if (x0 == x+1) + STBTT_assert(x1 >= x); + else if (x0 <= x) + STBTT_assert(x1 <= x); + else if (x0 >= x+1) + STBTT_assert(x1 >= x+1); + else + STBTT_assert(x1 >= x && x1 <= x+1); + + if (x0 <= x && x1 <= x) + scanline[x] += e->direction * (y1-y0); + else if (x0 >= x+1 && x1 >= x+1) + ; + else { + STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1); + scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position + } +} + +static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top) +{ + float y_bottom = y_top+1; + + while (e) { + // brute force every pixel + + // compute intersection points with top & bottom + STBTT_assert(e->ey >= y_top); + + if (e->fdx == 0) { + float x0 = e->fx; + if (x0 < len) { + if (x0 >= 0) { + stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom); + stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom); + } else { + stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom); + } + } + } else { + float x0 = e->fx; + float dx = e->fdx; + float xb = x0 + dx; + float x_top, x_bottom; + float sy0,sy1; + float dy = e->fdy; + STBTT_assert(e->sy <= y_bottom && e->ey >= y_top); + + // compute endpoints of line segment clipped to this scanline (if the + // line segment starts on this scanline. x0 is the intersection of the + // line with y_top, but that may be off the line segment. + if (e->sy > y_top) { + x_top = x0 + dx * (e->sy - y_top); + sy0 = e->sy; + } else { + x_top = x0; + sy0 = y_top; + } + if (e->ey < y_bottom) { + x_bottom = x0 + dx * (e->ey - y_top); + sy1 = e->ey; + } else { + x_bottom = xb; + sy1 = y_bottom; + } + + if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) { + // from here on, we don't have to range check x values + + if ((int) x_top == (int) x_bottom) { + float height; + // simple case, only spans one pixel + int x = (int) x_top; + height = sy1 - sy0; + STBTT_assert(x >= 0 && x < len); + scanline[x] += e->direction * (1-((x_top - x) + (x_bottom-x))/2) * height; + scanline_fill[x] += e->direction * height; // everything right of this pixel is filled + } else { + int x,x1,x2; + float y_crossing, step, sign, area; + // covers 2+ pixels + if (x_top > x_bottom) { + // flip scanline vertically; signed area is the same + float t; + sy0 = y_bottom - (sy0 - y_top); + sy1 = y_bottom - (sy1 - y_top); + t = sy0, sy0 = sy1, sy1 = t; + t = x_bottom, x_bottom = x_top, x_top = t; + dx = -dx; + dy = -dy; + t = x0, x0 = xb, xb = t; + } + + x1 = (int) x_top; + x2 = (int) x_bottom; + // compute intersection with y axis at x1+1 + y_crossing = (x1+1 - x0) * dy + y_top; + + sign = e->direction; + // area of the rectangle covered from y0..y_crossing + area = sign * (y_crossing-sy0); + // area of the triangle (x_top,y0), (x+1,y0), (x+1,y_crossing) + scanline[x1] += area * (1-((x_top - x1)+(x1+1-x1))/2); + + step = sign * dy; + for (x = x1+1; x < x2; ++x) { + scanline[x] += area + step/2; + area += step; + } + y_crossing += dy * (x2 - (x1+1)); + + STBTT_assert(STBTT_fabs(area) <= 1.01f); + + scanline[x2] += area + sign * (1-((x2-x2)+(x_bottom-x2))/2) * (sy1-y_crossing); + + scanline_fill[x2] += sign * (sy1-sy0); + } + } else { + // if edge goes outside of box we're drawing, we require + // clipping logic. since this does not match the intended use + // of this library, we use a different, very slow brute + // force implementation + int x; + for (x=0; x < len; ++x) { + // cases: + // + // there can be up to two intersections with the pixel. any intersection + // with left or right edges can be handled by splitting into two (or three) + // regions. intersections with top & bottom do not necessitate case-wise logic. + // + // the old way of doing this found the intersections with the left & right edges, + // then used some simple logic to produce up to three segments in sorted order + // from top-to-bottom. however, this had a problem: if an x edge was epsilon + // across the x border, then the corresponding y position might not be distinct + // from the other y segment, and it might ignored as an empty segment. to avoid + // that, we need to explicitly produce segments based on x positions. + + // rename variables to clear pairs + float y0 = y_top; + float x1 = (float) (x); + float x2 = (float) (x+1); + float x3 = xb; + float y3 = y_bottom; + float y1,y2; + + // x = e->x + e->dx * (y-y_top) + // (y-y_top) = (x - e->x) / e->dx + // y = (x - e->x) / e->dx + y_top + y1 = (x - x0) / dx + y_top; + y2 = (x+1 - x0) / dx + y_top; + + if (x0 < x1 && x3 > x2) { // three segments descending down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else if (x3 < x1 && x0 > x2) { // three segments descending down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x0 < x1 && x3 > x1) { // two segments across x, down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x3 < x1 && x0 > x1) { // two segments across x, down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x0 < x2 && x3 > x2) { // two segments across x+1, down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else if (x3 < x2 && x0 > x2) { // two segments across x+1, down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else { // one segment + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3); + } + } + } + } + e = e->next; + } +} + +// directly AA rasterize edges w/o supersampling +static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) +{ + (void)vsubsample; + stbtt__hheap hh = { 0, 0, 0 }; + stbtt__active_edge *active = NULL; + int y,j=0, i; + float scanline_data[129], *scanline, *scanline2; + + if (result->w > 64) + scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata); + else + scanline = scanline_data; + + scanline2 = scanline + result->w; + + y = off_y; + e[n].y0 = (float) (off_y + result->h) + 1; + + while (j < result->h) { + // find center of pixel for this scanline + float scan_y_top = y + 0.0f; + float scan_y_bottom = y + 1.0f; + stbtt__active_edge **step = &active; + + STBTT_memset(scanline , 0, result->w*sizeof(scanline[0])); + STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0])); + + // update all active edges; + // remove all active edges that terminate before the top of this scanline + while (*step) { + stbtt__active_edge * z = *step; + if (z->ey <= scan_y_top) { + *step = z->next; // delete from list + STBTT_assert(z->direction); + z->direction = 0; + stbtt__hheap_free(&hh, z); + } else { + step = &((*step)->next); // advance through list + } + } + + // insert all edges that start before the bottom of this scanline + while (e->y0 <= scan_y_bottom) { + if (e->y0 != e->y1) { + stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata); + if (z != NULL) { + STBTT_assert(z->ey >= scan_y_top); + // insert at front + z->next = active; + active = z; + } + } + ++e; + } + + // now process all active edges + if (active) + stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top); + + { + float sum = 0; + for (i=0; i < result->w; ++i) { + float k; + int m; + sum += scanline2[i]; + k = scanline[i] + sum; + k = (float) STBTT_fabs(k)*255 + 0.5f; + m = (int) k; + if (m > 255) m = 255; + result->pixels[j*result->stride + i] = (unsigned char) m; + } + } + // advance all the edges + step = &active; + while (*step) { + stbtt__active_edge *z = *step; + z->fx += z->fdx; // advance to position for current scanline + step = &((*step)->next); // advance through list + } + + ++y; + ++j; + } + + stbtt__hheap_cleanup(&hh, userdata); + + if (scanline != scanline_data) + STBTT_free(scanline, userdata); +} +#else +#error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + +#define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0) + +static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n) +{ + int i,j; + for (i=1; i < n; ++i) { + stbtt__edge t = p[i], *a = &t; + j = i; + while (j > 0) { + stbtt__edge *b = &p[j-1]; + int c = STBTT__COMPARE(a,b); + if (!c) break; + p[j] = p[j-1]; + --j; + } + if (i != j) + p[j] = t; + } +} + +static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n) +{ + /* threshhold for transitioning to insertion sort */ + while (n > 12) { + stbtt__edge t; + int c01,c12,c,m,i,j; + + /* compute median of three */ + m = n >> 1; + c01 = STBTT__COMPARE(&p[0],&p[m]); + c12 = STBTT__COMPARE(&p[m],&p[n-1]); + /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ + if (c01 != c12) { + /* otherwise, we'll need to swap something else to middle */ + int z; + c = STBTT__COMPARE(&p[0],&p[n-1]); + /* 0>mid && midn => n; 0 0 */ + /* 0n: 0>n => 0; 0 n */ + z = (c == c12) ? 0 : n-1; + t = p[z]; + p[z] = p[m]; + p[m] = t; + } + /* now p[m] is the median-of-three */ + /* swap it to the beginning so it won't move around */ + t = p[0]; + p[0] = p[m]; + p[m] = t; + + /* partition loop */ + i=1; + j=n-1; + for(;;) { + /* handling of equality is crucial here */ + /* for sentinels & efficiency with duplicates */ + for (;;++i) { + if (!STBTT__COMPARE(&p[i], &p[0])) break; + } + for (;;--j) { + if (!STBTT__COMPARE(&p[0], &p[j])) break; + } + /* make sure we haven't crossed */ + if (i >= j) break; + t = p[i]; + p[i] = p[j]; + p[j] = t; + + ++i; + --j; + } + /* recurse on smaller side, iterate on larger */ + if (j < (n-i)) { + stbtt__sort_edges_quicksort(p,j); + p = p+i; + n = n-i; + } else { + stbtt__sort_edges_quicksort(p+i, n-i); + n = j; + } + } +} + +static void stbtt__sort_edges(stbtt__edge *p, int n) +{ + stbtt__sort_edges_quicksort(p, n); + stbtt__sort_edges_ins_sort(p, n); } typedef struct @@ -1752,7 +2262,13 @@ static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcou float y_scale_inv = invert ? -scale_y : scale_y; stbtt__edge *e; int n,i,j,k,m; +#if STBTT_RASTERIZER_VERSION == 1 int vsubsample = result->h < 8 ? 15 : 5; +#elif STBTT_RASTERIZER_VERSION == 2 + int vsubsample = 1; +#else + #error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif // vsubsample should divide 255 evenly; otherwise we won't reach full opacity // now we have to blow out the windings into explicit edge lists @@ -1789,7 +2305,8 @@ static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcou } // now sort the edges by their highest point (should snap to integer, and then by x) - STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare); + //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare); + stbtt__sort_edges(e, n); // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata); @@ -1921,7 +2438,10 @@ STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info if (scale_x == 0) scale_x = scale_y; if (scale_y == 0) { - if (scale_x == 0) return NULL; + if (scale_x == 0) { + STBTT_free(vertices, info->userdata); + return NULL; + } scale_y = scale_x; } @@ -2013,6 +2533,7 @@ STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // fo float scale; int x,y,bottom_y, i; stbtt_fontinfo f; + f.userdata = NULL; if (!stbtt_InitFont(&f, data, offset)) return -1; STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels @@ -2054,8 +2575,8 @@ STBTT_DEF void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, int float d3d_bias = opengl_fillrule ? 0 : -0.5f; float ipw = 1.0f / pw, iph = 1.0f / ph; stbtt_bakedchar *b = chardata + char_index; - int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5); - int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5); + int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f); + int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f); q->x0 = round_x + d3d_bias; q->y0 = round_y + d3d_bias; @@ -2206,10 +2727,11 @@ static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_i unsigned char buffer[STBTT_MAX_OVERSAMPLE]; int safe_w = w - kernel_width; int j; + STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze for (j=0; j < h; ++j) { int i; unsigned int total; - memset(buffer, 0, kernel_width); + STBTT_memset(buffer, 0, kernel_width); total = 0; @@ -2236,6 +2758,13 @@ static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_i pixels[i] = (unsigned char) (total / 4); } break; + case 5: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 5); + } + break; default: for (i=0; i <= safe_w; ++i) { total += pixels[i] - buffer[i & STBTT__OVER_MASK]; @@ -2260,10 +2789,11 @@ static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_i unsigned char buffer[STBTT_MAX_OVERSAMPLE]; int safe_h = h - kernel_width; int j; + STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze for (j=0; j < w; ++j) { int i; unsigned int total; - memset(buffer, 0, kernel_width); + STBTT_memset(buffer, 0, kernel_width); total = 0; @@ -2290,6 +2820,13 @@ static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_i pixels[i*stride_in_bytes] = (unsigned char) (total / 4); } break; + case 5: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 5); + } + break; default: for (i=0; i <= safe_h; ++i) { total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; @@ -2330,21 +2867,20 @@ STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, stbtt_fon for (i=0; i < num_ranges; ++i) { float fh = ranges[i].font_size; float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); - for (j=0; j < ranges[i].num_chars_in_range; ++j) { + ranges[i].h_oversample = (unsigned char) spc->h_oversample; + ranges[i].v_oversample = (unsigned char) spc->v_oversample; + for (j=0; j < ranges[i].num_chars; ++j) { int x0,y0,x1,y1; - int glyph = stbtt_FindGlyphIndex(info,ranges[i].first_unicode_char_in_range + j); - if (glyph) { - stbtt_GetGlyphBitmapBoxSubpixel(info,glyph, - scale * spc->h_oversample, - scale * spc->v_oversample, - 0,0, - &x0,&y0,&x1,&y1); - rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1); - rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1); - } else { - rects[k].w = rects[k].h = 1; - } - ++k; + int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + int glyph = stbtt_FindGlyphIndex(info, codepoint); + stbtt_GetGlyphBitmapBoxSubpixel(info,glyph, + scale * spc->h_oversample, + scale * spc->v_oversample, + 0,0, + &x0,&y0,&x1,&y1); + rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1); + rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1); + ++k; } } @@ -2354,22 +2890,30 @@ STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, stbtt_fon // rects array must be big enough to accommodate all characters in the given ranges STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) { - float recip_h = 1.0f / spc->h_oversample; - float recip_v = 1.0f / spc->v_oversample; - float sub_x = stbtt__oversample_shift(spc->h_oversample); - float sub_y = stbtt__oversample_shift(spc->v_oversample); int i,j,k, return_value = 1; + // save current values + int old_h_over = spc->h_oversample; + int old_v_over = spc->v_oversample; + k = 0; for (i=0; i < num_ranges; ++i) { float fh = ranges[i].font_size; float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); - for (j=0; j < ranges[i].num_chars_in_range; ++j) { + float recip_h,recip_v,sub_x,sub_y; + spc->h_oversample = ranges[i].h_oversample; + spc->v_oversample = ranges[i].v_oversample; + recip_h = 1.0f / spc->h_oversample; + recip_v = 1.0f / spc->v_oversample; + sub_x = stbtt__oversample_shift(spc->h_oversample); + sub_y = stbtt__oversample_shift(spc->v_oversample); + for (j=0; j < ranges[i].num_chars; ++j) { stbrp_rect *r = &rects[k]; if (r->was_packed) { stbtt_packedchar *bc = &ranges[i].chardata_for_range[j]; int advance, lsb, x0,y0,x1,y1; - int glyph = stbtt_FindGlyphIndex(info, ranges[i].first_unicode_char_in_range + j); + int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + int glyph = stbtt_FindGlyphIndex(info, codepoint); stbrp_coord pad = (stbrp_coord) spc->padding; // pad on left and top @@ -2419,19 +2963,28 @@ STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, stbtt } } + // restore original values + spc->h_oversample = old_h_over; + spc->v_oversample = old_v_over; + return return_value; } +STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects) +{ + stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects); +} + STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges) { stbtt_fontinfo info; int i,j,n, return_value = 1; - stbrp_context *context = (stbrp_context *) spc->pack_info; + //stbrp_context *context = (stbrp_context *) spc->pack_info; stbrp_rect *rects; // flag all characters as NOT packed for (i=0; i < num_ranges; ++i) - for (j=0; j < ranges[i].num_chars_in_range; ++j) + for (j=0; j < ranges[i].num_chars; ++j) ranges[i].chardata_for_range[j].x0 = ranges[i].chardata_for_range[j].y0 = ranges[i].chardata_for_range[j].x1 = @@ -2439,29 +2992,32 @@ STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, unsigned char *fontd n = 0; for (i=0; i < num_ranges; ++i) - n += ranges[i].num_chars_in_range; + n += ranges[i].num_chars; rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context); if (rects == NULL) return 0; + info.userdata = spc->user_allocator_context; stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index)); n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects); - stbrp_pack_rects(context, rects, n); + stbtt_PackFontRangesPackRects(spc, rects, n); return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects); + STBTT_free(rects, spc->user_allocator_context); return return_value; } STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, float font_size, - int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range) + int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range) { stbtt_pack_range range; - range.first_unicode_char_in_range = first_unicode_char_in_range; - range.num_chars_in_range = num_chars_in_range; + range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range; + range.array_of_unicode_codepoints = NULL; + range.num_chars = num_chars_in_range; range.chardata_for_range = chardata_for_range; range.font_size = font_size; return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1); @@ -2473,8 +3029,8 @@ STBTT_DEF void stbtt_GetPackedQuad(stbtt_packedchar *chardata, int pw, int ph, i stbtt_packedchar *b = chardata + char_index; if (align_to_integer) { - float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5); - float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5); + float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f); + float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f); q->x0 = x; q->y0 = y; q->x1 = x + b->xoff2 - b->xoff; @@ -2656,3 +3212,52 @@ STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *font_collection, const } #endif // STB_TRUETYPE_IMPLEMENTATION + + +// FULL VERSION HISTORY +// +// 1.10 (2016-04-02) allow user-defined fabs() replacement +// fix memory leak if fontsize=0.0 +// fix warning from duplicate typedef +// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges +// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges +// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; +// allow PackFontRanges to pack and render in separate phases; +// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); +// fixed an assert() bug in the new rasterizer +// replace assert() with STBTT_assert() in new rasterizer +// 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine) +// also more precise AA rasterizer, except if shapes overlap +// remove need for STBTT_sort +// 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC +// 1.04 (2015-04-15) typo in example +// 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes +// 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++ +// 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match +// non-oversampled; STBTT_POINT_SIZE for packed case only +// 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling +// 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg) +// 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID +// 0.8b (2014-07-07) fix a warning +// 0.8 (2014-05-25) fix a few more warnings +// 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back +// 0.6c (2012-07-24) improve documentation +// 0.6b (2012-07-20) fix a few more warnings +// 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels, +// stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty +// 0.5 (2011-12-09) bugfixes: +// subpixel glyph renderer computed wrong bounding box +// first vertex of shape can be off-curve (FreeSans) +// 0.4b (2011-12-03) fixed an error in the font baking example +// 0.4 (2011-12-01) kerning, subpixel rendering (tor) +// bugfixes for: +// codepoint-to-glyph conversion using table fmt=12 +// codepoint-to-glyph conversion using table fmt=4 +// stbtt_GetBakedQuad with non-square texture (Zer) +// updated Hello World! sample to use kerning and subpixel +// fixed some warnings +// 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM) +// userdata, malloc-from-userdata, non-zero fill (stb) +// 0.2 (2009-03-11) Fix unsigned/signed char warnings +// 0.1 (2009-03-09) First public release +// diff --git a/modules/onscreengui/include/gui.h b/modules/onscreengui/include/gui.h index 673e7dbb31..dcbffff069 100644 --- a/modules/onscreengui/include/gui.h +++ b/modules/onscreengui/include/gui.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __GUI_H__ -#define __GUI_H__ +#ifndef __OPENSPACE_MODULE_ONSCREENGUI___GUI___H__ +#define __OPENSPACE_MODULE_ONSCREENGUI___GUI___H__ #include #include @@ -33,6 +33,7 @@ #include #include #include +#include #include #include @@ -56,13 +57,12 @@ public: bool keyCallback(Key key, KeyModifier modifier, KeyAction action); bool charCallback(unsigned int character, KeyModifier modifier); - void startFrame(float deltaTime, const glm::vec2& windowSize, const glm::vec2& mousePosCorrectionFactor, const glm::vec2& mousePos, uint32_t mouseButtons); + void startFrame(float deltaTime, const glm::vec2& windowSize, + const glm::vec2& dpiScaling, const glm::vec2& mousePos, uint32_t mouseButtons); void endFrame(); void render(); - static openspace::scripting::LuaLibrary luaLibrary(); - //protected: GuiHelpComponent _help; GuiOriginComponent _origin; @@ -72,9 +72,15 @@ public: GuiPropertyComponent _screenSpaceProperty; GuiTimeComponent _time; GuiIswaComponent _iswa; + +private: + void renderAndUpdatePropertyVisibility(); + + properties::Property::Visibility _currentVisibility; + }; } // namespace gui } // namespace openspace -#endif // __GUI_H__ +#endif // __OPENSPACE_MODULE_ONSCREENGUI___GUI___H__ diff --git a/modules/onscreengui/include/guicomponent.h b/modules/onscreengui/include/guicomponent.h index d59830b14e..7aed19c3d6 100644 --- a/modules/onscreengui/include/guicomponent.h +++ b/modules/onscreengui/include/guicomponent.h @@ -22,8 +22,11 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __GUICOMPONENT_H__ -#define __GUICOMPONENT_H__ +#ifndef __OPENSPACE_MODULE_ONSCREENGUI___GUICOMPONENT___H__ +#define __OPENSPACE_MODULE_ONSCREENGUI___GUICOMPONENT___H__ + +#include +#include namespace openspace { namespace gui { @@ -33,9 +36,10 @@ class GUI; /** * The base class for a GUI component that can be rendered to the screen. */ -class GuiComponent { +class GuiComponent : public properties::PropertyOwner { public: - friend class GUI; + /// Constructor that initializes this components member variables + GuiComponent(std::string name); /** * Returns if this component is enabled, that is, if it is currently active and @@ -68,10 +72,10 @@ public: protected: /// true if this component is enabled and visible on the screen - bool _isEnabled = false; + properties::BoolProperty _isEnabled; }; } // namespace gui } // namespace openspace -#endif // __GUICOMPONENT_H__ +#endif // __OPENSPACE_MODULE_ONSCREENGUI___GUICOMPONENT___H__ diff --git a/modules/onscreengui/include/guihelpcomponent.h b/modules/onscreengui/include/guihelpcomponent.h index 8f6e82e2c0..3f046405e6 100644 --- a/modules/onscreengui/include/guihelpcomponent.h +++ b/modules/onscreengui/include/guihelpcomponent.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __GUIHELPCOMPONENT_H__ -#define __GUIHELPCOMPONENT_H__ +#ifndef __OPENSPACE_MODULE_ONSCREENGUI___GUIHELPCOMPONENT___H__ +#define __OPENSPACE_MODULE_ONSCREENGUI___GUIHELPCOMPONENT___H__ #include @@ -32,10 +32,12 @@ namespace gui { class GuiHelpComponent : public GuiComponent { public: + GuiHelpComponent(); + void render() override; }; } // namespace gui } // namespace openspace -#endif // __GUIHELPCOMPONENT_H__ +#endif // __OPENSPACE_MODULE_ONSCREENGUI___GUIHELPCOMPONENT___H__ diff --git a/modules/onscreengui/include/guiiswacomponent.h b/modules/onscreengui/include/guiiswacomponent.h index a6d831f788..6f27fbf6de 100644 --- a/modules/onscreengui/include/guiiswacomponent.h +++ b/modules/onscreengui/include/guiiswacomponent.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __GUIISWACOMPONENT_H__ -#define __GUIISWACOMPONENT_H__ +#ifndef __OPENSPACE_MODULE_ONSCREENGUI___GUIISWACOMPONENT___H__ +#define __OPENSPACE_MODULE_ONSCREENGUI___GUIISWACOMPONENT___H__ #include @@ -49,4 +49,4 @@ private: } // namespace gui } // namespace openspace -#endif // __GUIISWACOMPONENT_H__ +#endif // __OPENSPACE_MODULE_ONSCREENGUI___GUIISWACOMPONENT___H__ diff --git a/modules/onscreengui/include/guiorigincomponent.h b/modules/onscreengui/include/guiorigincomponent.h index 8598b784e4..79ec27f278 100644 --- a/modules/onscreengui/include/guiorigincomponent.h +++ b/modules/onscreengui/include/guiorigincomponent.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __GUIORIGINCOMPONENT_H__ -#define __GUIORIGINCOMPONENT_H__ +#ifndef __OPENSPACE_MODULE_ONSCREENGUI___GUIORIGINCOMPONENT___H__ +#define __OPENSPACE_MODULE_ONSCREENGUI___GUIORIGINCOMPONENT___H__ #include @@ -32,10 +32,12 @@ namespace gui { class GuiOriginComponent : public GuiComponent { public: + GuiOriginComponent(); + void render() override; }; } // namespace gui } // namespace openspace -#endif // __GUIORIGINCOMPONENT_H__ +#endif // __OPENSPACE_MODULE_ONSCREENGUI___GUIORIGINCOMPONENT___H__ diff --git a/modules/onscreengui/include/guiperformancecomponent.h b/modules/onscreengui/include/guiperformancecomponent.h index f5beabd38a..241613c614 100644 --- a/modules/onscreengui/include/guiperformancecomponent.h +++ b/modules/onscreengui/include/guiperformancecomponent.h @@ -22,11 +22,16 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __GUIPERFORMANCECOMPONENT_H__ -#define __GUIPERFORMANCECOMPONENT_H__ +#ifndef __OPENSPACE_MODULE_ONSCREENGUI___GUIPERFORMANCECOMPONENT___H__ +#define __OPENSPACE_MODULE_ONSCREENGUI___GUIPERFORMANCECOMPONENT___H__ #include +#include +#include + +#include + #include namespace ghoul { @@ -38,17 +43,20 @@ namespace gui { class GuiPerformanceComponent : public GuiComponent { public: + GuiPerformanceComponent(); + void render() override; protected: std::unique_ptr _performanceMemory; - int _sortingSelection = -1; - - bool _sceneGraphIsEnabled = false; - bool _functionsIsEnabled = false; + + properties::IntProperty _sortingSelection; + + properties::BoolProperty _sceneGraphIsEnabled; + properties::BoolProperty _functionsIsEnabled; }; } // namespace gui } // namespace openspace -#endif // __GUIPERFORMANCECOMPONENT_H__ +#endif // __OPENSPACE_MODULE_ONSCREENGUI___GUIPERFORMANCECOMPONENT___H__ diff --git a/modules/onscreengui/include/guipropertycomponent.h b/modules/onscreengui/include/guipropertycomponent.h index 2be19af00a..a97fe0e154 100644 --- a/modules/onscreengui/include/guipropertycomponent.h +++ b/modules/onscreengui/include/guipropertycomponent.h @@ -22,11 +22,13 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __GUIPROPERTYCOMPONENT_H__ -#define __GUIPROPERTYCOMPONENT_H__ +#ifndef __OPENSPACE_MODULE_ONSCREENGUI___GUIPROPERTYCOMPONENT___H__ +#define __OPENSPACE_MODULE_ONSCREENGUI___GUIPROPERTYCOMPONENT___H__ #include +#include + #include #include #include @@ -50,17 +52,20 @@ public: // component should render void setSource(SourceFunction func); + void setVisibility(properties::Property::Visibility visibility); + void render(); protected: void renderPropertyOwner(properties::PropertyOwner* owner); void renderProperty(properties::Property* prop, properties::PropertyOwner* owner); - std::string _name; + properties::Property::Visibility _visibility; + SourceFunction _function; }; } // namespace gui } // namespace openspace -#endif // __GUIPROPERTYCOMPONENT_H__ +#endif // __OPENSPACE_MODULE_ONSCREENGUI___GUIPROPERTYCOMPONENT___H__ diff --git a/modules/onscreengui/include/guitimecomponent.h b/modules/onscreengui/include/guitimecomponent.h index dcdb9f78ab..4598eee0d1 100644 --- a/modules/onscreengui/include/guitimecomponent.h +++ b/modules/onscreengui/include/guitimecomponent.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __GUITIMECOMPONENT_H__ -#define __GUITIMECOMPONENT_H__ +#ifndef __OPENSPACE_MODULE_ONSCREENGUI___GUITIMECOMPONENT___H__ +#define __OPENSPACE_MODULE_ONSCREENGUI___GUITIMECOMPONENT___H__ #include @@ -32,10 +32,12 @@ namespace gui { class GuiTimeComponent : public GuiComponent { public: + GuiTimeComponent(); + void render() override; }; } // namespace gui } // namespace openspace -#endif // __GUITIMECOMPONENT_H__ +#endif // __OPENSPACE_MODULE_ONSCREENGUI___GUITIMECOMPONENT___H__ diff --git a/modules/onscreengui/include/renderproperties.h b/modules/onscreengui/include/renderproperties.h index 29433f3bba..acbf461a8f 100644 --- a/modules/onscreengui/include/renderproperties.h +++ b/modules/onscreengui/include/renderproperties.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERPROPERTIES_H__ -#define __RENDERPROPERTIES_H__ +#ifndef __OPENSPACE_MODULE_ONSCREENGUI___RENDERPROPERTIES___H__ +#define __OPENSPACE_MODULE_ONSCREENGUI___RENDERPROPERTIES___H__ #include @@ -38,6 +38,7 @@ void renderBoolProperty(properties::Property* prop, const std::string& ownerName void renderOptionProperty(properties::Property* prop, const std::string& ownerName); void renderSelectionProperty(properties::Property* prop, const std::string& ownerName); void renderStringProperty(properties::Property* prop, const std::string& ownerName); +void renderDoubleProperty(properties::Property* prop, const std::string& ownerName); void renderIntProperty(properties::Property* prop, const std::string& ownerName); void renderIVec2Property(properties::Property* prop, const std::string& ownerName); void renderIVec3Property(properties::Property* prop, const std::string& ownerName); @@ -46,8 +47,11 @@ void renderFloatProperty(properties::Property* prop, const std::string& ownerNam void renderVec2Property(properties::Property* prop, const std::string& ownerName); void renderVec3Property(properties::Property* prop, const std::string& ownerName); void renderVec4Property(properties::Property* prop, const std::string& ownerName); +void renderDVec2Property(properties::Property* prop, const std::string& ownerName); +void renderDVec3Property(properties::Property* prop, const std::string& ownerName); +void renderDVec4Property(properties::Property* prop, const std::string& ownerName); void renderTriggerProperty(properties::Property* prop, const std::string& ownerName); } // namespace openspace -#endif __RENDERPROPERTIES_H__ +#endif __OPENSPACE_MODULE_ONSCREENGUI___RENDERPROPERTIES___H__ diff --git a/modules/onscreengui/onscreenguimodule.cpp b/modules/onscreengui/onscreenguimodule.cpp index 472d26c947..118beeb259 100644 --- a/modules/onscreengui/onscreenguimodule.cpp +++ b/modules/onscreengui/onscreenguimodule.cpp @@ -24,10 +24,16 @@ #include +#include + +#include + namespace openspace { OnScreenGUIModule::OnScreenGUIModule() : OpenSpaceModule("OnScreenGUI") -{} +{ + addPropertySubOwner(OsEng.gui()); +} } // namespace openspace diff --git a/modules/onscreengui/onscreenguimodule.h b/modules/onscreengui/onscreenguimodule.h index 224cc980e0..ca6c59c18e 100644 --- a/modules/onscreengui/onscreenguimodule.h +++ b/modules/onscreengui/onscreenguimodule.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __ONSCREENGUIMODULE_H__ -#define __ONSCREENGUIMODULE_H__ +#ifndef __OPENSPACE_MODULE_ONSCREENGUI___ONSCREENGUIMODULE___H__ +#define __OPENSPACE_MODULE_ONSCREENGUI___ONSCREENGUIMODULE___H__ #include @@ -36,4 +36,4 @@ public: } // namespace openspace -#endif // __ONSCREENGUIMODULE_H__ +#endif // __OPENSPACE_MODULE_ONSCREENGUI___ONSCREENGUIMODULE___H__ diff --git a/modules/onscreengui/shaders/gui_fs.glsl b/modules/onscreengui/shaders/gui_fs.glsl index df3ab9bbef..6201873727 100644 --- a/modules/onscreengui/shaders/gui_fs.glsl +++ b/modules/onscreengui/shaders/gui_fs.glsl @@ -33,4 +33,4 @@ out vec4 FragColor; void main() { FragColor = out_color * texture(tex, out_uv); -} \ No newline at end of file +} diff --git a/modules/onscreengui/src/gui.cpp b/modules/onscreengui/src/gui.cpp index 2057c64a38..d0802a4a9d 100644 --- a/modules/onscreengui/src/gui.cpp +++ b/modules/onscreengui/src/gui.cpp @@ -44,8 +44,8 @@ namespace { const std::string _loggerCat = "GUI"; -const std::string configurationFile = "imgui.ini"; -const std::string GuiFont = "${FONTS}/Roboto/Roboto-Regular.ttf"; +const char* configurationFile = "imgui.ini"; +const char* GuiFont = "${FONTS}/Roboto/Roboto-Regular.ttf"; const ImVec2 size = ImVec2(350, 500); //GLuint fontTex = 0; @@ -53,13 +53,20 @@ const ImVec2 size = ImVec2(350, 500); size_t vboMaxSize = 0; GLuint vao = 0; GLuint vbo = 0; +GLuint vboElements = 0; std::unique_ptr _program; std::unique_ptr _fontTexture; char* iniFileBuffer = nullptr; -static void RenderDrawLists(ImDrawList** const commandLists, int nCommandLists) { - if (nCommandLists == 0) +static void RenderDrawLists(ImDrawData* drawData) { + // Avoid rendering when minimized, scale coordinates for retina displays + // (screen coordinates != framebuffer coordinates) + ImGuiIO& io = ImGui::GetIO(); + int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x); + int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y); + if (fb_width == 0 || fb_height == 0) return; + drawData->ScaleClipRects(io.DisplayFramebufferScale); // Setup render state: // alpha-blending enabled, no face culling, no depth testing, scissor enabled @@ -77,6 +84,7 @@ static void RenderDrawLists(ImDrawList** const commandLists, int nCommandLists) // Setup orthographic projection matrix const float width = ImGui::GetIO().DisplaySize.x; const float height = ImGui::GetIO().DisplaySize.y; + glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); const glm::mat4 ortho( 2.f / width, 0.0f, 0.0f, 0.f, 0.0f, 2.0f / -height, 0.0f, 0.f, @@ -88,59 +96,105 @@ static void RenderDrawLists(ImDrawList** const commandLists, int nCommandLists) _program->setUniform("tex", unit); _program->setUniform("ortho", ortho); - // Grow our buffer according to what we need - size_t totalVertexCount = 0; - for (int i = 0; i < nCommandLists; ++i) - totalVertexCount += commandLists[i]->vtx_buffer.size(); - - glBindBuffer(GL_ARRAY_BUFFER, vbo); - size_t neededBufferSize = totalVertexCount * sizeof(ImDrawVert); - if (neededBufferSize > vboMaxSize) { - // Grow buffer - vboMaxSize = neededBufferSize * 1.25f; - glBufferData(GL_ARRAY_BUFFER, vboMaxSize, NULL, GL_STREAM_DRAW); - } - - // Copy and convert all vertices into a single contiguous buffer - unsigned char* bufferData = reinterpret_cast( - glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY) - ); - - if (!bufferData) { - LFATAL("Error mapping ImGui buffer"); - return; - } - - for (int i = 0; i < nCommandLists; ++i) { - const ImDrawList* cmd_list = commandLists[i]; - memcpy( - bufferData, - &cmd_list->vtx_buffer[0], - cmd_list->vtx_buffer.size() * sizeof(ImDrawVert) - ); - bufferData += (cmd_list->vtx_buffer.size() * sizeof(ImDrawVert)); - } - glUnmapBuffer(GL_ARRAY_BUFFER); - glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(vao); - int cmdOffset = 0; - for (int i = 0; i < nCommandLists; ++i) { - const ImDrawList* cmd_list = commandLists[i]; - int vtxOffset = cmdOffset; - for (const auto& pcmd : cmd_list->commands) { - glScissor( - static_cast(pcmd.clip_rect.x), - static_cast(height - pcmd.clip_rect.w), - static_cast(pcmd.clip_rect.z - pcmd.clip_rect.x), - static_cast(pcmd.clip_rect.w - pcmd.clip_rect.y) - ); - glDrawArrays(GL_TRIANGLES, vtxOffset, pcmd.vtx_count); - vtxOffset += pcmd.vtx_count; + for (int i = 0; i < drawData->CmdListsCount; ++i) { + const ImDrawList* cmdList = drawData->CmdLists[i]; + const ImDrawIdx* indexBufferOffset = 0; + + glBindBuffer(GL_ARRAY_BUFFER, vbo); + glBufferData( + GL_ARRAY_BUFFER, + (GLsizeiptr)cmdList->VtxBuffer.size() * sizeof(ImDrawVert), + (GLvoid*)&cmdList->VtxBuffer.front(), + GL_STREAM_DRAW + ); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboElements); + glBufferData( + GL_ELEMENT_ARRAY_BUFFER, + (GLsizeiptr)cmdList->IdxBuffer.size() * sizeof(ImDrawIdx), + (GLvoid*)&cmdList->IdxBuffer.front(), + GL_STREAM_DRAW + ); + + for (const ImDrawCmd* pcmd = cmdList->CmdBuffer.begin(); pcmd != cmdList->CmdBuffer.end(); pcmd++) { + if (pcmd->UserCallback) { + pcmd->UserCallback(cmdList, pcmd); + } + else { + glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); + glScissor( + (int)pcmd->ClipRect.x, + (int)(fb_height - pcmd->ClipRect.w), + (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), + (int)(pcmd->ClipRect.w - pcmd->ClipRect.y) + ); + glDrawElements( + GL_TRIANGLES, + (GLsizei)pcmd->ElemCount, + sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, + indexBufferOffset + ); + } + indexBufferOffset += pcmd->ElemCount; } - cmdOffset = vtxOffset; } + + //// Grow our buffer according to what we need + //size_t totalVertexCount = 0; + //for (int i = 0; i < nCommandLists; ++i) + // totalVertexCount += commandLists[i]->vtx_buffer.size(); + + //glBindBuffer(GL_ARRAY_BUFFER, vbo); + //size_t neededBufferSize = totalVertexCount * sizeof(ImDrawVert); + //if (neededBufferSize > vboMaxSize) { + // // Grow buffer + // vboMaxSize = neededBufferSize * 1.25f; + // glBufferData(GL_ARRAY_BUFFER, vboMaxSize, NULL, GL_STREAM_DRAW); + //} + + //// Copy and convert all vertices into a single contiguous buffer + //unsigned char* bufferData = reinterpret_cast( + // glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY) + // ); + + //if (!bufferData) { + // LFATAL("Error mapping ImGui buffer"); + // return; + //} + + //for (int i = 0; i < nCommandLists; ++i) { + // const ImDrawList* cmd_list = commandLists[i]; + // memcpy( + // bufferData, + // &cmd_list->vtx_buffer[0], + // cmd_list->vtx_buffer.size() * sizeof(ImDrawVert) + // ); + // bufferData += (cmd_list->vtx_buffer.size() * sizeof(ImDrawVert)); + //} + //glUnmapBuffer(GL_ARRAY_BUFFER); + //glBindBuffer(GL_ARRAY_BUFFER, 0); + //glBindVertexArray(vao); + + //int cmdOffset = 0; + //for (int i = 0; i < nCommandLists; ++i) { + // const ImDrawList* cmd_list = commandLists[i]; + // int vtxOffset = cmdOffset; + // for (const auto& pcmd : cmd_list->commands) { + // glScissor( + // static_cast(pcmd.clip_rect.x), + // static_cast(height - pcmd.clip_rect.w), + // static_cast(pcmd.clip_rect.z - pcmd.clip_rect.x), + // static_cast(pcmd.clip_rect.w - pcmd.clip_rect.y) + // ); + // glDrawArrays(GL_TRIANGLES, vtxOffset, pcmd.vtx_count); + // vtxOffset += pcmd.vtx_count; + // } + // cmdOffset = vtxOffset; + //} + glBindVertexArray(0); _program->deactivate(); glDisable(GL_SCISSOR_TEST); @@ -152,10 +206,14 @@ void addScreenSpaceRenderable(std::string texturePath) { LWARNING("Could not find image '" << texturePath << "'"); return; } + + texturePath = absPath(texturePath); + texturePath = FileSys.convertPathSeparator(texturePath, '/'); + std::string luaTable = - "{Type = 'ScreenSpaceImage', TexturePath = '" + absPath(texturePath) + "' }"; + "{Type = 'ScreenSpaceImage', TexturePath = '" + texturePath + "' }"; std::string script = "openspace.registerScreenSpaceRenderable(" + luaTable + ");"; - OsEng.scriptEngine().queueScript(script); + OsEng.scriptEngine().queueScript(script, openspace::scripting::ScriptEngine::RemoteScripting::Yes); } } // namespace @@ -163,11 +221,21 @@ namespace openspace { namespace gui { GUI::GUI() - : GuiComponent() + : GuiComponent("Main") , _globalProperty("Global") , _property("Properties") , _screenSpaceProperty("ScreenSpace Properties") -{} + , _currentVisibility(properties::Property::Visibility::All) +{ + addPropertySubOwner(_help); + addPropertySubOwner(_origin); + addPropertySubOwner(_performance); + addPropertySubOwner(_globalProperty); + addPropertySubOwner(_property); + addPropertySubOwner(_screenSpaceProperty); + addPropertySubOwner(_time); + addPropertySubOwner(_iswa); +} GUI::~GUI() { ImGui::Shutdown(); @@ -218,7 +286,7 @@ void GUI::initialize() { style.WindowRounding = 0.f; style.FramePadding = { 3.f, 3.f }; style.FrameRounding = 0.f; - style.ScrollbarWidth = 15.f; + style.ScrollbarSize = 15.f; style.ScrollbarRounding = 0.f; style.IndentSpacing = 25; style.ItemSpacing = { 4.f, 2.f }; @@ -270,8 +338,9 @@ void GUI::initializeGL() { "${MODULE_ONSCREENGUI}/shaders/gui_vs.glsl", "${MODULE_ONSCREENGUI}/shaders/gui_fs.glsl" ); - if (!_program) + if (!_program) { return; + } unsigned char* pngData; glm::ivec2 textureSize; @@ -284,11 +353,15 @@ void GUI::initializeGL() { _fontTexture->setName("Gui Text"); _fontTexture->setDataOwnership(ghoul::opengl::Texture::TakeOwnership::No); _fontTexture->uploadTexture(); + GLuint id = *_fontTexture; + ImGui::GetIO().Fonts->TexID = (void*)(intptr_t)id; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, vboMaxSize, NULL, GL_DYNAMIC_DRAW); + glGenBuffers(1, &vboElements); + glGenVertexArrays(1, &vao); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); @@ -337,6 +410,7 @@ void GUI::deinitializeGL() { glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vbo); + glDeleteBuffers(1, &vboElements); _iswa.deinitializeGL(); _help.deinitializeGL(); @@ -347,18 +421,15 @@ void GUI::deinitializeGL() { } void GUI::startFrame(float deltaTime, const glm::vec2& windowSize, - const glm::vec2& mousePosCorrectionFactor, - const glm::vec2& mousePos, + const glm::vec2& dpiScaling, const glm::vec2& mousePos, uint32_t mouseButtonsPressed) { ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2(windowSize.x, windowSize.y); + io.DisplayFramebufferScale = ImVec2(dpiScaling.x, dpiScaling.y); io.DeltaTime = deltaTime; - io.MousePos = ImVec2( - mousePos.x * mousePosCorrectionFactor.x, - mousePos.y * mousePosCorrectionFactor.y - ); + io.MousePos = ImVec2(mousePos.x, mousePos.y); io.MouseDown[0] = mouseButtonsPressed & (1 << 0); io.MouseDown[1] = mouseButtonsPressed & (1 << 1); @@ -367,20 +438,34 @@ void GUI::startFrame(float deltaTime, const glm::vec2& windowSize, } void GUI::endFrame() { - render(); + if (_program->isDirty()) { + _program->rebuildFromFile(); + } - if (_globalProperty.isEnabled()) - _globalProperty.render(); - if (_property.isEnabled()) - _property.render(); - if (_screenSpaceProperty.isEnabled()) - _screenSpaceProperty.render(); - if (_performance.isEnabled()) + if (OsEng.renderEngine().doesPerformanceMeasurements()) { _performance.render(); - if (_help.isEnabled()) - _help.render(); - if (_iswa.isEnabled()) - _iswa.render(); + } + + if (_isEnabled) { + render(); + + if (_globalProperty.isEnabled()) { + _globalProperty.render(); + } + if (_property.isEnabled()) { + _property.render(); + } + if (_screenSpaceProperty.isEnabled()) { + _screenSpaceProperty.render(); + } + + if (_help.isEnabled()) { + _help.render(); + } + if (_iswa.isEnabled()) { + _iswa.render(); + } + } ImGui::Render(); } @@ -406,8 +491,9 @@ bool GUI::keyCallback(Key key, KeyModifier modifier, KeyAction action) { bool consumeEvent = io.WantCaptureKeyboard; if (consumeEvent) { int keyIndex = static_cast(key); - if (keyIndex < 0) + if (keyIndex < 0) { LERROR("Pressed key of index '" << keyIndex << "' was negative"); + } else { if (action == KeyAction::Press) io.KeysDown[keyIndex] = true; @@ -426,8 +512,9 @@ bool GUI::charCallback(unsigned int character, KeyModifier modifier) { ImGuiIO& io = ImGui::GetIO(); bool consumeEvent = io.WantCaptureKeyboard; - if (consumeEvent) - io.AddInputCharacter((unsigned short)character); + if (consumeEvent) { + io.AddInputCharacter(static_cast(character)); + } return consumeEvent; } @@ -435,50 +522,43 @@ bool GUI::charCallback(unsigned int character, KeyModifier modifier) { void GUI::render() { ImGui::Begin("OpenSpace GUI", nullptr); - ImGui::Checkbox("Scene Graph Properties", &_property._isEnabled); - ImGui::Checkbox("ScreenSpace Properties", &_screenSpaceProperty._isEnabled); - ImGui::Checkbox("Global Properties", &_globalProperty._isEnabled); + bool property = _property.isEnabled(); + ImGui::Checkbox("Scene Graph Properties", &property); + _property.setEnabled(property); + + bool screenSpaceProperty = _screenSpaceProperty.isEnabled(); + ImGui::Checkbox("ScreenSpace Properties", &screenSpaceProperty); + _screenSpaceProperty.setEnabled(screenSpaceProperty); + + bool globalProperty = _globalProperty.isEnabled(); + ImGui::Checkbox("Global Properties", &globalProperty); + _globalProperty.setEnabled(globalProperty); + #ifdef OPENSPACE_MODULE_ISWA_ENABLED - ImGui::Checkbox("iSWA", &_iswa._isEnabled); + bool iswa = _iswa.isEnabled(); + ImGui::Checkbox("iSWA", &iswa); + _iswa.setEnabled(iswa); #endif - ImGui::Checkbox("Performance", &_performance._isEnabled); + _origin.render(); _time.render(); - // These are temporary until the scalegraph is in effect ---abock - bool toSun = ImGui::Button("Coordinate System to Sun"); - bool toPluto = ImGui::Button("Coordinate System to Pluto"); - bool toJupiter = ImGui::Button("Coordinate System to Jupiter"); - bool to67P = ImGui::Button("Coordinate System to 67P"); + bool help = _help.isEnabled(); + ImGui::Checkbox("Help", &help); + _help.setEnabled(help); - if (toSun) { - OsEng.scriptEngine().queueScript( - "openspace.setPropertyValue('Interaction.coordinateSystem', 'Sun');" - ); - } - if (toPluto) { - OsEng.scriptEngine().queueScript( - "openspace.setPropertyValue('Interaction.coordinateSystem', 'Pluto');" - ); - } - if (toJupiter) { - OsEng.scriptEngine().queueScript( - "openspace.setPropertyValue('Interaction.coordinateSystem', 'Jupiter');" - ); - } - if (to67P) { - OsEng.scriptEngine().queueScript( - "openspace.setPropertyValue('Interaction.coordinateSystem', '67P');" - ); - } - - ImGui::Checkbox("Help", &_help._isEnabled); + renderAndUpdatePropertyVisibility(); static const int addImageBufferSize = 256; static char addImageBuffer[addImageBufferSize]; - ImGui::InputText("addImage", addImageBuffer, addImageBufferSize); - if (ImGui::SmallButton("Add Image")) { + bool addImage = ImGui::InputText( + "addImage", + addImageBuffer, + addImageBufferSize, + ImGuiInputTextFlags_EnterReturnsTrue + ); + if (addImage) { addScreenSpaceRenderable(std::string(addImageBuffer)); } @@ -499,31 +579,21 @@ void GUI::render() { ImGui::End(); } -scripting::LuaLibrary GUI::luaLibrary() { - return { - "gui", - { - { - "show", - &luascriptfunctions::gui::show, - "", - "Shows the console" - }, - { - "hide", - &luascriptfunctions::gui::hide, - "", - "Hides the console" - }, - { - "toggle", - &luascriptfunctions::gui::toggle, - "", - "Toggles the console" - } - } - }; +void GUI::renderAndUpdatePropertyVisibility() { + // Fragile! Keep this in sync with properties::Property::Visibility + using V = properties::Property::Visibility; + int t = static_cast>(_currentVisibility); + + // Array is sorted by importance + std::array items = { "None", "User", "Developer", "All"}; + ImGui::Combo("PropertyVisibility", &t, items.data(), items.size()); + + _currentVisibility = static_cast(t); + _globalProperty.setVisibility(_currentVisibility); + _property.setVisibility(_currentVisibility); + _screenSpaceProperty.setVisibility(_currentVisibility); } + } // namespace gui } // namespace openspace diff --git a/modules/onscreengui/src/gui_lua.inl b/modules/onscreengui/src/gui_lua.inl index d84ea0defd..49d4e02fc6 100644 --- a/modules/onscreengui/src/gui_lua.inl +++ b/modules/onscreengui/src/gui_lua.inl @@ -35,8 +35,9 @@ namespace gui { */ int show(lua_State* L) { int nArguments = lua_gettop(L); - if (nArguments != 0) + if (nArguments != 0) { return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments); + } OsEng.gui().setEnabled(true); return 0; @@ -49,8 +50,9 @@ int show(lua_State* L) { */ int hide(lua_State* L) { int nArguments = lua_gettop(L); - if (nArguments != 0) + if (nArguments != 0) { return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments); + } OsEng.gui().setEnabled(false); return 0; @@ -63,8 +65,9 @@ int hide(lua_State* L) { */ int toggle(lua_State* L) { int nArguments = lua_gettop(L); - if (nArguments != 0) + if (nArguments != 0) { return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments); + } OsEng.gui().setEnabled(!OsEng.gui().isEnabled()); return 0; diff --git a/modules/onscreengui/src/guicomponent.cpp b/modules/onscreengui/src/guicomponent.cpp index afd9b5ab6a..27373aadf7 100644 --- a/modules/onscreengui/src/guicomponent.cpp +++ b/modules/onscreengui/src/guicomponent.cpp @@ -27,6 +27,14 @@ namespace openspace { namespace gui { +GuiComponent::GuiComponent(std::string name) + : _isEnabled("enabled", "Is Enabled", false) +{ + setName(std::move(name)); + + addProperty(_isEnabled); +} + bool GuiComponent::isEnabled() const { return _isEnabled; } diff --git a/modules/onscreengui/src/guihelpcomponent.cpp b/modules/onscreengui/src/guihelpcomponent.cpp index c38e2ebe38..f7a7bf7aad 100644 --- a/modules/onscreengui/src/guihelpcomponent.cpp +++ b/modules/onscreengui/src/guihelpcomponent.cpp @@ -33,8 +33,14 @@ namespace { namespace openspace { namespace gui { +GuiHelpComponent::GuiHelpComponent() + : GuiComponent("Help") +{} + void GuiHelpComponent::render() { - ImGui::Begin("Help", &_isEnabled, size, 0.5f); + bool v = _isEnabled; + ImGui::Begin("Help", &v, size, 0.5f); + _isEnabled = v; ImGui::ShowUserGuide(); ImGui::End(); } diff --git a/modules/onscreengui/src/guiiswacomponent.cpp b/modules/onscreengui/src/guiiswacomponent.cpp index e09a294a85..61d5b4548d 100644 --- a/modules/onscreengui/src/guiiswacomponent.cpp +++ b/modules/onscreengui/src/guiiswacomponent.cpp @@ -58,7 +58,11 @@ void GuiIswaComponent::render() { bool oldGmImageValue = _gmImage; bool oldIonDataValue = _ionData; - ImGui::Begin("ISWA", &_isEnabled, size, 0.5f); + bool e = _isEnabled; + + ImGui::Begin("ISWA", &e, size, 0.5f); + + _isEnabled = e; ImGui::Text("Global Magnetosphere"); ImGui::Checkbox("Gm From Data", &_gmData); ImGui::SameLine(); @@ -74,7 +78,8 @@ void GuiIswaComponent::render() { if (ImGui::SmallButton("Add Cygnet")) { OsEng.scriptEngine().queueScript( - "openspace.iswa.addCygnet(" + std::string(addCygnetBuffer) + ");" + "openspace.iswa.addCygnet(" + std::string(addCygnetBuffer) + ");", + scripting::ScriptEngine::RemoteScripting::Yes ); } @@ -83,9 +88,15 @@ void GuiIswaComponent::render() { std::string x = "openspace.iswa.addCygnet(-4, 'Data', 'GMData');"; std::string y = "openspace.iswa.addCygnet(-5, 'Data', 'GMData');"; std::string z = "openspace.iswa.addCygnet(-6, 'Data', 'GMData');"; - OsEng.scriptEngine().queueScript(x + y + z); + OsEng.scriptEngine().queueScript( + x + y + z, + scripting::ScriptEngine::RemoteScripting::Yes + ); } else { - OsEng.scriptEngine().queueScript("openspace.iswa.removeGroup('GMData');"); + OsEng.scriptEngine().queueScript( + "openspace.iswa.removeGroup('GMData');", + scripting::ScriptEngine::RemoteScripting::Yes + ); } } @@ -94,19 +105,29 @@ void GuiIswaComponent::render() { std::string x = "openspace.iswa.addCygnet(-4, 'Texture', 'GMImage');"; std::string y = "openspace.iswa.addCygnet(-5, 'Texture', 'GMImage');"; std::string z = "openspace.iswa.addCygnet(-6, 'Texture', 'GMImage');"; - OsEng.scriptEngine().queueScript(x + y + z); + OsEng.scriptEngine().queueScript( + x + y + z, + scripting::ScriptEngine::RemoteScripting::Yes + ); } else { - OsEng.scriptEngine().queueScript("openspace.iswa.removeGroup('GMImage');"); + OsEng.scriptEngine().queueScript( + "openspace.iswa.removeGroup('GMImage');", + scripting::ScriptEngine::RemoteScripting::Yes + ); } } if(_ionData != oldIonDataValue) { if(_ionData) { OsEng.scriptEngine().queueScript( - "openspace.iswa.addCygnet(-10,'Data','Ionosphere');" + "openspace.iswa.addCygnet(-10,'Data','Ionosphere');", + scripting::ScriptEngine::RemoteScripting::Yes ); } else { - OsEng.scriptEngine().queueScript("openspace.iswa.removeGroup('Ionosphere');"); + OsEng.scriptEngine().queueScript( + "openspace.iswa.removeGroup('Ionosphere');", + scripting::ScriptEngine::RemoteScripting::Yes + ); } } @@ -147,13 +168,16 @@ void GuiIswaComponent::render() { groupName + "'," + std::to_string(cdfOption) + - ");" + ");", + scripting::ScriptEngine::RemoteScripting::Yes ); OsEng.scriptEngine().queueScript( - "openspace.time.setTime('" + date + "');" + "openspace.time.setTime('" + date + "');", + scripting::ScriptEngine::RemoteScripting::Yes ); OsEng.scriptEngine().queueScript( - "openspace.time.setDeltaTime(0);" + "openspace.time.setDeltaTime(0);", + scripting::ScriptEngine::RemoteScripting::Yes ); } } @@ -181,13 +205,15 @@ void GuiIswaComponent::render() { if (info->selected) { OsEng.scriptEngine().queueScript( "openspace.iswa.addScreenSpaceCygnet(" - "{CygnetId = " + std::to_string(id) + " });" + "{CygnetId = " + std::to_string(id) + " });", + scripting::ScriptEngine::RemoteScripting::Yes ); } else { OsEng.scriptEngine().queueScript( "openspace.iswa.removeScreenSpaceCygnet(" + std::to_string(id) + - ");" + ");", + scripting::ScriptEngine::RemoteScripting::Yes ); } } diff --git a/modules/onscreengui/src/guiorigincomponent.cpp b/modules/onscreengui/src/guiorigincomponent.cpp index 07bf244161..1e6efdd7aa 100644 --- a/modules/onscreengui/src/guiorigincomponent.cpp +++ b/modules/onscreengui/src/guiorigincomponent.cpp @@ -33,13 +33,13 @@ #include "imgui.h" -namespace { - const std::string _loggerCat = "GuiOriginComponent"; -} - namespace openspace { namespace gui { +GuiOriginComponent::GuiOriginComponent() + : GuiComponent("Origin") +{} + void GuiOriginComponent::render() { SceneGraphNode* currentFocus = OsEng.interactionHandler().focusNode(); @@ -54,8 +54,9 @@ void GuiOriginComponent::render() { } ); std::string nodeNames = ""; - for (SceneGraphNode* n : nodes) + for (SceneGraphNode* n : nodes) { nodeNames += n->name() + '\0'; + } auto iCurrentFocus = std::find(nodes.begin(), nodes.end(), currentFocus); ghoul_assert(iCurrentFocus != nodes.end(), "Focus node not found"); @@ -65,7 +66,8 @@ void GuiOriginComponent::render() { if (hasChanged) { OsEng.scriptEngine().queueScript( "openspace.setPropertyValue('Interaction.origin', '" + - nodes[currentPosition]->name() + "');" + nodes[currentPosition]->name() + "');", + scripting::ScriptEngine::RemoteScripting::Yes ); } } diff --git a/modules/onscreengui/src/guiperformancecomponent.cpp b/modules/onscreengui/src/guiperformancecomponent.cpp index 6e564a7122..d11430f056 100644 --- a/modules/onscreengui/src/guiperformancecomponent.cpp +++ b/modules/onscreengui/src/guiperformancecomponent.cpp @@ -42,294 +42,404 @@ namespace { enum class Sorting { NoSorting = -1, - UpdateEphemeris = 0, - UpdateRender = 1, - Render = 2, - Total = 3 + UpdateTranslation = 0, + UpdateRotation = 1, + UpdateScaling = 2, + UpdateRender = 3, + Render = 4, + Total = 5 }; } namespace openspace { namespace gui { +GuiPerformanceComponent::GuiPerformanceComponent() + : GuiComponent("PerformanceComponent") + , _sortingSelection("sortingSelection", "Sorting", -1, -1, 6) + , _sceneGraphIsEnabled("showSceneGraph", "Show Scene Graph Measurements", false) + , _functionsIsEnabled("showFunctions", "Show Function Measurements", false) +{ + addProperty(_sortingSelection); + + addProperty(_sceneGraphIsEnabled); + addProperty(_functionsIsEnabled); +} + void GuiPerformanceComponent::render() { using ghoul::SharedMemory; using namespace performance; - ImGui::Begin("Performance", &_isEnabled); - if (OsEng.renderEngine().doesPerformanceMeasurements()) { - PerformanceLayout* layout = OsEng.renderEngine().performanceManager()->performanceData(); + bool v = _isEnabled; + ImGui::Begin("Performance", &v); + _isEnabled = v; + PerformanceLayout* layout = OsEng.renderEngine().performanceManager()->performanceData(); - ImGui::Checkbox("SceneGraph", &_sceneGraphIsEnabled); - ImGui::Checkbox("Functions", &_functionsIsEnabled); + v = _sceneGraphIsEnabled; + ImGui::Checkbox("SceneGraph", &v); + _sceneGraphIsEnabled = v; + v = _functionsIsEnabled; + ImGui::Checkbox("Functions", &v); + _functionsIsEnabled = v; - ImGui::Spacing(); + ImGui::Spacing(); - if (ImGui::Button("Reset measurements")) { - OsEng.renderEngine().performanceManager()->resetPerformanceMeasurements(); + if (ImGui::Button("Reset measurements")) { + OsEng.renderEngine().performanceManager()->resetPerformanceMeasurements(); + } + + if (_sceneGraphIsEnabled) { + bool v = _sceneGraphIsEnabled; + ImGui::Begin("SceneGraph", &v); + _sceneGraphIsEnabled = v; + + // The indices correspond to the index into the average array further below + ImGui::Text("Sorting"); + int sorting = _sortingSelection; + ImGui::RadioButton( + "No Sorting", + &sorting, + static_cast(Sorting::NoSorting) + ); + ImGui::RadioButton( + "UpdateTranslation", + &sorting, + static_cast(Sorting::UpdateTranslation) + ); + ImGui::RadioButton( + "UpdateRotation", + &sorting, + static_cast(Sorting::UpdateRotation) + ); + ImGui::RadioButton( + "UpdateScaling", + &sorting, + static_cast(Sorting::UpdateScaling) + ); + ImGui::RadioButton( + "UpdateRender", + &sorting, + static_cast(Sorting::UpdateRender) + ); + ImGui::RadioButton( + "RenderTime", + &sorting, + static_cast(Sorting::Render) + ); + ImGui::RadioButton( + "TotalTime", + &sorting, + static_cast(Sorting::Total) + ); + _sortingSelection = sorting; + + // Later, we will sort this indices list instead of the real values for + // performance reasons + std::vector indices(layout->nScaleGraphEntries); + std::iota(indices.begin(), indices.end(), 0); + + // Ordering: + // updateTranslation + // updateRotation + // updateScaling + // UpdateRender + // RenderTime + std::vector> averages( + layout->nScaleGraphEntries, + { 0.f, 0.f, 0.f, 0.f, 0.f } + ); + + std::vector, 5>> minMax( + layout->nScaleGraphEntries + ); + + for (int i = 0; i < layout->nScaleGraphEntries; ++i) { + const PerformanceLayout::SceneGraphPerformanceLayout& entry = + layout->sceneGraphEntries[i]; + + int nValues[5] = { 0, 0, 0, 0, 0 }; + + // Compute the averages and count the number of values so we don't divide + // by 0 later + for (int j = 0; j < PerformanceLayout::NumberValues; ++j) { + averages[i][0] += entry.updateTranslation[j]; + if (entry.updateTranslation[j] != 0.f) + ++(nValues[0]); + averages[i][1] += entry.updateRotation[j]; + if (entry.updateRotation[j] != 0.f) + ++(nValues[1]); + averages[i][2] += entry.updateScaling[j]; + if (entry.updateScaling[j] != 0.f) + ++(nValues[2]); + averages[i][3] += entry.updateRenderable[j]; + if (entry.updateRenderable[j] != 0.f) + ++(nValues[3]); + averages[i][4] += entry.renderTime[j]; + if (entry.renderTime[j] != 0.f) + ++(nValues[4]); + } + + if (nValues[0] != 0) { + averages[i][0] /= static_cast(nValues[0]); + } + if (nValues[1] != 0) { + averages[i][1] /= static_cast(nValues[1]); + } + if (nValues[2] != 0) { + averages[i][2] /= static_cast(nValues[2]); + } + if (nValues[3] != 0) { + averages[i][3] /= static_cast(nValues[3]); + } + if (nValues[4] != 0) { + averages[i][4] /= static_cast(nValues[4]); + } + + // Get the minimum/maximum values for each of the components so that we + // can scale the plot by these numbers + auto minmaxTranslation = std::minmax_element( + std::begin(entry.updateTranslation), + std::end(entry.updateTranslation) + ); + minMax[i][0] = std::make_pair( + *(minmaxTranslation.first), + *(minmaxTranslation.second) + ); + + auto minmaxRotation = std::minmax_element( + std::begin(entry.updateRotation), + std::end(entry.updateRotation) + ); + minMax[i][1] = std::make_pair( + *(minmaxRotation.first), + *(minmaxRotation.second) + ); + + auto minmaxScaling = std::minmax_element( + std::begin(entry.updateScaling), + std::end(entry.updateScaling) + ); + minMax[i][2] = std::make_pair( + *(minmaxScaling.first), + *(minmaxScaling.second) + ); + + auto minmaxUpdateRenderable = std::minmax_element( + std::begin(entry.updateRenderable), + std::end(entry.updateRenderable) + ); + minMax[i][3] = std::make_pair( + *(minmaxUpdateRenderable.first), + *(minmaxUpdateRenderable.second) + ); + + auto minmaxRendering = std::minmax_element( + std::begin(entry.renderTime), + std::end(entry.renderTime) + ); + minMax[i][4] = std::make_pair( + *(minmaxRendering.first), + *(minmaxRendering.second) + ); + + } - - if (_sceneGraphIsEnabled) { - ImGui::Begin("SceneGraph", &_sceneGraphIsEnabled); - - // The indices correspond to the index into the average array further below - ImGui::Text("Sorting"); - ImGui::RadioButton( - "No Sorting", - &_sortingSelection, - static_cast(Sorting::NoSorting) - ); - ImGui::RadioButton( - "UpdateEphemeris", - &_sortingSelection, - static_cast(Sorting::UpdateEphemeris) - ); - ImGui::RadioButton( - "UpdateRender", - &_sortingSelection, - static_cast(Sorting::UpdateRender) - ); - ImGui::RadioButton( - "RenderTime", - &_sortingSelection, - static_cast(Sorting::Render) - ); - ImGui::RadioButton( - "TotalTime", - &_sortingSelection, - static_cast(Sorting::Total) - ); - - // Later, we will sort this indices list instead of the real values for - // performance reasons - std::vector indices(layout->nScaleGraphEntries); - std::iota(indices.begin(), indices.end(), 0); - - // Ordering: - // updateEphemeris - // UpdateRender - // RenderTime - std::vector> averages( - layout->nScaleGraphEntries, - { 0.f, 0.f, 0.f } - ); - std::vector, 3>> minMax( - layout->nScaleGraphEntries - ); - - for (int i = 0; i < layout->nScaleGraphEntries; ++i) { - const PerformanceLayout::SceneGraphPerformanceLayout& entry = - layout->sceneGraphEntries[i]; + // If we don't want to sort, we will leave the indices list alone, thus + // leaving them in the regular ordering + Sorting selection = Sorting(sorting); + if (selection != Sorting::NoSorting) { + std::function sortFunc; - int nValues[3] = { 0, 0, 0 }; - - // Compute the averages and count the number of values so we don't divide - // by 0 later - for (int j = 0; j < PerformanceLayout::NumberValues; ++j) { - averages[i][0] += entry.updateEphemeris[j]; - if (entry.updateEphemeris[j] != 0.f) - ++(nValues[0]); - averages[i][1] += entry.updateRenderable[j]; - if (entry.updateRenderable[j] != 0.f) - ++(nValues[1]); - averages[i][2] += entry.renderTime[j]; - if (entry.renderTime[j] != 0.f) - ++(nValues[2]); - } - - if (nValues[0] != 0) - averages[i][0] /= static_cast(nValues[0]); - if (nValues[1] != 0) - averages[i][1] /= static_cast(nValues[1]); - if (nValues[2] != 0) - averages[i][2] /= static_cast(nValues[2]); - - // Get the minimum/maximum values for each of the components so that we - // can scale the plot by these numbers - auto minmaxEphemeris = std::minmax_element( - std::begin(entry.updateEphemeris), - std::end(entry.updateEphemeris) - ); - minMax[i][0] = std::make_pair( - *(minmaxEphemeris.first), - *(minmaxEphemeris.second) - ); - - auto minmaxUpdateRenderable = std::minmax_element( - std::begin(entry.updateRenderable), - std::end(entry.updateRenderable) - ); - minMax[i][1] = std::make_pair( - *(minmaxUpdateRenderable.first), - *(minmaxUpdateRenderable.second) - ); - - auto minmaxRendering = std::minmax_element( - std::begin(entry.renderTime), - std::end(entry.renderTime) - ); - minMax[i][2] = std::make_pair( - *(minmaxRendering.first), - *(minmaxRendering.second) - ); - - - } - - // If we don't want to sort, we will leave the indices list alone, thus - // leaving them in the regular ordering - Sorting selection = Sorting(_sortingSelection); - if (selection != Sorting::NoSorting) { - std::function sortFunc; - - if (selection == Sorting::Total) { - // If we do want to sort totally, we need to sum all the averages and - // use that as the criterion - sortFunc = [&averages](size_t a, size_t b) { - float sumA = std::accumulate( - std::begin(averages[a]), - std::end(averages[a]), - 0.f - ); - - float sumB = std::accumulate( - std::begin(averages[b]), - std::end(averages[b]), - 0.f - ); - - return sumA > sumB; - }; - } - else { - // otherwise we use the sorting index - int sel = _sortingSelection; - sortFunc = [sel, &averages](size_t a, size_t b) { - return averages[a][sel] > averages[b][sel]; - }; - } - - std::sort( - indices.begin(), - indices.end(), - sortFunc - ); - } - - for (int i = 0; i < layout->nScaleGraphEntries; ++i) { - // We are using the indices list as an additional level of indirection - // into the respective values so that the list will be sorted by whatever - // criterion we selected previously - - const PerformanceLayout::SceneGraphPerformanceLayout& entry = - layout->sceneGraphEntries[indices[i]]; - - if (ImGui::CollapsingHeader(entry.name)) { - - std::string updateEphemerisTime = std::to_string( - entry.updateEphemeris[PerformanceLayout::NumberValues - 1] - ) + "us"; - - ImGui::PlotLines( - fmt::format( - "UpdateEphemeris\nAverage: {}us", - averages[indices[i]][0] - ).c_str(), - &entry.updateEphemeris[0], - PerformanceLayout::NumberValues, - 0, - updateEphemerisTime.c_str(), - minMax[indices[i]][0].first, - minMax[indices[i]][0].second, - ImVec2(0, 40) + if (selection == Sorting::Total) { + // If we do want to sort totally, we need to sum all the averages and + // use that as the criterion + sortFunc = [&averages](size_t a, size_t b) { + float sumA = std::accumulate( + std::begin(averages[a]), + std::end(averages[a]), + 0.f ); - std::string updateRenderableTime = std::to_string( - entry.updateRenderable[PerformanceLayout::NumberValues - 1] - ) + "us"; - - ImGui::PlotLines( - fmt::format( - "UpdateRender\nAverage: {}us", - averages[indices[i]][1] - ).c_str(), - &entry.updateRenderable[0], - PerformanceLayout::NumberValues, - 0, - updateRenderableTime.c_str(), - minMax[indices[i]][1].first, - minMax[indices[i]][1].second, - ImVec2(0, 40) + float sumB = std::accumulate( + std::begin(averages[b]), + std::end(averages[b]), + 0.f ); - std::string renderTime = std::to_string( - entry.renderTime[PerformanceLayout::NumberValues - 1] - ) + "us"; - - ImGui::PlotLines( - fmt::format( - "RenderTime\nAverage: {}us", - averages[indices[i]][2] - ).c_str(), - &entry.renderTime[0], - PerformanceLayout::NumberValues, - 0, - renderTime.c_str(), - minMax[indices[i]][2].first, - minMax[indices[i]][2].second, - ImVec2(0, 40) - ); - } + return sumA > sumB; + }; } - ImGui::End(); + else { + // otherwise we use the sorting index + int sel = _sortingSelection; + sortFunc = [sel, &averages](size_t a, size_t b) { + return averages[a][sel] > averages[b][sel]; + }; + } + + std::sort( + indices.begin(), + indices.end(), + sortFunc + ); } - - if (_functionsIsEnabled) { - ImGui::Begin("Functions", &_functionsIsEnabled); - using namespace performance; - - for (int i = 0; i < layout->nFunctionEntries; ++i) { - const PerformanceLayout::FunctionPerformanceLayout& entry = - layout->functionEntries[i]; - - float avg = 0.f; - int count = 0; - for (int j = 0; j < PerformanceLayout::NumberValues; ++j) { - avg += layout->functionEntries[i].time[j]; - if (layout->functionEntries[i].time[j] != 0.f) - ++count; + else { + // NoSorting -> So we sort by names instead + std::sort( + indices.begin(), + indices.end(), + [layout](size_t a, size_t b) { + return std::string(layout->sceneGraphEntries[a].name) < std::string(layout->sceneGraphEntries[b].name); } - avg /= count; - - auto minmax = std::minmax_element( - std::begin(layout->functionEntries[i].time), - std::end(layout->functionEntries[i].time) - ); - - const PerformanceLayout::FunctionPerformanceLayout& f = - layout->functionEntries[i]; - - std::string renderTime = std::to_string( - entry.time[PerformanceLayout::NumberValues - 1] + ); + } + + for (int i = 0; i < layout->nScaleGraphEntries; ++i) { + // We are using the indices list as an additional level of indirection + // into the respective values so that the list will be sorted by whatever + // criterion we selected previously + + const PerformanceLayout::SceneGraphPerformanceLayout& entry = + layout->sceneGraphEntries[indices[i]]; + + if (ImGui::CollapsingHeader(entry.name)) { + std::string updateTranslationTime = std::to_string( + entry.updateTranslation[PerformanceLayout::NumberValues - 1] ) + "us"; + ImGui::PlotLines( - fmt::format("{}\nAverage: {}us", entry.name, avg).c_str(), - &entry.time[0], + fmt::format( + "UpdateTranslation\nAverage: {}us", + averages[indices[i]][0] + ).c_str(), + &entry.updateTranslation[0], + PerformanceLayout::NumberValues, + 0, + updateTranslationTime.c_str(), + minMax[indices[i]][0].first, + minMax[indices[i]][0].second, + ImVec2(0, 40) + ); + + std::string updateRotationTime = std::to_string( + entry.updateRotation[PerformanceLayout::NumberValues - 1] + ) + "us"; + + ImGui::PlotLines( + fmt::format( + "UpdateRotation\nAverage: {}us", + averages[indices[i]][1] + ).c_str(), + &entry.updateRotation[0], + PerformanceLayout::NumberValues, + 0, + updateRotationTime.c_str(), + minMax[indices[i]][1].first, + minMax[indices[i]][1].second, + ImVec2(0, 40) + ); + + std::string updateScalingTime = std::to_string( + entry.updateScaling[PerformanceLayout::NumberValues - 1] + ) + "us"; + + ImGui::PlotLines( + fmt::format( + "UpdateScaling\nAverage: {}us", + averages[indices[i]][2] + ).c_str(), + &entry.updateScaling[0], + PerformanceLayout::NumberValues, + 0, + updateScalingTime.c_str(), + minMax[indices[i]][2].first, + minMax[indices[i]][2].second, + ImVec2(0, 40) + ); + + std::string updateRenderableTime = std::to_string( + entry.updateRenderable[PerformanceLayout::NumberValues - 1] + ) + "us"; + + ImGui::PlotLines( + fmt::format( + "UpdateRender\nAverage: {}us", + averages[indices[i]][3] + ).c_str(), + &entry.updateRenderable[0], + PerformanceLayout::NumberValues, + 0, + updateRenderableTime.c_str(), + minMax[indices[i]][3].first, + minMax[indices[i]][3].second, + ImVec2(0, 40) + ); + + std::string renderTime = std::to_string( + entry.renderTime[PerformanceLayout::NumberValues - 1] + ) + "us"; + + ImGui::PlotLines( + fmt::format( + "RenderTime\nAverage: {}us", + averages[indices[i]][4] + ).c_str(), + &entry.renderTime[0], PerformanceLayout::NumberValues, 0, renderTime.c_str(), - *(minmax.first), - *(minmax.second), + minMax[indices[i]][4].first, + minMax[indices[i]][4].second, ImVec2(0, 40) ); } - ImGui::End(); } + ImGui::End(); } - else { - ImGui::TextWrapped("Performance monitoring is disabled. Enable with " - "'openspace.setPerformanceMeasurement(true)'"); + + if (_functionsIsEnabled) { + bool v = _functionsIsEnabled; + ImGui::Begin("Functions", &v); + _functionsIsEnabled = v; + using namespace performance; + + for (int i = 0; i < layout->nFunctionEntries; ++i) { + const PerformanceLayout::FunctionPerformanceLayout& entry = + layout->functionEntries[i]; + + float avg = 0.f; + int count = 0; + for (int j = 0; j < PerformanceLayout::NumberValues; ++j) { + avg += layout->functionEntries[i].time[j]; + if (layout->functionEntries[i].time[j] != 0.f) + ++count; + } + avg /= count; + + auto minmax = std::minmax_element( + std::begin(layout->functionEntries[i].time), + std::end(layout->functionEntries[i].time) + ); + + const PerformanceLayout::FunctionPerformanceLayout& f = + layout->functionEntries[i]; + + std::string renderTime = std::to_string( + entry.time[PerformanceLayout::NumberValues - 1] + ) + "us"; + ImGui::PlotLines( + fmt::format("{}\nAverage: {}us", entry.name, avg).c_str(), + &entry.time[0], + PerformanceLayout::NumberValues, + 0, + renderTime.c_str(), + *(minmax.first), + *(minmax.second), + ImVec2(0, 40) + ); + } + ImGui::End(); } ImGui::End(); diff --git a/modules/onscreengui/src/guipropertycomponent.cpp b/modules/onscreengui/src/guipropertycomponent.cpp index 79af1a59f0..edf2a1ed87 100644 --- a/modules/onscreengui/src/guipropertycomponent.cpp +++ b/modules/onscreengui/src/guipropertycomponent.cpp @@ -28,6 +28,7 @@ #include +#include #include "imgui.h" namespace { @@ -36,21 +37,53 @@ namespace { } namespace openspace { + +namespace { +int nVisibleProperties(const std::vector& properties, + properties::Property::Visibility visibility) +{ + return std::count_if( + properties.begin(), + properties.end(), + [visibility](properties::Property* p) { + using V = properties::Property::Visibility; + return + static_cast>(visibility) >= + static_cast>(p->visibility()); + } + ); +} +} + namespace gui { GuiPropertyComponent::GuiPropertyComponent(std::string name) - : _name(std::move(name)) + : GuiComponent(std::move(name)) {} void GuiPropertyComponent::setSource(SourceFunction function) { _function = std::move(function); } +void GuiPropertyComponent::setVisibility(properties::Property::Visibility visibility) { + _visibility = visibility; +} + void GuiPropertyComponent::renderPropertyOwner(properties::PropertyOwner* owner) { + if (owner->propertiesRecursive().empty()) { + return; + } + + int nThisProperty = nVisibleProperties(owner->properties(), _visibility); ImGui::PushID(owner->name().c_str()); const auto& subOwners = owner->propertySubOwners(); for (properties::PropertyOwner* subOwner : subOwners) { - if (subOwners.size() == 1) { + std::vector properties = subOwner->propertiesRecursive(); + int count = nVisibleProperties(properties, _visibility); + if (count == 0) { + continue; + } + if (subOwners.size() == 1 && (nThisProperty == 0)) { renderPropertyOwner(subOwner); } else { @@ -89,24 +122,34 @@ void GuiPropertyComponent::renderPropertyOwner(properties::PropertyOwner* owner) ImGui::Spacing(); for (properties::Property* prop : remainingProperies) { - if (prop->isVisible()) { - renderProperty(prop, owner); - } + renderProperty(prop, owner); } ImGui::PopID(); } void GuiPropertyComponent::render() { - ImGui::Begin(_name.c_str(), &_isEnabled, size, 0.5f); + bool v = _isEnabled; + ImGui::Begin(name().c_str(), &v, size, 0.5f); + _isEnabled = v; ImGui::Spacing(); if (_function) { - const std::vector& owners = _function(); + std::vector owners = _function(); + std::sort( + owners.begin(), + owners.end(), + [](properties::PropertyOwner* lhs, properties::PropertyOwner* rhs) { + return lhs->name() < rhs->name(); + } + ); for (properties::PropertyOwner* pOwner : owners) { - if (pOwner->propertiesRecursive().empty()) + int count = nVisibleProperties(pOwner->propertiesRecursive(), _visibility); + + if (count == 0) { continue; + } auto header = [&]() -> bool { if (owners.size() > 1) { @@ -130,10 +173,13 @@ void GuiPropertyComponent::render() { ImGui::End(); } -void GuiPropertyComponent::renderProperty(properties::Property* prop, properties::PropertyOwner* owner) { +void GuiPropertyComponent::renderProperty(properties::Property* prop, + properties::PropertyOwner* owner) +{ using Func = std::function; - static std::map FunctionMapping = { + static const std::map FunctionMapping = { { "BoolProperty", &renderBoolProperty }, + { "DoubleProperty", &renderDoubleProperty}, { "IntProperty", &renderIntProperty }, { "IVec2Property", &renderIVec2Property }, { "IVec3Property", &renderIVec3Property }, @@ -142,15 +188,24 @@ void GuiPropertyComponent::renderProperty(properties::Property* prop, properties { "Vec2Property", &renderVec2Property }, { "Vec3Property", &renderVec3Property }, { "Vec4Property", &renderVec4Property }, + { "DVec2Property", &renderDVec2Property }, + { "DVec3Property", &renderDVec3Property }, + { "DVec4Property", &renderDVec4Property }, { "StringProperty", &renderStringProperty }, { "OptionProperty", &renderOptionProperty }, { "TriggerProperty", &renderTriggerProperty }, { "SelectionProperty", &renderSelectionProperty } }; - auto it = FunctionMapping.find(prop->className()); - if (it != FunctionMapping.end()) { - it->second(prop, owner->name()); + // Check if the visibility of the property is high enough to be displayed + using V = properties::Property::Visibility; + auto v = static_cast>(_visibility); + auto propV = static_cast>(prop->visibility()); + if (v >= propV) { + auto it = FunctionMapping.find(prop->className()); + if (it != FunctionMapping.end()) { + it->second(prop, owner->name()); + } } } diff --git a/modules/onscreengui/src/guitimecomponent.cpp b/modules/onscreengui/src/guitimecomponent.cpp index e98c2d5059..43178a2270 100644 --- a/modules/onscreengui/src/guitimecomponent.cpp +++ b/modules/onscreengui/src/guitimecomponent.cpp @@ -32,13 +32,18 @@ namespace openspace { namespace gui { +GuiTimeComponent::GuiTimeComponent() + : GuiComponent("Time") +{} + void GuiTimeComponent::render() { float deltaTime = static_cast(Time::ref().deltaTime()); - bool changed = ImGui::SliderFloat("Delta Time", &deltaTime, -5000.f, 5000.f); + bool changed = ImGui::SliderFloat("Delta Time", &deltaTime, -50000.f, 50000.f); if (changed) { OsEng.scriptEngine().queueScript( - "openspace.time.setDeltaTime(" + std::to_string(deltaTime) + ")" + "openspace.time.setDeltaTime(" + std::to_string(deltaTime) + ")", + scripting::ScriptEngine::RemoteScripting::Yes ); } } diff --git a/modules/onscreengui/src/renderproperties.cpp b/modules/onscreengui/src/renderproperties.cpp index 47014d4f11..21489500ae 100644 --- a/modules/onscreengui/src/renderproperties.cpp +++ b/modules/onscreengui/src/renderproperties.cpp @@ -32,6 +32,8 @@ #include #include +#include + #include "imgui.h" namespace openspace { @@ -47,7 +49,7 @@ void renderTooltip(Property* prop) { void executeScript(const std::string& id, const std::string& value) { std::string script = "openspace.setPropertyValueSingle('" + id + "', " + value + ");"; - OsEng.scriptEngine().queueScript(script); + OsEng.scriptEngine().queueScript(script, scripting::ScriptEngine::RemoteScripting::Yes); } void renderBoolProperty(Property* prop, const std::string& ownerName) { @@ -59,8 +61,9 @@ void renderBoolProperty(Property* prop, const std::string& ownerName) { ImGui::Checkbox(name.c_str(), &value); renderTooltip(prop); - if (value != p->value()) + if (value != p->value()) { executeScript(p->fullyQualifiedIdentifier(), value ? "true" : "false"); + } ImGui::PopID(); } @@ -72,16 +75,16 @@ void renderOptionProperty(Property* prop, const std::string& ownerName) { int value = *p; std::vector options = p->options(); switch (p->displayType()) { - case OptionProperty::DisplayType::RADIO: { + case OptionProperty::DisplayType::Radio: { + ImGui::Text(name.c_str()); + ImGui::Separator(); for (const OptionProperty::Option& o : options) { - ImGui::RadioButton(name.c_str(), &value, o.value); - ImGui::SameLine(); - ImGui::Text(o.description.c_str()); + ImGui::RadioButton(o.description.c_str(), &value, o.value); renderTooltip(prop); } break; } - case OptionProperty::DisplayType::DROPDOWN: { + case OptionProperty::DisplayType::Dropdown: { std::string nodeNames = ""; for (const OptionProperty::Option& o : options) { nodeNames += o.description + '\0'; @@ -90,8 +93,9 @@ void renderOptionProperty(Property* prop, const std::string& ownerName) { break; } } - if (value != p->value()) + if (value != p->value()) { executeScript(p->fullyQualifiedIdentifier(), std::to_string(value)); + } ImGui::PopID(); } @@ -115,14 +119,16 @@ void renderSelectionProperty(Property* prop, const std::string& ownerName) { ImGui::Checkbox(description.c_str(), &selected); renderTooltip(prop); - if (selected) + if (selected) { newSelectedIndices.push_back(i); + } } if (newSelectedIndices != p->value()) { std::string parameters = "{"; - for (int i : newSelectedIndices) + for (int i : newSelectedIndices) { parameters += std::to_string(i) + ","; + } parameters += "}"; executeScript(p->fullyQualifiedIdentifier(), parameters); } @@ -136,20 +142,46 @@ void renderStringProperty(Property* prop, const std::string& ownerName) { std::string name = p->guiName(); ImGui::PushID((ownerName + "." + name).c_str()); + std::string value = FileSys.convertPathSeparator(p->value(), '/'); + static const int bufferSize = 256; static char buffer[bufferSize]; #ifdef _MSC_VER - strcpy_s(buffer, p->value().length() + 1, p->value().c_str()); + strcpy_s(buffer, value.length() + 1, value.c_str()); #else - strcpy(buffer, p->value().c_str()); + strcpy(buffer, value.c_str()); #endif - ImGui::InputText(name.c_str(), buffer, bufferSize); + bool hasNewValue = ImGui::InputText( + name.c_str(), + buffer, + bufferSize, + ImGuiInputTextFlags_EnterReturnsTrue + ); renderTooltip(prop); - std::string newValue(buffer); - if (newValue != p->value()) - executeScript(p->fullyQualifiedIdentifier(), "'" + newValue + "'"); + if (hasNewValue) { + executeScript(p->fullyQualifiedIdentifier(), "'" + std::string(buffer) + "'"); + } + + ImGui::PopID(); +} + +void renderDoubleProperty(properties::Property* prop, const std::string& ownerName) { + DoubleProperty* p = static_cast(prop); + std::string name = p->guiName(); + ImGui::PushID((ownerName + "." + name).c_str()); + + float value = *p; + float min = p->minValue(); + float max = p->maxValue(); + + ImGui::SliderFloat(name.c_str(), &value, min, max); + renderTooltip(prop); + + if (value != static_cast(p->value())) { + executeScript(p->fullyQualifiedIdentifier(), std::to_string(value)); + } ImGui::PopID(); } @@ -166,8 +198,9 @@ void renderIntProperty(Property* prop, const std::string& ownerName) { ImGui::SliderInt(name.c_str(), &value, min, max); renderTooltip(prop); - if (value != p->value()) + if (value != p->value()) { executeScript(p->fullyQualifiedIdentifier(), std::to_string(value)); + } ImGui::PopID(); } @@ -181,17 +214,18 @@ void renderIVec2Property(Property* prop, const std::string& ownerName) { float min = std::min(p->minValue().x, p->minValue().y); float max = std::max(p->maxValue().x, p->maxValue().y); ImGui::SliderInt2( - name.c_str(), - &value.x, - min, - max - ); + name.c_str(), + &value.x, + min, + max + ); renderTooltip(prop); if (value != p->value()) { - executeScript(p->fullyQualifiedIdentifier(), - "{" + std::to_string(value.x) + "," + std::to_string(value.y) + "}" - ); + executeScript( + p->fullyQualifiedIdentifier(), + "{" + std::to_string(value.x) + "," + std::to_string(value.y) + "}" + ); } ImGui::PopID(); @@ -207,19 +241,20 @@ void renderIVec3Property(Property* prop, const std::string& ownerName) { float max = std::max(std::max(p->maxValue().x, p->maxValue().y), p->maxValue().z); ImGui::SliderInt3( - name.c_str(), - &value.x, - min, - max - ); + name.c_str(), + &value.x, + min, + max + ); renderTooltip(prop); - if (value != p->value()) - executeScript(p->fullyQualifiedIdentifier(), - "{" + std::to_string(value.x) + "," + - std::to_string(value.y) + "," + - std::to_string(value.z) + "}"); - + if (value != p->value()) { + executeScript( + p->fullyQualifiedIdentifier(), + "{" + std::to_string(value.x) + "," + std::to_string(value.y) + "," + + std::to_string(value.z) + "}" + ); + } ImGui::PopID(); } @@ -230,29 +265,32 @@ void renderIVec4Property(Property* prop, const std::string& ownerName) { IVec4Property::ValueType value = *p; float min = std::min(std::min(std::min( - p->minValue().x, p->minValue().y), p->minValue().z), p->minValue().w); + p->minValue().x, p->minValue().y), p->minValue().z), p->minValue().w + ); float max = std::max(std::max(std::max( - p->maxValue().x, p->maxValue().y), p->maxValue().z), p->maxValue().w); + p->maxValue().x, p->maxValue().y), p->maxValue().z), p->maxValue().w + ); ImGui::SliderInt4( - name.c_str(), - &value.x, - min, - max - ); + name.c_str(), + &value.x, + min, + max + ); renderTooltip(prop); - if (value != p->value()) - executeScript(p->fullyQualifiedIdentifier(), - "{" + std::to_string(value.x) + "," + - std::to_string(value.y) + "," + - std::to_string(value.z) + "," + - std::to_string(value.w) + "}"); - + if (value != p->value()) { + executeScript( + p->fullyQualifiedIdentifier(), + "{" + std::to_string(value.x) + "," + + std::to_string(value.y) + "," + + std::to_string(value.z) + "," + + std::to_string(value.w) + "}" + ); + } ImGui::PopID(); } - - + void renderFloatProperty(Property* prop, const std::string& ownerName) { FloatProperty* p = static_cast(prop); std::string name = p->guiName(); @@ -264,8 +302,9 @@ void renderFloatProperty(Property* prop, const std::string& ownerName) { ImGui::SliderFloat(name.c_str(), &value, min, max); renderTooltip(prop); - if (value != p->value()) + if (value != p->value()) { executeScript(p->fullyQualifiedIdentifier(), std::to_string(value)); + } ImGui::PopID(); } @@ -287,8 +326,9 @@ void renderVec2Property(Property* prop, const std::string& ownerName) { renderTooltip(prop); if (value != p->value()) { - executeScript(p->fullyQualifiedIdentifier(), - "{" + std::to_string(value.x) + "," + std::to_string(value.y) + "}" + executeScript( + p->fullyQualifiedIdentifier(), + "{" + std::to_string(value.x) + "," + std::to_string(value.y) + "}" ); } @@ -304,19 +344,23 @@ void renderVec3Property(Property* prop, const std::string& ownerName) { float min = std::min(std::min(p->minValue().x, p->minValue().y), p->minValue().z); float max = std::max(std::max(p->maxValue().x, p->maxValue().y), p->maxValue().z); + ImGui::SliderFloat3( name.c_str(), - &value.x, + glm::value_ptr(value), min, max ); renderTooltip(prop); - if (value != p->value()) - executeScript(p->fullyQualifiedIdentifier(), - "{" + std::to_string(value.x) + "," + - std::to_string(value.y) + "," + - std::to_string(value.z) + "}"); + if (value != p->value()) { + executeScript( + p->fullyQualifiedIdentifier(), + "{" + std::to_string(value.x) + "," + + std::to_string(value.y) + "," + + std::to_string(value.z) + "}" + ); + } ImGui::PopID(); } @@ -340,12 +384,103 @@ void renderVec4Property(Property* prop, const std::string& ownerName) { ); renderTooltip(prop); - if (value != p->value()) - executeScript(p->fullyQualifiedIdentifier(), - "{" + std::to_string(value.x) + "," + - std::to_string(value.y) + "," + - std::to_string(value.z) + "," + - std::to_string(value.w) + "}"); + if (value != p->value()) { + executeScript( + p->fullyQualifiedIdentifier(), + "{" + std::to_string(value.x) + "," + + std::to_string(value.y) + "," + + std::to_string(value.z) + "," + + std::to_string(value.w) + "}" + ); + } + + ImGui::PopID(); +} + +void renderDVec2Property(Property* prop, const std::string& ownerName) { + DVec2Property* p = static_cast(prop); + std::string name = p->guiName(); + ImGui::PushID((ownerName + "." + name).c_str()); + + glm::vec2 value = glm::dvec2(*p); + float min = std::min(p->minValue().x, p->minValue().y); + float max = std::max(p->maxValue().x, p->maxValue().y); + ImGui::SliderFloat2( + name.c_str(), + &value.x, + min, + max + ); + renderTooltip(prop); + + if (glm::dvec2(value) != p->value()) { + executeScript( + p->fullyQualifiedIdentifier(), + "{" + std::to_string(value.x) + "," + std::to_string(value.y) + "}" + ); + } + + ImGui::PopID(); +} + +void renderDVec3Property(Property* prop, const std::string& ownerName) { + DVec3Property* p = static_cast(prop); + std::string name = p->guiName(); + ImGui::PushID((ownerName + "." + name).c_str()); + + glm::vec3 value = glm::dvec3(*p); + float min = std::min(std::min(p->minValue().x, p->minValue().y), p->minValue().z); + float max = std::max(std::max(p->maxValue().x, p->maxValue().y), p->maxValue().z); + + + ImGui::SliderFloat3( + name.c_str(), + glm::value_ptr(value), + min, + max + ); + renderTooltip(prop); + + if (glm::dvec3(value) != p->value()) { + executeScript( + p->fullyQualifiedIdentifier(), + "{" + std::to_string(value.x) + "," + + std::to_string(value.y) + "," + + std::to_string(value.z) + "}" + ); + } + + ImGui::PopID(); +} + +void renderDVec4Property(Property* prop, const std::string& ownerName) { + DVec4Property* p = static_cast(prop); + std::string name = p->guiName(); + ImGui::PushID((ownerName + "." + name).c_str()); + + glm::vec4 value = glm::dvec4(*p); + float min = std::min(std::min(std::min( + p->minValue().x, p->minValue().y), p->minValue().z), p->minValue().w); + float max = std::max(std::max(std::max( + p->maxValue().x, p->maxValue().y), p->maxValue().z), p->maxValue().w); + + ImGui::SliderFloat4( + name.c_str(), + &value.x, + min, + max + ); + renderTooltip(prop); + + if (glm::dvec4(value) != p->value()) { + executeScript( + p->fullyQualifiedIdentifier(), + "{" + std::to_string(value.x) + "," + + std::to_string(value.y) + "," + + std::to_string(value.z) + "," + + std::to_string(value.w) + "}" + ); + } ImGui::PopID(); } @@ -355,8 +490,9 @@ void renderTriggerProperty(Property* prop, const std::string& ownerName) { ImGui::PushID((ownerName + "." + name).c_str()); bool pressed = ImGui::Button(name.c_str()); - if (pressed) + if (pressed) { executeScript(prop->fullyQualifiedIdentifier(), "nil"); + } renderTooltip(prop); ImGui::PopID(); diff --git a/modules/space/CMakeLists.txt b/modules/space/CMakeLists.txt new file mode 100644 index 0000000000..b4fc052ad4 --- /dev/null +++ b/modules/space/CMakeLists.txt @@ -0,0 +1,78 @@ +######################################################################################### +# # +# OpenSpace # +# # +# Copyright (c) 2014-2016 # +# # +# Permission is hereby granted, free of charge, to any person obtaining a copy of this # +# software and associated documentation files (the "Software"), to deal in the Software # +# without restriction, including without limitation the rights to use, copy, modify, # +# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to # +# permit persons to whom the Software is furnished to do so, subject to the following # +# conditions: # +# # +# The above copyright notice and this permission notice shall be included in all copies # +# or substantial portions of the Software. # +# # +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # +# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A # +# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # +# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF # +# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE # +# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # +######################################################################################### + +include(${OPENSPACE_CMAKE_EXT_DIR}/module_definition.cmake) + +set(HEADER_FILES + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/planetgeometry.h + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableconstellationbounds.h + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableplanet.h + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablerings.h + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablestars.h + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/simplespheregeometry.h + ${CMAKE_CURRENT_SOURCE_DIR}/translation/keplertranslation.h + ${CMAKE_CURRENT_SOURCE_DIR}/translation/spicetranslation.h + ${CMAKE_CURRENT_SOURCE_DIR}/translation/tletranslation.h + ${CMAKE_CURRENT_SOURCE_DIR}/rotation/spicerotation.h +) +source_group("Header Files" FILES ${HEADER_FILES}) + +set(SOURCE_FILES + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/planetgeometry.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableconstellationbounds.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableplanet.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablerings.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablestars.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/simplespheregeometry.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/translation/keplertranslation.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/translation/spicetranslation.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/translation/tletranslation.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rotation/spicerotation.cpp +) +source_group("Source Files" FILES ${SOURCE_FILES}) + +set(SHADER_FILES + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/constellationbounds_fs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/constellationbounds_vs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/nighttexture_fs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/nighttexture_vs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/renderableplanet_fs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/renderableplanet_vs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/rings_vs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/rings_fs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shadow_fs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shadow_vs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shadow_nighttexture_fs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shadow_nighttexture_vs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/star_fs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/star_ge.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/star_vs.glsl +) +source_group("Shader Files" FILES ${SHADER_FILES}) + +create_new_module( + "Space" + space_module + ${HEADER_FILES} ${SOURCE_FILES} ${SHADER_FILES} +) diff --git a/modules/space/include.cmake b/modules/space/include.cmake new file mode 100644 index 0000000000..ffea0ac430 --- /dev/null +++ b/modules/space/include.cmake @@ -0,0 +1 @@ +set(DEFAULT_MODULE ON) diff --git a/modules/base/rendering/planetgeometry.cpp b/modules/space/rendering/planetgeometry.cpp similarity index 74% rename from modules/base/rendering/planetgeometry.cpp rename to modules/space/rendering/planetgeometry.cpp index 32e366b0fd..8d437fb539 100644 --- a/modules/base/rendering/planetgeometry.cpp +++ b/modules/space/rendering/planetgeometry.cpp @@ -22,33 +22,51 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include +#include #include +#include + namespace { const std::string _loggerCat = "PlanetGeometry"; - const std::string KeyType = "Type"; + const char* KeyType = "Type"; } namespace openspace { namespace planetgeometry { -PlanetGeometry* PlanetGeometry::createFromDictionary(const ghoul::Dictionary& dictionary) { - std::string geometryType; - const bool success = dictionary.getValue(KeyType, geometryType); - if (!success) { - LERROR("PlanetGeometry did not contain a correct value of the key '" - << KeyType << "'"); - return nullptr; - } - ghoul::TemplateFactory* factory - = FactoryManager::ref().factory(); +Documentation PlanetGeometry::Documentation() { + using namespace documentation; + return { + "Planet Geometry", + "space_geometry_planet", + { + { + KeyType, + new StringVerifier, + "The type of the PlanetGeometry that will can be constructed.", + Optional::No + } + } + }; +} + +PlanetGeometry* PlanetGeometry::createFromDictionary(const ghoul::Dictionary& dictionary) +{ + documentation::testSpecificationAndThrow( + Documentation(), + dictionary, + "PlanetGeometry" + ); + + std::string geometryType = dictionary.value(KeyType); + auto factory = FactoryManager::ref().factory(); PlanetGeometry* result = factory->create(geometryType, dictionary); if (result == nullptr) { - LERROR("Failed to create a PlanetGeometry object of type '" << geometryType - << "'"); - return nullptr; + throw ghoul::RuntimeError( + "Failed to create a PlanetGeometry object of type '" + geometryType + "'" + ); } return result; } diff --git a/modules/base/rendering/planetgeometry.h b/modules/space/rendering/planetgeometry.h similarity index 89% rename from modules/base/rendering/planetgeometry.h rename to modules/space/rendering/planetgeometry.h index 3a38f3be81..d1690a4924 100644 --- a/modules/base/rendering/planetgeometry.h +++ b/modules/space/rendering/planetgeometry.h @@ -22,14 +22,15 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __PLANETGEOMETRY_H__ -#define __PLANETGEOMETRY_H__ +#ifndef __OPENSPACE_MODULE_SPACE___PLANETGEOMETRY___H__ +#define __OPENSPACE_MODULE_SPACE___PLANETGEOMETRY___H__ #include -#include -#include + +#include namespace openspace { +class Renderable; namespace planetgeometry { @@ -43,6 +44,8 @@ public: virtual void deinitialize(); virtual void render() = 0; + static openspace::Documentation Documentation(); + protected: Renderable* _parent; }; @@ -50,4 +53,4 @@ protected: } // namespace planetgeometry } // namespace openspace -#endif // __PLANETGEOMETRY_H__ +#endif // __OPENSPACE_MODULE_SPACE___PLANETGEOMETRY___H__ diff --git a/modules/base/rendering/renderableconstellationbounds.cpp b/modules/space/rendering/renderableconstellationbounds.cpp similarity index 95% rename from modules/base/rendering/renderableconstellationbounds.cpp rename to modules/space/rendering/renderableconstellationbounds.cpp index ea7b07c85c..49e7f01968 100644 --- a/modules/base/rendering/renderableconstellationbounds.cpp +++ b/modules/space/rendering/renderableconstellationbounds.cpp @@ -25,7 +25,7 @@ // openspace #include #include -#include +#include #include #include @@ -37,14 +37,17 @@ #define _USE_MATH_DEFINES #include +#include "SpiceUsr.h" +#include "SpiceZpr.h" + namespace { const std::string _loggerCat = "RenderableConstellationBounds"; - const std::string keyVertexFile = "File"; - const std::string keyConstellationFile = "ConstellationFile"; - const std::string keyReferenceFrame = "ReferenceFrame"; + const char* keyVertexFile = "File"; + const char* keyConstellationFile = "ConstellationFile"; + const char* keyReferenceFrame = "ReferenceFrame"; - const std::string defaultReferenceFrame = "J2000"; + const char* defaultReferenceFrame = "J2000"; float deg2rad(float deg) { return static_cast((deg / 360.f) * 2.f * M_PI); @@ -58,7 +61,7 @@ namespace { namespace openspace { RenderableConstellationBounds::RenderableConstellationBounds( - const ghoul::Dictionary& dictionary) + const ghoul::Dictionary& dictionary) : Renderable(dictionary) , _vertexFilename("") , _constellationFilename("") @@ -88,14 +91,11 @@ RenderableConstellationBounds::RenderableConstellationBounds( ); } -RenderableConstellationBounds::~RenderableConstellationBounds() { -} - bool RenderableConstellationBounds::initialize() { RenderEngine& renderEngine = OsEng.renderEngine(); _program = renderEngine.buildRenderProgram("ConstellationBounds", - "${MODULE_BASE}/shaders/constellationbounds_vs.glsl", - "${MODULE_BASE}/shaders/constellationbounds_fs.glsl"); + "${MODULE_SPACE}/shaders/constellationbounds_vs.glsl", + "${MODULE_SPACE}/shaders/constellationbounds_fs.glsl"); if (!_program) return false; @@ -211,7 +211,7 @@ bool RenderableConstellationBounds::loadVertexFile() { float ra; float dec; std::string constellationName; - SpiceDouble rectangularValues[3]; + double rectangularValues[3]; // Overview of the reading algorithm: // We keep an active ConstellationBound (currentBound) and update it until we read diff --git a/modules/base/rendering/renderableconstellationbounds.h b/modules/space/rendering/renderableconstellationbounds.h similarity index 96% rename from modules/base/rendering/renderableconstellationbounds.h rename to modules/space/rendering/renderableconstellationbounds.h index b4b7774c0f..68a1014513 100644 --- a/modules/base/rendering/renderableconstellationbounds.h +++ b/modules/space/rendering/renderableconstellationbounds.h @@ -22,10 +22,11 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERABLECONSTELLATIONBOUNDS_H__ -#define __RENDERABLECONSTELLATIONBOUNDS_H__ +#ifndef __OPENSPACE_MODULE_SPACE___RENDERABLECONSTELLATIONBOUNDS___H__ +#define __OPENSPACE_MODULE_SPACE___RENDERABLECONSTELLATIONBOUNDS___H__ #include + #include #include #include @@ -53,7 +54,6 @@ namespace openspace { class RenderableConstellationBounds : public Renderable { public: RenderableConstellationBounds(const ghoul::Dictionary& dictionary); - ~RenderableConstellationBounds(); bool initialize() override; bool deinitialize() override; @@ -126,4 +126,4 @@ private: } // namespace openspace -#endif // __RENDERABLECONSTELLATIONBOUNDS_H__ +#endif // __OPENSPACE_MODULE_SPACE___RENDERABLECONSTELLATIONBOUNDS___H__ diff --git a/modules/space/rendering/renderableplanet.cpp b/modules/space/rendering/renderableplanet.cpp new file mode 100644 index 0000000000..f113d78f72 --- /dev/null +++ b/modules/space/rendering/renderableplanet.cpp @@ -0,0 +1,559 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +// open space includes +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +#define _USE_MATH_DEFINES +#include + + +namespace { + static const std::string _loggerCat = "RenderablePlanet"; + + const char* keyFrame = "Frame"; + const char* keyGeometry = "Geometry"; + const char* keyRadius = "Radius"; + const char* keyShading = "PerformShading"; + const char* keyShadowGroup = "Shadow_Group"; + const char* keyShadowSource = "Source"; + const char* keyShadowCaster = "Caster"; + const char* keyPlanetRadius = "PlanetRadius"; + const char* keyBody = "Body"; +} + +namespace openspace { + +RenderablePlanet::RenderablePlanet(const ghoul::Dictionary& dictionary) + : Renderable(dictionary) + , _colorTexturePath("colorTexture", "Color Texture") + , _nightTexturePath("nightTexture", "Night Texture") + , _heightMapTexturePath("heightMap", "Heightmap Texture") + , _heightExaggeration("heightExaggeration", "Height Exaggeration", 1.f, 0.f, 10.f) + , _programObject(nullptr) + , _texture(nullptr) + , _nightTexture(nullptr) + , _geometry(nullptr) + , _performShading("performShading", "Perform Shading", true) + , _rotation("rotation", "Rotation", 0, 0, 360) + , _alpha(1.f) + , _planetRadius(0.f) + , _hasNightTexture(false) + , _hasHeightTexture(false) + , _shadowEnabled(false) +{ + std::string name; + bool success = dictionary.getValue(SceneGraphNode::KeyName, name); + ghoul_assert(success, + "RenderablePlanet need the '" << SceneGraphNode::KeyName<<"' be specified"); + + ghoul::Dictionary geometryDictionary; + success = dictionary.getValue(keyGeometry, geometryDictionary); + if (success) { + geometryDictionary.setValue(SceneGraphNode::KeyName, name); + _geometry = planetgeometry::PlanetGeometry::createFromDictionary(geometryDictionary); + + glm::vec2 planetRadiusVec; + success = geometryDictionary.getValue(keyRadius, planetRadiusVec); + if (success) + _planetRadius = planetRadiusVec[0] * glm::pow(10, planetRadiusVec[1]); + else + LWARNING("No Radius value expecified for " << name << " planet."); + } + + dictionary.getValue(keyFrame, _frame); + dictionary.getValue(keyBody, _target); + + + // TODO: textures need to be replaced by a good system similar to the geometry as soon + // as the requirements are fixed (ab) + std::string texturePath = ""; + success = dictionary.getValue("Textures.Color", texturePath); + if (success) + _colorTexturePath = absPath(texturePath); + + std::string nightTexturePath = ""; + dictionary.getValue("Textures.Night", nightTexturePath); + if (nightTexturePath != ""){ + _hasNightTexture = true; + _nightTexturePath = absPath(nightTexturePath); + } + + std::string heightMapTexturePath = ""; + dictionary.getValue("Textures.Height", heightMapTexturePath); + if (heightMapTexturePath != "") { + _hasHeightTexture = true; + _heightMapTexturePath = absPath(heightMapTexturePath); + } + + addPropertySubOwner(_geometry); + + addProperty(_colorTexturePath); + _colorTexturePath.onChange(std::bind(&RenderablePlanet::loadTexture, this)); + + addProperty(_nightTexturePath); + _nightTexturePath.onChange(std::bind(&RenderablePlanet::loadTexture, this)); + + addProperty(_heightMapTexturePath); + _heightMapTexturePath.onChange(std::bind(&RenderablePlanet::loadTexture, this)); + + addProperty(_heightExaggeration); + + if (dictionary.hasKeyAndValue(keyShading)) { + bool shading; + dictionary.getValue(keyShading, shading); + _performShading = shading; + } + + addProperty(_performShading); + // Mainly for debugging purposes @AA + addProperty(_rotation); + + // Shadow data: + ghoul::Dictionary shadowDictionary; + success = dictionary.getValue(keyShadowGroup, shadowDictionary); + bool disableShadows = false; + if (success) { + std::vector< std::pair > sourceArray; + unsigned int sourceCounter = 1; + while (success) { + std::string sourceName; + std::stringstream ss; + ss << keyShadowSource << sourceCounter << ".Name"; + success = shadowDictionary.getValue(ss.str(), sourceName); + if (success) { + glm::vec2 sourceRadius; + ss.str(std::string()); + ss << keyShadowSource << sourceCounter << ".Radius"; + success = shadowDictionary.getValue(ss.str(), sourceRadius); + if (success) { + sourceArray.push_back(std::pair< std::string, float>( + sourceName, sourceRadius[0] * pow(10.f, sourceRadius[1]))); + } + else { + LWARNING("No Radius value expecified for Shadow Source Name " + << sourceName << " from " << name + << " planet.\nDisabling shadows for this planet."); + disableShadows = true; + break; + } + } + sourceCounter++; + } + + if (!disableShadows && !sourceArray.empty()) { + success = true; + std::vector< std::pair > casterArray; + unsigned int casterCounter = 1; + while (success) { + std::string casterName; + std::stringstream ss; + ss << keyShadowCaster << casterCounter << ".Name"; + success = shadowDictionary.getValue(ss.str(), casterName); + if (success) { + glm::vec2 casterRadius; + ss.str(std::string()); + ss << keyShadowCaster << casterCounter << ".Radius"; + success = shadowDictionary.getValue(ss.str(), casterRadius); + if (success) { + casterArray.push_back(std::pair< std::string, float>( + casterName, casterRadius[0] * pow(10.f, casterRadius[1]))); + } + else { + LWARNING("No Radius value expecified for Shadow Caster Name " + << casterName << " from " << name + << " planet.\nDisabling shadows for this planet."); + disableShadows = true; + break; + } + } + + casterCounter++; + } + + if (!disableShadows && (!sourceArray.empty() && !casterArray.empty())) { + for (const auto & source : sourceArray) + for (const auto & caster : casterArray) { + ShadowConf sc; + sc.source = source; + sc.caster = caster; + _shadowConfArray.push_back(sc); + } + _shadowEnabled = true; + } + } + } +} + +RenderablePlanet::~RenderablePlanet() { +} + +bool RenderablePlanet::initialize() { + RenderEngine& renderEngine = OsEng.renderEngine(); + + GLenum err; + while ((err = glGetError()) != GL_NO_ERROR) { + const GLubyte * errString = gluErrorString(err); + std::stringstream ss; + ss << "Checking System State. OpenGL error: " << errString << std::endl; + LERROR(ss.str()); + } + + if (_programObject == nullptr && _shadowEnabled && _hasNightTexture) { + // shadow program + _programObject = renderEngine.buildRenderProgram( + "shadowNightProgram", + "${MODULE_SPACE}/shaders/shadow_nighttexture_vs.glsl", + "${MODULE_SPACE}/shaders/shadow_nighttexture_fs.glsl"); + if (!_programObject) + return false; + } + else if (_programObject == nullptr && _shadowEnabled) { + // shadow program + _programObject = renderEngine.buildRenderProgram( + "shadowProgram", + "${MODULE_SPACE}/shaders/shadow_vs.glsl", + "${MODULE_SPACE}/shaders/shadow_fs.glsl"); + if (!_programObject) + return false; + } + else if (_programObject == nullptr && _hasNightTexture) { + // Night texture program + _programObject = renderEngine.buildRenderProgram( + "nightTextureProgram", + "${MODULE_SPACE}/shaders/nighttexture_vs.glsl", + "${MODULE_SPACE}/shaders/nighttexture_fs.glsl"); + if (!_programObject) + return false; + } + else if (_programObject == nullptr) { + // pscstandard + _programObject = renderEngine.buildRenderProgram( + "pscstandard", + "${MODULE_SPACE}/shaders/renderableplanet_vs.glsl", + "${MODULE_SPACE}/shaders/renderableplanet_fs.glsl"); + if (!_programObject) + return false; + } + using IgnoreError = ghoul::opengl::ProgramObject::IgnoreError; + _programObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); + _programObject->setIgnoreUniformLocationError(IgnoreError::Yes); + + while ((err = glGetError()) != GL_NO_ERROR) { + const GLubyte * errString = gluErrorString(err); + std::stringstream ss; + ss << "Error after load shading programs. OpenGL error: " << errString << std::endl; + LERROR(ss.str()); + } + + loadTexture(); + + while ((err = glGetError()) != GL_NO_ERROR) { + const GLubyte * errString = gluErrorString(err); + std::stringstream ss; + ss << "Error loading textures. OpenGL error: " << errString << std::endl; + LERROR(ss.str()); + } + + _geometry->initialize(this); + + _programObject->deactivate(); + + while ((err = glGetError()) != GL_NO_ERROR) { + const GLubyte * errString = gluErrorString(err); + LERROR("Shader Programs Creation. OpenGL error: " << errString); + } + + return isReady(); +} + +bool RenderablePlanet::deinitialize() { + if(_geometry) { + _geometry->deinitialize(); + delete _geometry; + } + + RenderEngine& renderEngine = OsEng.renderEngine(); + if (_programObject) { + renderEngine.removeRenderProgram(_programObject); + _programObject = nullptr; + } + + _geometry = nullptr; + _texture = nullptr; + _nightTexture = nullptr; + + return true; +} + +bool RenderablePlanet::isReady() const { + bool ready = true; + ready &= (_programObject != nullptr); + ready &= (_texture != nullptr); + ready &= (_geometry != nullptr); + return ready; +} + +void RenderablePlanet::render(const RenderData& data) { + // activate shader + _programObject->activate(); + + glm::dmat4 modelTransform = + glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * // Translation + glm::dmat4(data.modelTransform.rotation) * // Spice rotation + glm::dmat4(glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale))); + + // scale the planet to appropriate size since the planet is a unit sphere + //glm::mat4 transform = glm::mat4(1); + + //earth needs to be rotated for that to work. + glm::dmat4 rot = glm::rotate(glm::dmat4(1.0), M_PI_2, glm::dvec3(1, 0, 0)); + glm::dmat4 roty = glm::rotate(glm::dmat4(1.0), M_PI_2, glm::dvec3(0, -1, 0)); + //glm::dmat4 rotProp = glm::rotate(glm::dmat4(1.0), glm::radians(static_cast(_rotation)), glm::dvec3(0, 1, 0)); + modelTransform = modelTransform * rot * roty /** rotProp*/; + + glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() * modelTransform; + + _programObject->setUniform("transparency", _alpha); + _programObject->setUniform( + "modelViewProjectionTransform", + data.camera.projectionMatrix() * glm::mat4(modelViewTransform) + ); + _programObject->setUniform("ModelTransform", glm::mat4(modelTransform)); + + // Normal Transformation + glm::mat4 translateObjTrans = glm::translate(glm::mat4(1.0), data.position.vec3()); + glm::mat4 translateCamTrans = glm::translate(glm::mat4(1.0), -data.camera.position().vec3()); + float scaleFactor = data.camera.scaling().x * powf(10.0, data.camera.scaling().y); + glm::mat4 scaleCamTrans = glm::scale(glm::mat4(1.0), glm::vec3(scaleFactor)); + + glm::mat4 ModelViewTrans = data.camera.viewMatrix() * scaleCamTrans * + translateCamTrans * translateObjTrans * glm::mat4(modelTransform); + + setPscUniforms(*_programObject.get(), data.camera, data.position); + + _programObject->setUniform("_performShading", _performShading); + + _programObject->setUniform("_hasHeightMap", _hasHeightTexture); + _programObject->setUniform("_heightExaggeration", _heightExaggeration); + + // Bind texture + ghoul::opengl::TextureUnit dayUnit; + ghoul::opengl::TextureUnit nightUnit; + ghoul::opengl::TextureUnit heightUnit; + + + dayUnit.activate(); + _texture->bind(); + _programObject->setUniform("texture1", dayUnit); + + // Bind possible night texture + if (_hasNightTexture) { + nightUnit.activate(); + _nightTexture->bind(); + _programObject->setUniform("nightTex", nightUnit); + } + + if (_hasHeightTexture) { + heightUnit.activate(); + _heightMapTexture->bind(); + _programObject->setUniform("heightTex", heightUnit); + } + + glEnable(GL_CULL_FACE); + glCullFace(GL_BACK); + + // TODO: Move Calculations to VIEW SPACE (precision problems avoidance...) + + double lt; + // Shadow calculations.. + if (!_shadowConfArray.empty()) { + std::vector shadowDataArray; + shadowDataArray.reserve(_shadowConfArray.size()); + + for (const auto & shadowConf : _shadowConfArray) { + // TO REMEMBER: all distances and lengths in world coordinates are in meters!!! We need to move this to view space... + // Getting source and caster: + glm::dvec3 sourcePos = SpiceManager::ref().targetPosition(shadowConf.source.first, "SUN", "GALACTIC", {}, _time, lt); + sourcePos *= 1000.0; // converting to meters + glm::dvec3 casterPos = SpiceManager::ref().targetPosition(shadowConf.caster.first, "SUN", "GALACTIC", {}, _time, lt); + casterPos *= 1000.0; // converting to meters + psc caster_pos = PowerScaledCoordinate::CreatePowerScaledCoordinate(casterPos.x, casterPos.y, casterPos.z); + + + // First we determine if the caster is shadowing the current planet (all calculations in World Coordinates): + glm::vec3 planetCasterVec = (caster_pos - data.position).vec3(); + glm::vec3 sourceCasterVec = glm::vec3(casterPos - sourcePos); + float sc_length = glm::length(sourceCasterVec); + glm::vec3 planetCaster_proj = (glm::dot(planetCasterVec, sourceCasterVec) / (sc_length*sc_length)) * sourceCasterVec; + float d_test = glm::length(planetCasterVec - planetCaster_proj); + float xp_test = shadowConf.caster.second * sc_length / (shadowConf.source.second + shadowConf.caster.second); + float rp_test = shadowConf.caster.second * (glm::length(planetCaster_proj) + xp_test) / xp_test; + + float casterDistSun = glm::length(casterPos); + float planetDistSun = glm::length(data.position.vec3()); + + ShadowRenderingStruct shadowData; + shadowData.isShadowing = false; + + if (((d_test - rp_test) < _planetRadius) && + (casterDistSun < planetDistSun) ) { + // The current caster is shadowing the current planet + shadowData.isShadowing = true; + shadowData.rs = shadowConf.source.second; + shadowData.rc = shadowConf.caster.second; + shadowData.sourceCasterVec = sourceCasterVec; + shadowData.xp = xp_test; + shadowData.xu = shadowData.rc * sc_length / (shadowData.rs - shadowData.rc); + shadowData.casterPositionVec = glm::vec3(casterPos); + } + shadowDataArray.push_back(shadowData); + } + + const std::string uniformVarName("shadowDataArray["); + unsigned int counter = 0; + for (const auto & sd : shadowDataArray) { + std::stringstream ss; + ss << uniformVarName << counter << "].isShadowing"; + _programObject->setUniform(ss.str(), sd.isShadowing); + if (sd.isShadowing) { + ss.str(std::string()); + ss << uniformVarName << counter << "].xp"; + _programObject->setUniform(ss.str(), sd.xp); + ss.str(std::string()); + ss << uniformVarName << counter << "].xu"; + _programObject->setUniform(ss.str(), sd.xu); + /*ss.str(std::string()); + ss << uniformVarName << counter << "].rs"; + _programObject->setUniform(ss.str(), sd.rs);*/ + ss.str(std::string()); + ss << uniformVarName << counter << "].rc"; + _programObject->setUniform(ss.str(), sd.rc); + ss.str(std::string()); + ss << uniformVarName << counter << "].sourceCasterVec"; + _programObject->setUniform(ss.str(), sd.sourceCasterVec); + ss.str(std::string()); + ss << uniformVarName << counter << "].casterPositionVec"; + _programObject->setUniform(ss.str(), sd.casterPositionVec); + } + counter++; + } + } + + // render + _geometry->render(); + + // disable shader + _programObject->deactivate(); + +} + +void RenderablePlanet::update(const UpdateData& data) { + // set spice-orientation in accordance to timestamp + _stateMatrix = data.modelTransform.rotation; + //_stateMatrix = SpiceManager::ref().positionTransformMatrix(_frame, "GALACTIC", data.time); + _time = data.time; +} + +void RenderablePlanet::loadTexture() { + _texture = nullptr; + if (_colorTexturePath.value() != "") { + _texture = std::move(ghoul::io::TextureReader::ref().loadTexture(absPath(_colorTexturePath))); + if (_texture) { + if (_texture->numberOfChannels() == 1) { + _texture->setSwizzleMask({ GL_RED, GL_RED, GL_RED, GL_RED }); + } + + LDEBUG("Loaded texture from '" << _colorTexturePath << "'"); + _texture->uploadTexture(); + + // Textures of planets looks much smoother with AnisotropicMipMap rather than linear + // TODO: AnisotropicMipMap crashes on ATI cards ---abock + //_texture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); + _texture->setFilter(ghoul::opengl::Texture::FilterMode::Linear); + } + } + + GLenum err; + while ((err = glGetError()) != GL_NO_ERROR) { + const GLubyte * errString = gluErrorString(err); + LERROR("Error after reading color texture. OpenGL error: " << errString); + } + + if (_hasNightTexture) { + _nightTexture = nullptr; + if (_nightTexturePath.value() != "") { + _nightTexture = std::move(ghoul::io::TextureReader::ref().loadTexture(absPath(_nightTexturePath))); + if (_nightTexture) { + LDEBUG("Loaded texture from '" << _nightTexturePath << "'"); + _nightTexture->uploadTexture(); + _nightTexture->setFilter(ghoul::opengl::Texture::FilterMode::Linear); + //_nightTexture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); + } + } + } + + while ((err = glGetError()) != GL_NO_ERROR) { + const GLubyte * errString = gluErrorString(err); + LERROR("Error after reading night texture. OpenGL error: " << errString); + } + + if (_hasHeightTexture) { + _heightMapTexture = nullptr; + if (_heightMapTexturePath.value() != "") { + _heightMapTexture = std::move(ghoul::io::TextureReader::ref().loadTexture(absPath(_heightMapTexturePath))); + if (_heightMapTexture) { + LDEBUG("Loaded texture from '" << _heightMapTexturePath << "'"); + _heightMapTexture->uploadTexture(); + _heightMapTexture->setFilter(ghoul::opengl::Texture::FilterMode::Linear); + //_nightTexture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); + } + } + } + + while ((err = glGetError()) != GL_NO_ERROR) { + const GLubyte * errString = gluErrorString(err); + LERROR("Error after reading height mapping texture. OpenGL error: " << errString); + } +} + +} // namespace openspace diff --git a/modules/base/rendering/renderabletrailnew.h b/modules/space/rendering/renderableplanet.h similarity index 54% rename from modules/base/rendering/renderabletrailnew.h rename to modules/space/rendering/renderableplanet.h index fe469892d9..4c324cda3c 100644 --- a/modules/base/rendering/renderabletrailnew.h +++ b/modules/space/rendering/renderableplanet.h @@ -22,95 +22,95 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERABLETRAILNEW_H__ -#define __RENDERABLETRAILNEW_H__ +#ifndef __OPENSPACE_MODULE_SPACE___RENDERABLEPLANET___H__ +#define __OPENSPACE_MODULE_SPACE___RENDERABLEPLANET___H__ #include + #include -#include +#include +#include +#include +#include -#include +#include -#include +#include +#include namespace ghoul { -namespace opengl { - class ProgramObject; - class Texture; -} + namespace opengl { + class ProgramObject; + class Texture; + } } namespace openspace { -/** - * This class currently has a temporary name until it is merged with or replaces - * RenderableTrail. It renders the trail with higher precision close to the - * position of the body of a renderable. The lua mod dictionary describing the - * renderable trail is changed. -*/ -class RenderableTrailNew : public Renderable { +namespace planetgeometry { +class PlanetGeometry; +} + +class RenderablePlanet : public Renderable { public: - explicit RenderableTrailNew(const ghoul::Dictionary& dictionary); + // Shadow structure + typedef struct { + std::pair source; + std::pair caster; + } ShadowConf; + + struct ShadowRenderingStruct { + float xu, xp; + float rs, rc; + glm::vec3 sourceCasterVec; + glm::vec3 casterPositionVec; + bool isShadowing; + }; + +public: + explicit RenderablePlanet(const ghoul::Dictionary& dictionary); + ~RenderablePlanet(); bool initialize() override; bool deinitialize() override; - bool isReady() const override; void render(const RenderData& data) override; void update(const UpdateData& data) override; +protected: + void loadTexture(); private: - void sweepTimeRange(); - - void initializeGlobalOpenGLPathData(); - void initializeLocalOpenGLPathData(); - - void deInitializeGlobalOpenGLPathData(); - void deInitializeLocalOpenGLPathData(); - - void preRender(int totalNumVerticesToDraw); - void preRenderSubPathGlobally(const RenderData& renderData); - void preRenderSubPathLocally(const RenderData& renderData, int totalNumVerticesToDraw); - - void renderLines(GLuint vao, int numberOfVertices); - void renderPoints(GLuint vao, int numberOfVertices); + properties::StringProperty _colorTexturePath; + properties::StringProperty _nightTexturePath; + properties::StringProperty _heightMapTexturePath; - // Spice - std::string _body; - std::string _observer; - std::string _frame; - - // Properties - properties::Vec3Property _lineColor; - properties::Vec3Property _pointColor; - properties::FloatProperty _lineFade; - properties::FloatProperty _lineWidth; - properties::FloatProperty _renderPart; - properties::BoolProperty _showTimeStamps; - properties::BoolProperty _renderFullTrail; - - // OpenGL - GLuint _vaoGlobalID; - GLuint _vBufferGlobalID; - - GLuint _vaoLocalID; - GLuint _vBufferLocalID; - - // Other - bool _successfullDictionaryFetch; - TimeRange _timeRange; - double _sampleDeltaTime; - int _subSamples; std::unique_ptr _programObject; - std::vector _vertexPositionArray; - // Data updated in update function - double _currentTimeClamped; // Time clamped to time range - glm::dmat4 _modelTransform; - glm::dvec3 _clampedBodyPosition; // Position of body clamped to time range + std::unique_ptr _texture; + std::unique_ptr _nightTexture; + std::unique_ptr _heightMapTexture; + + properties::FloatProperty _heightExaggeration; + + planetgeometry::PlanetGeometry* _geometry; + properties::BoolProperty _performShading; + properties::IntProperty _rotation; + float _alpha; + std::vector< ShadowConf > _shadowConfArray; + float _planetRadius; + + glm::dmat3 _stateMatrix; + std::string _frame; + std::string _target; + bool _hasNightTexture; + bool _hasHeightTexture; + bool _shadowEnabled; + double _time; + + bool tempPic; }; -} // namespace openspace +} // namespace openspace -#endif // __RENDERABLETRAILNEW_H__ +#endif // __OPENSPACE_MODULE_SPACE___RENDERABLEPLANET___H__ diff --git a/modules/base/rendering/renderablerings.cpp b/modules/space/rendering/renderablerings.cpp similarity index 53% rename from modules/base/rendering/renderablerings.cpp rename to modules/space/rendering/renderablerings.cpp index bc3da200cd..75c3f8c08a 100644 --- a/modules/base/rendering/renderablerings.cpp +++ b/modules/space/rendering/renderablerings.cpp @@ -22,11 +22,12 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include +#include +#include #include #include -#include +#include #include #include @@ -35,25 +36,56 @@ #include namespace { - const std::string _loggerCat = "RenderableRings"; - - const std::string KeySize = "Size"; - const std::string KeyTexture = "Texture"; - const std::string KeyBody = "Body"; - const std::string KeyFrame = "Frame"; - const std::string KeyOrientation = "Orientation"; - const std::string KeyOffset = "Offset"; - const std::string KeyNightFactor = "NightFactor"; - const std::string KeyTransparency = "Transparency"; + const char* KeyTexture = "Texture"; + const char* KeySize = "Size"; + const char* KeyOffset = "Offset"; } namespace openspace { +Documentation RenderableRings::Documentation() { + using namespace documentation; + return { + "Renderable Rings", + "space_renderable_rings", + { + { + "Type", + new StringEqualVerifier("RenderableRings"), + "", + Optional::No + }, + { + KeyTexture, + new StringVerifier, + "The one dimensional texture that is used for both sides of the ring.", + Optional::No + }, + { + KeySize, + new DoubleVerifier, + "The radius of the rings in meters.", + Optional::No + }, + { + KeyOffset, + new DoubleVector2Verifier, + "The offset that is used to limit the width of the rings. Each of the " + "two values is a value between 0 and 1, where 0 is the center of the " + "ring and 1 is the maximum extent at the radius. If this value is, for " + "example {0.5, 1.0}, the ring is only shown between radius/2 and radius. " + "It defaults to {0.0, 1.0}.", + Optional::Yes + } + } + }; +} + RenderableRings::RenderableRings(const ghoul::Dictionary& dictionary) : Renderable(dictionary) , _texturePath("texture", "Texture") - , _size("size", "Size", glm::vec2(1.f, 1.f), glm::vec2(0.f), glm::vec2(1.f, 25.f)) - , _offset("offset", "Texture Offset", glm::vec2(0.f, 1.f), glm::vec2(0.f), glm::vec2(1.f)) + , _size("size", "Size", 1.f, 0.f, std::pow(1.f, 25.f)) + , _offset("offset", "Offset", glm::vec2(0, 1.f), glm::vec2(0.f), glm::vec2(1.f)) , _nightFactor("nightFactor", "Night Factor", 0.33f, 0.f, 1.f) , _transparency("transparency", "Transparency", 0.15f, 0.f, 1.f) , _shader(nullptr) @@ -63,62 +95,36 @@ RenderableRings::RenderableRings(const ghoul::Dictionary& dictionary) , _quad(0) , _vertexPositionBuffer(0) , _planeIsDirty(false) - , _hasSunPosition(false) { - glm::vec2 size; - dictionary.getValue(KeySize, size); - _size = size; - - if (dictionary.hasKeyAndValue(KeyBody)) { - _body = dictionary.value(KeyBody); - _hasSunPosition = true; - } - - if (dictionary.hasKeyAndValue(KeyFrame)) { - _frame = dictionary.value(KeyFrame); - } - - if (dictionary.hasKeyAndValue(KeyOrientation)) { - _orientation = dictionary.value(KeyOrientation); - } + using ghoul::filesystem::File; + + documentation::testSpecificationAndThrow( + Documentation(), + dictionary, + "RenderableRings" + ); + + _size = dictionary.value(KeySize); + setBoundingSphere(PowerScaledScalar::CreatePSS(_size)); + addProperty(_size); + _size.onChange([&]() { _planeIsDirty = true; }); + + _texturePath = absPath(dictionary.value(KeyTexture)); + _textureFile = std::make_unique(_texturePath); - if (dictionary.hasKeyAndValue(KeyTexture)) { - _texturePath = absPath(dictionary.value(KeyTexture)); - _textureFile = std::make_unique(_texturePath); - } - if (dictionary.hasKeyAndValue(KeyOffset)) { - glm::vec2 off = dictionary.value(KeyOffset); - _offset = off; + _offset = dictionary.value(KeyOffset); } - - if (dictionary.hasKeyAndValue(KeyNightFactor)) { - float v = dictionary.value(KeyNightFactor); - _nightFactor = v; - } - - if (dictionary.hasKeyAndValue(KeyTransparency)) { - float v = dictionary.value(KeyTransparency); - _transparency = v; - } - addProperty(_offset); - addProperty(_size); - _size.onChange([&](){ _planeIsDirty = true; }); addProperty(_texturePath); _texturePath.onChange([&](){ loadTexture(); }); - _textureFile->setCallback( - [&](const ghoul::filesystem::File&) { _textureIsDirty = true; } - ); + _textureFile->setCallback([&](const File&) { _textureIsDirty = true; }); addProperty(_nightFactor); - addProperty(_transparency); - - setBoundingSphere(_size.value()); } bool RenderableRings::isReady() const { @@ -129,21 +135,17 @@ bool RenderableRings::initialize() { if (!_shader) { RenderEngine& renderEngine = OsEng.renderEngine(); _shader = renderEngine.buildRenderProgram("RingProgram", - "${MODULE_BASE}/shaders/rings_vs.glsl", - "${MODULE_BASE}/shaders/rings_fs.glsl" + "${MODULE_SPACE}/shaders/rings_vs.glsl", + "${MODULE_SPACE}/shaders/rings_fs.glsl" ); - if (!_shader) - return false; - _shader->setIgnoreUniformLocationError( ghoul::opengl::ProgramObject::IgnoreError::Yes ); } - glGenVertexArrays(1, &_quad); // generate array - glGenBuffers(1, &_vertexPositionBuffer); // generate buffer + glGenVertexArrays(1, &_quad); + glGenBuffers(1, &_vertexPositionBuffer); createPlane(); - loadTexture(); return isReady(); @@ -159,11 +161,8 @@ bool RenderableRings::deinitialize() { _textureFile = nullptr; _texture = nullptr; - RenderEngine& renderEngine = OsEng.renderEngine(); - if (_shader) { - renderEngine.removeRenderProgram(_shader); - _shader = nullptr; - } + OsEng.renderEngine().removeRenderProgram(_shader); + _shader = nullptr; return true; } @@ -171,18 +170,27 @@ bool RenderableRings::deinitialize() { void RenderableRings::render(const RenderData& data) { _shader->activate(); - _shader->setUniform("ViewProjection", data.camera.viewProjectionMatrix()); - _shader->setUniform("ModelTransform", glm::mat4(_orientation * _state)); + glm::dmat4 modelTransform = + glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * + glm::dmat4(data.modelTransform.rotation) * + glm::dmat4(glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale))); + + glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() * modelTransform; + + _shader->setUniform( + "modelViewProjectionTransform", + data.camera.projectionMatrix() * glm::mat4(modelViewTransform) + ); _shader->setUniform("textureOffset", _offset); _shader->setUniform("transparency", _transparency); - _shader->setUniform("hasSunPosition", _hasSunPosition); - if (_hasSunPosition) { - _shader->setUniform("_nightFactor", _nightFactor); - _shader->setUniform("sunPosition", _sunPosition); - } + _shader->setUniform("_nightFactor", _nightFactor); + _shader->setUniform( + "sunPosition", + _sunPosition + ); - setPscUniforms(*_shader.get(), data.camera, data.position); + setPscUniforms(*_shader, data.camera, data.position); ghoul::opengl::TextureUnit unit; unit.activate(); @@ -212,37 +220,26 @@ void RenderableRings::update(const UpdateData& data) { loadTexture(); _textureIsDirty = false; } - - if (!_frame.empty()) { - _state = SpiceManager::ref().positionTransformMatrix(_frame, "GALACTIC", data.time); - } - - if (!_body.empty()) { - double lt; - _sunPosition = SpiceManager::ref().targetPosition( - "SUN", - _body, - "GALACTIC", - {}, - data.time, - lt - ); - } + + _sunPosition = OsEng.renderEngine().scene()->sceneGraphNode("Sun")->worldPosition() - + data.modelTransform.translation; } void RenderableRings::loadTexture() { if (_texturePath.value() != "") { - std::unique_ptr texture = ghoul::io::TextureReader::ref().loadTexture(absPath(_texturePath)); + std::unique_ptr texture = + ghoul::io::TextureReader::ref().loadTexture(absPath(_texturePath)); + if (texture) { - LDEBUG("Loaded texture from '" << absPath(_texturePath) << "'"); + LDEBUGC( + "RenderableRings", + "Loaded texture from '" << absPath(_texturePath) << "'" + ); _texture = std::move(texture); - // Textures of planets looks much smoother with AnisotropicMipMap rather than linear -// _texture->setFilter(ghoul::opengl::Texture::FilterMode::Linear); _texture->uploadTexture(); _texture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); - _textureFile = std::make_unique(_texturePath); _textureFile->setCallback( [&](const ghoul::filesystem::File&) { _textureIsDirty = true; } @@ -252,28 +249,45 @@ void RenderableRings::loadTexture() { } void RenderableRings::createPlane() { - // ============================ - // GEOMETRY (quad) - // ============================ - const GLfloat size = _size.value()[0]; - const GLfloat w = _size.value()[1]; - const GLfloat vertex_data[] = { - // x y z w s t - -size, -size, 0.f, w, 0.f, 0.f, - size, size, 0.f, w, 1.f, 1.f, - -size, size, 0.f, w, 0.f, 1.f, - -size, -size, 0.f, w, 0.f, 0.f, - size, -size, 0.f, w, 1.f, 0.f, - size, size, 0.f, w, 1.f, 1.f, + const GLfloat size = _size.value(); + + struct VertexData { + GLfloat x; + GLfloat y; + GLfloat s; + GLfloat t; + }; + + VertexData data[] = { + -size, -size, 0.f, 0.f, + size, size, 1.f, 1.f, + -size, size, 0.f, 1.f, + -size, -size, 0.f, 0.f, + size, -size, 1.f, 0.f, + size, size, 1.f, 1.f, }; - glBindVertexArray(_quad); // bind array - glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); // bind buffer - glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW); + glBindVertexArray(_quad); + glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); + glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_STATIC_DRAW); glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, reinterpret_cast(0)); + glVertexAttribPointer( + 0, + 2, + GL_FLOAT, + GL_FALSE, + sizeof(VertexData), + reinterpret_cast(0) + ); glEnableVertexAttribArray(1); - glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, reinterpret_cast(sizeof(GLfloat) * 4)); + glVertexAttribPointer( + 1, + 2, + GL_FLOAT, + GL_FALSE, + sizeof(VertexData), + reinterpret_cast(offsetof(VertexData, s)) + ); } } // namespace openspace diff --git a/modules/base/rendering/renderablerings.h b/modules/space/rendering/renderablerings.h similarity index 88% rename from modules/base/rendering/renderablerings.h rename to modules/space/rendering/renderablerings.h index 1836404e71..2df2c64a21 100644 --- a/modules/base/rendering/renderablerings.h +++ b/modules/space/rendering/renderablerings.h @@ -22,13 +22,15 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERABLERINGS_H__ -#define __RENDERABLERINGS_H__ +#ifndef __OPENSPACE_MODULE_SPACE___RENDERABLERINGS___H__ +#define __OPENSPACE_MODULE_SPACE___RENDERABLERINGS___H__ #include +#include #include -#include +#include +#include #include namespace ghoul { @@ -42,6 +44,7 @@ namespace ghoul { } namespace openspace { + class RenderableRings : public Renderable { public: RenderableRings(const ghoul::Dictionary& dictionary); @@ -54,12 +57,14 @@ public: void render(const RenderData& data) override; void update(const UpdateData& data) override; + static openspace::Documentation Documentation(); + private: void loadTexture(); void createPlane(); properties::StringProperty _texturePath; - properties::Vec2Property _size; + properties::FloatProperty _size; properties::Vec2Property _offset; properties::FloatProperty _nightFactor; properties::FloatProperty _transparency; @@ -72,16 +77,10 @@ private: GLuint _quad; GLuint _vertexPositionBuffer; bool _planeIsDirty; - - std::string _frame; - glm::mat3 _orientation; - glm::mat3 _state; - - std::string _body; + glm::vec3 _sunPosition; - bool _hasSunPosition; }; } // namespace openspace -#endif // __RENDERABLERINGS_H__ +#endif // __OPENSPACE_MODULE_SPACE___RENDERABLERINGS___H__ diff --git a/modules/base/rendering/renderablestars.cpp b/modules/space/rendering/renderablestars.cpp similarity index 82% rename from modules/base/rendering/renderablestars.cpp rename to modules/space/rendering/renderablestars.cpp index addbbe2a9b..108bb4639b 100644 --- a/modules/base/rendering/renderablestars.cpp +++ b/modules/space/rendering/renderablestars.cpp @@ -22,8 +22,9 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include +#include +#include #include #include #include @@ -31,6 +32,8 @@ #include #include #include +#include +#include #include #include @@ -38,14 +41,11 @@ #include namespace { - const std::string _loggerCat = "RenderableStars"; + static const std::string _loggerCat = "RenderableStars"; - const std::string KeyFile = "File"; - const std::string KeyTexture = "Texture"; - const std::string KeyColorMap = "ColorMap"; - - ghoul::filesystem::File* _psfTextureFile; - ghoul::filesystem::File* _colorTextureFile; + const char* KeyFile = "File"; + const char* KeyTexture = "Texture"; + const char* KeyColorMap = "ColorMap"; const int8_t CurrentCacheVersion = 1; @@ -82,6 +82,46 @@ namespace { namespace openspace { +openspace::Documentation RenderableStars::Documentation() { + using namespace documentation; + return { + "RenderableStars", + "space_renderablestars", + { + { + "Type", + new StringEqualVerifier("RenderableStars"), + "", + Optional::No + }, + { + KeyFile, + new StringVerifier, + "The path to the SPECK file that contains information about the stars " + "being rendered.", + Optional::No + }, + { + KeyTexture, + new StringVerifier, + "The path to the texture that should be used as a point spread function " + "for the stars. The path is relative to the location of the .mod file " + "and can contain file system token.", + Optional::No + }, + { + KeyColorMap, + new StringVerifier, + "The path to the texture that is used to convert from the B-V value of " + "the star to its color. The texture is used as a one dimensional lookup " + "function.", + Optional::No + } + } + }; +} + + RenderableStars::RenderableStars(const ghoul::Dictionary& dictionary) : Renderable(dictionary) , _pointSpreadFunctionTexturePath("psfTexture", "Point Spread Function Texture") @@ -90,7 +130,11 @@ RenderableStars::RenderableStars(const ghoul::Dictionary& dictionary) , _colorTexturePath("colorTexture", "ColorBV Texture") , _colorTexture(nullptr) , _colorTextureIsDirty(true) - , _colorOption("colorOption", "Color Option") + , _colorOption( + "colorOption", + "Color Option", + properties::OptionProperty::DisplayType::Dropdown + ) , _dataIsDirty(true) , _alphaValue("alphaValue", "Transparency", 1.f, 0.f, 1.f) , _scaleFactor("scaleFactor", "Scale Factor", 1.f, 0.f, 10.f) @@ -101,47 +145,54 @@ RenderableStars::RenderableStars(const ghoul::Dictionary& dictionary) , _vao(0) , _vbo(0) { - using ghoul::filesystem::File; + using File = ghoul::filesystem::File; - std::string texturePath = ""; - dictionary.getValue(KeyTexture, texturePath); - _pointSpreadFunctionTexturePath = absPath(texturePath); - _psfTextureFile = new File(_pointSpreadFunctionTexturePath); + documentation::testSpecificationAndThrow( + Documentation(), + dictionary, + "RenderableStars" + ); - dictionary.getValue(KeyColorMap, texturePath); - _colorTexturePath = absPath(texturePath); - _colorTextureFile = new File(_colorTexturePath); + _pointSpreadFunctionTexturePath = absPath(dictionary.value(KeyTexture)); + _pointSpreadFunctionFile = std::make_unique(_pointSpreadFunctionTexturePath); - bool success = dictionary.getValue(KeyFile, _speckFile); - if (!success) { - LERROR("SpeckDataSource did not contain key '" << KeyFile << "'"); - return; - } - _speckFile = absPath(_speckFile); + _colorTexturePath = absPath(dictionary.value(KeyColorMap)); + _colorTextureFile = std::make_unique(_colorTexturePath); + _speckFile = absPath(dictionary.value(KeyFile)); + + //_colorOption.addOptions({ + // { ColorOption::Color, "Color" }, + // { ColorOption::Velocity, "Velocity" }, + // { ColorOption::Speed, "Speed" } + //}); _colorOption.addOption(ColorOption::Color, "Color"); _colorOption.addOption(ColorOption::Velocity, "Velocity"); _colorOption.addOption(ColorOption::Speed, "Speed"); addProperty(_colorOption); + _colorOption.onChange([&]{ _dataIsDirty = true;}); addProperty(_pointSpreadFunctionTexturePath); - _pointSpreadFunctionTexturePath.onChange([&]{ _pointSpreadFunctionTextureIsDirty = true; }); - _psfTextureFile->setCallback([&](const File&) { _pointSpreadFunctionTextureIsDirty = true; }); + _pointSpreadFunctionTexturePath.onChange( + [&]{ _pointSpreadFunctionTextureIsDirty = true; } + ); + _pointSpreadFunctionFile->setCallback( + [&](const File&) { _pointSpreadFunctionTextureIsDirty = true; } + ); addProperty(_colorTexturePath); _colorTexturePath.onChange([&]{ _colorTextureIsDirty = true; }); - _colorTextureFile->setCallback([&](const File&) { _colorTextureIsDirty = true; }); + _colorTextureFile->setCallback( + [&](const File&) { _colorTextureIsDirty = true; } + ); addProperty(_alphaValue); addProperty(_scaleFactor); addProperty(_minBillboardSize); } -RenderableStars::~RenderableStars() { - delete _psfTextureFile; - delete _colorTextureFile; -} +RenderableStars::~RenderableStars() {} bool RenderableStars::isReady() const { return (_program != nullptr) && (!_fullData.empty()); @@ -152,12 +203,13 @@ bool RenderableStars::initialize() { RenderEngine& renderEngine = OsEng.renderEngine(); _program = renderEngine.buildRenderProgram("Star", - "${MODULE_BASE}/shaders/star_vs.glsl", - "${MODULE_BASE}/shaders/star_fs.glsl", - "${MODULE_BASE}/shaders/star_ge.glsl"); + "${MODULE_SPACE}/shaders/star_vs.glsl", + "${MODULE_SPACE}/shaders/star_fs.glsl", + "${MODULE_SPACE}/shaders/star_ge.glsl"); - if (!_program) + if (!_program) { return false; + } completeSuccess &= loadData(); completeSuccess &= (_pointSpreadFunctionTexture != nullptr); @@ -205,20 +257,19 @@ void RenderableStars::render(const RenderData& data) { _program->setUniform("alphaValue", _alphaValue); _program->setUniform("scaleFactor", _scaleFactor); _program->setUniform("minBillboardSize", _minBillboardSize); + _program->setUniform("screenSize", glm::vec2(OsEng.renderEngine().renderingResolution())); setPscUniforms(*_program.get(), data.camera, data.position); _program->setUniform("scaling", scaling); ghoul::opengl::TextureUnit psfUnit; psfUnit.activate(); - if (_pointSpreadFunctionTexture) - _pointSpreadFunctionTexture->bind(); + _pointSpreadFunctionTexture->bind(); _program->setUniform("psfTexture", psfUnit); ghoul::opengl::TextureUnit colorUnit; colorUnit.activate(); - if (_colorTexture) - _colorTexture->bind(); + _colorTexture->bind(); _program->setUniform("colorTexture", colorUnit); glBindVertexArray(_vao); @@ -252,10 +303,12 @@ void RenderableStars::update(const UpdateData& data) { } glBindVertexArray(_vao); glBindBuffer(GL_ARRAY_BUFFER, _vbo); - glBufferData(GL_ARRAY_BUFFER, - size*sizeof(GLfloat), + glBufferData( + GL_ARRAY_BUFFER, + size * sizeof(GLfloat), &_slicedData[0], - GL_STATIC_DRAW); + GL_STATIC_DRAW + ); GLint positionAttrib = _program->attributeLocation("in_position"); GLint brightnessDataAttrib = _program->attributeLocation("in_brightness"); @@ -315,17 +368,27 @@ void RenderableStars::update(const UpdateData& data) { LDEBUG("Reloading Point Spread Function texture"); _pointSpreadFunctionTexture = nullptr; if (_pointSpreadFunctionTexturePath.value() != "") { - _pointSpreadFunctionTexture = std::move(ghoul::io::TextureReader::ref().loadTexture(absPath(_pointSpreadFunctionTexturePath))); + _pointSpreadFunctionTexture = std::move( + ghoul::io::TextureReader::ref().loadTexture( + absPath(_pointSpreadFunctionTexturePath) + ) + ); if (_pointSpreadFunctionTexture) { - LDEBUG("Loaded texture from '" << absPath(_pointSpreadFunctionTexturePath) << "'"); + LDEBUG("Loaded texture from '" << + absPath(_pointSpreadFunctionTexturePath) << "'"); _pointSpreadFunctionTexture->uploadTexture(); } _pointSpreadFunctionTexture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); - delete _psfTextureFile; - _psfTextureFile = new ghoul::filesystem::File(_pointSpreadFunctionTexturePath); - _psfTextureFile->setCallback([&](const ghoul::filesystem::File&) { _pointSpreadFunctionTextureIsDirty = true; }); + _pointSpreadFunctionFile = std::make_unique( + _pointSpreadFunctionTexturePath + ); + _pointSpreadFunctionFile->setCallback( + [&](const ghoul::filesystem::File&) { + _pointSpreadFunctionTextureIsDirty = true; + } + ); } _pointSpreadFunctionTextureIsDirty = false; } @@ -340,9 +403,12 @@ void RenderableStars::update(const UpdateData& data) { _colorTexture->uploadTexture(); } - delete _colorTextureFile; - _colorTextureFile = new ghoul::filesystem::File(_colorTexturePath); - _colorTextureFile->setCallback([&](const ghoul::filesystem::File&) { _colorTextureIsDirty = true; }); + _colorTextureFile = std::make_unique( + _colorTexturePath + ); + _colorTextureFile->setCallback( + [&](const ghoul::filesystem::File&) { _colorTextureIsDirty = true; } + ); } _colorTextureIsDirty = false; } @@ -360,12 +426,14 @@ bool RenderableStars::loadData() { LINFO("Cached file '" << cachedFile << "' used for Speck file '" << _file << "'"); bool success = loadCachedFile(cachedFile); - if (success) + if (success) { return true; - else + } + else { FileSys.cacheManager()->removeCacheFile(_file); // Intentional fall-through to the 'else' computation to generate the cache // file for the next run + } } else { LINFO("Cache for Speck file '" << _file << "' not found"); @@ -373,8 +441,9 @@ bool RenderableStars::loadData() { LINFO("Loading Speck file '" << _file << "'"); bool success = readSpeckFile(); - if (!success) + if (!success) { return false; + } LINFO("Saving cache"); success = saveCachedFile(cachedFile); @@ -400,8 +469,9 @@ bool RenderableStars::readSpeckFile() { std::ifstream::streampos position = file.tellg(); std::getline(file, line); - if (line[0] == '#' || line.empty()) + if (line[0] == '#' || line.empty()) { continue; + } if (line.substr(0, 7) != "datavar" && line.substr(0, 10) != "texturevar" && @@ -436,8 +506,9 @@ bool RenderableStars::readSpeckFile() { std::getline(file, line); std::stringstream str(line); - for (int i = 0; i < _nValuesPerStar; ++i) + for (int i = 0; i < _nValuesPerStar; ++i) { str >> values[i]; + } _fullData.insert(_fullData.end(), values.begin(), values.end()); } while (!file.eof()); diff --git a/modules/base/rendering/renderablestars.h b/modules/space/rendering/renderablestars.h similarity index 86% rename from modules/base/rendering/renderablestars.h rename to modules/space/rendering/renderablestars.h index 945e82871f..69e24517b3 100644 --- a/modules/base/rendering/renderablestars.h +++ b/modules/space/rendering/renderablestars.h @@ -22,19 +22,29 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERABLESTARS_H__ -#define __RENDERABLESTARS_H__ +#ifndef __OPENSPACE_MODULE_SPACE___RENDERABLESTARS___H__ +#define __OPENSPACE_MODULE_SPACE___RENDERABLESTARS___H__ #include + +#include #include #include -#include +#include -#include -#include +namespace ghoul { +namespace filesystem { +class File; +} +} namespace openspace { +namespace opengl { +class ProgramObject; +class Texture; +} + class RenderableStars : public Renderable { public: explicit RenderableStars(const ghoul::Dictionary& dictionary); @@ -48,6 +58,8 @@ public: void render(const RenderData& data) override; void update(const UpdateData& data) override; + static openspace::Documentation Documentation(); + private: enum ColorOption { Color = 0, @@ -64,10 +76,12 @@ private: properties::StringProperty _pointSpreadFunctionTexturePath; std::unique_ptr _pointSpreadFunctionTexture; + std::unique_ptr _pointSpreadFunctionFile; bool _pointSpreadFunctionTextureIsDirty; properties::StringProperty _colorTexturePath; std::unique_ptr _colorTexture; + std::unique_ptr _colorTextureFile; bool _colorTextureIsDirty; properties::OptionProperty _colorOption; @@ -91,4 +105,4 @@ private: } // namespace openspace -#endif // __RENDERABLESTARS_H__ \ No newline at end of file +#endif // __OPENSPACE_MODULE_SPACE___RENDERABLESTARS___H__ diff --git a/modules/base/rendering/simplespheregeometry.cpp b/modules/space/rendering/simplespheregeometry.cpp similarity index 97% rename from modules/base/rendering/simplespheregeometry.cpp rename to modules/space/rendering/simplespheregeometry.cpp index 36ac52afb5..468bc6403f 100644 --- a/modules/base/rendering/simplespheregeometry.cpp +++ b/modules/space/rendering/simplespheregeometry.cpp @@ -22,7 +22,7 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include +#include #include #include @@ -34,8 +34,8 @@ namespace openspace { namespace constants { namespace simplespheregeometry { -const std::string keyRadius = "Radius"; -const std::string keySegments = "Segments"; + const char* keyRadius = "Radius"; + const char* keySegments = "Segments"; } // namespace simplespheregeometry } diff --git a/modules/base/rendering/simplespheregeometry.h b/modules/space/rendering/simplespheregeometry.h similarity index 86% rename from modules/base/rendering/simplespheregeometry.h rename to modules/space/rendering/simplespheregeometry.h index 1b752a2b48..c9b38220f2 100644 --- a/modules/base/rendering/simplespheregeometry.h +++ b/modules/space/rendering/simplespheregeometry.h @@ -22,12 +22,13 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SIMPLESPHEREGEOMETRY_H__ -#define __SIMPLESPHEREGEOMETRY_H__ +#ifndef __OPENSPACE_MODULE_SPACE___SIMPLESPHEREGEOMETRY___H__ +#define __OPENSPACE_MODULE_SPACE___SIMPLESPHEREGEOMETRY___H__ -#include -#include -#include +#include + +#include +#include namespace openspace { @@ -58,7 +59,7 @@ private: PowerScaledSphere* _sphere; }; -} // namespace planetgeometry -} // namespace openspace +} // namespace planetgeometry +} // namespace openspace -#endif // __SIMPLESPHEREGEOMETRY_H__ +#endif // __OPENSPACE_MODULE_SPACE___SIMPLESPHEREGEOMETRY___H__ diff --git a/modules/space/rotation/spicerotation.cpp b/modules/space/rotation/spicerotation.cpp new file mode 100644 index 0000000000..d6efccae16 --- /dev/null +++ b/modules/space/rotation/spicerotation.cpp @@ -0,0 +1,131 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include + +namespace { + const std::string _loggerCat = "SpiceRotation"; + //const std::string keyGhosting = "EphmerisGhosting"; + + const char* KeySourceFrame = "SourceFrame"; + const char* KeyDestinationFrame = "DestinationFrame"; + const char* KeyKernels = "Kernels"; +} + +namespace openspace { + +Documentation SpiceRotation::Documentation() { + using namespace openspace::documentation; + return { + "Spice Rotation", + "space_transform_rotation_spice", + { + { + "Type", + new StringEqualVerifier("SpiceRotation"), + "", + Optional::No + }, + { + KeySourceFrame, + new StringAnnotationVerifier("A valid SPICE NAIF name or integer"), + "The source frame that is used as the basis for the coordinate " + "transformation. This has to be a valid SPICE name.", + Optional::No + }, + { + KeyDestinationFrame, + new StringAnnotationVerifier("A valid SPICE NAIF name or integer"), + "The destination frame that is used for the coordinate transformation. " + "This has to be a valid SPICE name.", + Optional::No + }, + { + KeyKernels, + new OrVerifier( + new TableVerifier({ + { "*", new StringVerifier } + }), + new StringVerifier + ), + "A single kernel or list of kernels that this SpiceTranslation depends " + "on. All provided kernels will be loaded before any other operation is " + "performed.", + Optional::Yes + } + } + }; +} + +SpiceRotation::SpiceRotation(const ghoul::Dictionary& dictionary) + : _sourceFrame("source", "Source", "") + , _destinationFrame("destination", "Destination", "") +{ + documentation::testSpecificationAndThrow( + Documentation(), + dictionary, + "SpiceRotation" + ); + + _sourceFrame = dictionary.value(KeySourceFrame); + _destinationFrame = dictionary.value(KeyDestinationFrame); + + if (dictionary.hasKeyAndValue(KeyKernels)) { + SpiceManager::ref().loadKernel(dictionary.value(KeyKernels)); + } + else if (dictionary.hasKeyAndValue(KeyKernels)) { + ghoul::Dictionary kernels = dictionary.value(KeyKernels); + for (size_t i = 1; i <= kernels.size(); ++i) { + if (!kernels.hasKeyAndValue(std::to_string(i))) { + throw ghoul::RuntimeError("Kernels has to be an array-style table"); + } + + std::string kernel = kernels.value(std::to_string(i)); + SpiceManager::ref().loadKernel(kernel); + } + } + + addProperty(_sourceFrame); + addProperty(_destinationFrame); +} + +void SpiceRotation::update(const UpdateData& data) { + try { + _matrix = SpiceManager::ref().positionTransformMatrix( + _sourceFrame, + _destinationFrame, + data.time + ); + } + catch (...) { + _matrix = glm::dmat3(1.0); + } +} + +} // namespace openspace diff --git a/modules/base/rotation/spicerotation.h b/modules/space/rotation/spicerotation.h similarity index 83% rename from modules/base/rotation/spicerotation.h rename to modules/space/rotation/spicerotation.h index 034ff7fece..94a1ec0101 100644 --- a/modules/base/rotation/spicerotation.h +++ b/modules/space/rotation/spicerotation.h @@ -22,26 +22,28 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SPICEROTATION_H__ -#define __SPICEROTATION_H__ +#ifndef __OPENSPACE_MODULE_SPACE___SPICEROTATION___H__ +#define __OPENSPACE_MODULE_SPACE___SPICEROTATION___H__ #include +#include +#include namespace openspace { class SpiceRotation : public Rotation { public: SpiceRotation(const ghoul::Dictionary& dictionary); - virtual const glm::dmat3& matrix() const; + const glm::dmat3& matrix() const; void update(const UpdateData& data) override; + static openspace::Documentation Documentation(); + private: - std::string _sourceFrame; - std::string _destinationFrame; - glm::dmat3 _rotationMatrix; - bool _kernelsLoadedSuccessfully; + properties::StringProperty _sourceFrame; + properties::StringProperty _destinationFrame; }; } // namespace openspace -#endif // __SPICEROTATION_H__ +#endif // __OPENSPACE_MODULE_SPACE___SPICEROTATION___H__ diff --git a/modules/base/shaders/constellationbounds_fs.glsl b/modules/space/shaders/constellationbounds_fs.glsl similarity index 100% rename from modules/base/shaders/constellationbounds_fs.glsl rename to modules/space/shaders/constellationbounds_fs.glsl diff --git a/modules/base/shaders/constellationbounds_vs.glsl b/modules/space/shaders/constellationbounds_vs.glsl similarity index 100% rename from modules/base/shaders/constellationbounds_vs.glsl rename to modules/space/shaders/constellationbounds_vs.glsl diff --git a/modules/base/shaders/nighttexture_fs.glsl b/modules/space/shaders/nighttexture_fs.glsl similarity index 97% rename from modules/base/shaders/nighttexture_fs.glsl rename to modules/space/shaders/nighttexture_fs.glsl index dd527d5537..94175a9f7b 100644 --- a/modules/base/shaders/nighttexture_fs.glsl +++ b/modules/space/shaders/nighttexture_fs.glsl @@ -45,8 +45,6 @@ in vec4 test; #include "fragment.glsl" Fragment getFragment() { - vec4 position = vs_position; - float depth = pscDepth(position); vec4 diffuse = texture(texture1, vs_st); vec4 diffuse2 = texture(nightTex, vs_st); @@ -76,7 +74,7 @@ Fragment getFragment() { diffuse[3] = transparency; frag.color = diffuse; - frag.depth = depth; + frag.depth = vs_position.w; return frag; } diff --git a/modules/base/shaders/nighttexture_vs.glsl b/modules/space/shaders/nighttexture_vs.glsl similarity index 92% rename from modules/base/shaders/nighttexture_vs.glsl rename to modules/space/shaders/nighttexture_vs.glsl index e278611ebb..8056fd63ad 100644 --- a/modules/base/shaders/nighttexture_vs.glsl +++ b/modules/space/shaders/nighttexture_vs.glsl @@ -36,27 +36,23 @@ out vec2 vs_st; out vec4 vs_normal; out vec4 vs_position; -uniform mat4 ViewProjection; uniform mat4 ModelTransform; +uniform mat4 modelViewProjectionTransform; uniform sampler2D heightTex; uniform bool _hasHeightMap; uniform float _heightExaggeration; - -void main() -{ +void main() { // set variables vs_st = in_st; - vs_position = in_position; vec4 tmp = in_position; // this is wrong for the normal. The normal transform is the transposed inverse of the model transform vs_normal = normalize(ModelTransform * vec4(in_normal,0)); // vs_normal = vec4(in_normal, 0.0); - vec4 position = pscTransform(tmp, ModelTransform); - vs_position = tmp; + vec4 position = vec4(tmp.xyz * pow(10, tmp. w), 1.0); if (_hasHeightMap) { float height = texture(heightTex, in_st).r; @@ -64,8 +60,9 @@ void main() float displacementFactor = height * _heightExaggeration; position.xyz = position.xyz + displacementDirection * displacementFactor; } -// - position = ViewProjection * position; + + position = modelViewProjectionTransform * position; + vs_position = z_normalization(position); - gl_Position = z_normalization(position); + gl_Position = vs_position; } \ No newline at end of file diff --git a/modules/space/shaders/renderableplanet_fs.glsl b/modules/space/shaders/renderableplanet_fs.glsl new file mode 100644 index 0000000000..f275091d76 --- /dev/null +++ b/modules/space/shaders/renderableplanet_fs.glsl @@ -0,0 +1,82 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +uniform vec4 campos; +uniform vec4 objpos; +//uniform vec3 camdir; // add this for specular + +uniform vec3 sun_pos; + +uniform bool _performShading = true; +uniform float transparency; +uniform int shadows; + +uniform float time; +uniform sampler2D texture1; + +in vec2 vs_st; +in vec4 vs_normal; +in vec4 vs_position; + +#include "fragment.glsl" +#include "PowerScaling/powerScaling_fs.hglsl" + +//#include "PowerScaling/powerScaling_vs.hglsl" +Fragment getFragment() { + vec4 diffuse = texture(texture1, vs_st); + + Fragment frag; + if (_performShading) { + // directional lighting + vec3 origin = vec3(0.0); + vec4 spec = vec4(0.0); + + vec3 n = normalize(vs_normal.xyz); + //vec3 e = normalize(camdir); + vec3 l_pos = vec3(sun_pos); // sun. + vec3 l_dir = normalize(l_pos-objpos.xyz); + float intensity = min(max(5*dot(n,l_dir), 0.0), 1); + + float shine = 0.0001; + + vec4 specular = vec4(0.5); + vec4 ambient = vec4(0.0,0.0,0.0,transparency); + /* + if(intensity > 0.f){ + // halfway vector + vec3 h = normalize(l_dir + e); + // specular factor + float intSpec = max(dot(h,n),0.0); + spec = specular * pow(intSpec, shine); + } + */ + diffuse = max(intensity * diffuse, ambient); + } + + diffuse[3] = transparency; + frag.color = diffuse; + frag.depth = vs_position.w; + + return frag; +} diff --git a/modules/base/shaders/ephemeris_vs.glsl b/modules/space/shaders/renderableplanet_vs.glsl similarity index 72% rename from modules/base/shaders/ephemeris_vs.glsl rename to modules/space/shaders/renderableplanet_vs.glsl index 5339a6321a..e726d0149a 100644 --- a/modules/base/shaders/ephemeris_vs.glsl +++ b/modules/space/shaders/renderableplanet_vs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * Copyright (c) 2014 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -24,28 +24,35 @@ #version __CONTEXT__ -uniform mat4 modelViewTransform; -uniform mat4 projectionTransform; -uniform vec4 objectVelocity; +uniform mat4 ModelTransform; +uniform mat4 modelViewProjectionTransform; -uniform uint nVertices; -uniform float lineFade; +layout(location = 0) in vec4 in_position; +//in vec3 in_position; +layout(location = 1) in vec2 in_st; +layout(location = 2) in vec3 in_normal; -layout(location = 0) in vec4 in_point_position; - -out vec4 vs_positionScreenSpace; -out float fade; +out vec2 vs_st; +out vec4 vs_normal; +out vec4 vs_position; +out float s; #include "PowerScaling/powerScaling_vs.hglsl" void main() { - float id = float(gl_VertexID) / float(nVertices * lineFade); - fade = 1.0 - id; + // set variables + vs_st = in_st; + vec4 tmp = in_position; - // Convert from psc to regular homogenous coordinates - vec4 position = vec4(in_point_position.xyz * pow(10, in_point_position.w), 1); - vec4 positionClipSpace = projectionTransform * modelViewTransform * position; - vs_positionScreenSpace = z_normalization(positionClipSpace); + // this is wrong for the normal. The normal transform is the transposed inverse of the model transform + vs_normal = normalize(ModelTransform * vec4(in_normal,0)); + // vs_normal = vec4(in_normal, 0.0); - gl_Position = vs_positionScreenSpace; + vec4 position = vec4(tmp.xyz * pow(10, tmp.w), 1.0); + position = modelViewProjectionTransform * position; + + vs_position = z_normalization(position); + + + gl_Position = vs_position; } \ No newline at end of file diff --git a/modules/base/shaders/rings_fs.glsl b/modules/space/shaders/rings_fs.glsl similarity index 82% rename from modules/base/shaders/rings_fs.glsl rename to modules/space/shaders/rings_fs.glsl index 8a7c237de3..6de4b8503f 100644 --- a/modules/base/shaders/rings_fs.glsl +++ b/modules/space/shaders/rings_fs.glsl @@ -37,9 +37,6 @@ uniform vec3 sunPosition; uniform float _nightFactor; Fragment getFragment() { - vec4 position = vs_position; - float depth = pscDepth(position); - // Moving the origin to the center vec2 st = (vs_st - vec2(0.5)) * 2.0; @@ -66,28 +63,26 @@ Fragment getFragment() { diffuse.a = pow(colorValue / (3*transparency), 1); } - if (hasSunPosition) { - // The normal for the one plane depends on whether we are dealing - // with a front facing or back facing fragment - vec3 normal; - // The plane is oriented on the xz plane - // WARNING: This might not be the case for Uranus - if (gl_FrontFacing) { - normal = vec3(-1.0, 0.0, 0.0); - } - else { - normal = vec3(1.0, 0.0, 0.0); - } - - // Reduce the color of the fragment by the user factor - // if we are facing away from the Sun - if (dot(sunPosition, normal) < 0) - diffuse.xyz *= _nightFactor; + // The normal for the one plane depends on whether we are dealing + // with a front facing or back facing fragment + vec3 normal; + // The plane is oriented on the xz plane + // WARNING: This might not be the case for Uranus + if (gl_FrontFacing) { + normal = vec3(-1.0, 0.0, 0.0); } + else { + normal = vec3(1.0, 0.0, 0.0); + } + + // Reduce the color of the fragment by the user factor + // if we are facing away from the Sun + if (dot(sunPosition, normal) < 0) + diffuse.xyz *= _nightFactor; Fragment frag; frag.color = diffuse; - frag.depth = depth; + frag.depth = vs_position.w; return frag; } diff --git a/modules/base/shaders/rings_vs.glsl b/modules/space/shaders/rings_vs.glsl similarity index 82% rename from modules/base/shaders/rings_vs.glsl rename to modules/space/shaders/rings_vs.glsl index b1299f30ce..86ecefef8e 100644 --- a/modules/base/shaders/rings_vs.glsl +++ b/modules/space/shaders/rings_vs.glsl @@ -26,22 +26,30 @@ #include "PowerScaling/powerScaling_vs.hglsl" -layout(location = 0) in vec4 in_position; +layout(location = 0) in vec2 in_position; layout(location = 1) in vec2 in_st; out vec2 vs_st; out vec4 vs_position; -uniform mat4 ViewProjection; -uniform mat4 ModelTransform; +uniform mat4 modelViewProjectionTransform; void main() { - vec4 tmp = in_position; - vec4 position = pscTransform(tmp, ModelTransform); - - vs_position = tmp; vs_st = in_st; + + vs_position = z_normalization( + modelViewProjectionTransform * vec4(in_position.xy, 0.0, 1.0) + ); + gl_Position = vs_position; + + // vec4 tmp = in_position; + + + // vec4 tmp = in_position; + // vec4 position = pscTransform(tmp, ModelTransform); + + // vs_position = tmp; - position = ViewProjection * position; - gl_Position = z_normalization(position); + // position = ViewProjection * position; + // gl_Position = z_normalization(position); } diff --git a/modules/base/shaders/shadow_fs.glsl b/modules/space/shaders/shadow_fs.glsl similarity index 100% rename from modules/base/shaders/shadow_fs.glsl rename to modules/space/shaders/shadow_fs.glsl diff --git a/modules/base/shaders/shadow_nighttexture_fs.glsl b/modules/space/shaders/shadow_nighttexture_fs.glsl similarity index 100% rename from modules/base/shaders/shadow_nighttexture_fs.glsl rename to modules/space/shaders/shadow_nighttexture_fs.glsl diff --git a/modules/base/shaders/shadow_nighttexture_vs.glsl b/modules/space/shaders/shadow_nighttexture_vs.glsl similarity index 100% rename from modules/base/shaders/shadow_nighttexture_vs.glsl rename to modules/space/shaders/shadow_nighttexture_vs.glsl diff --git a/modules/base/shaders/shadow_vs.glsl b/modules/space/shaders/shadow_vs.glsl similarity index 100% rename from modules/base/shaders/shadow_vs.glsl rename to modules/space/shaders/shadow_vs.glsl diff --git a/modules/base/shaders/star_fs.glsl b/modules/space/shaders/star_fs.glsl similarity index 100% rename from modules/base/shaders/star_fs.glsl rename to modules/space/shaders/star_fs.glsl diff --git a/modules/base/shaders/star_ge.glsl b/modules/space/shaders/star_ge.glsl similarity index 97% rename from modules/base/shaders/star_ge.glsl rename to modules/space/shaders/star_ge.glsl index 09af7ddecf..0315797b0a 100644 --- a/modules/base/shaders/star_ge.glsl +++ b/modules/space/shaders/star_ge.glsl @@ -53,6 +53,7 @@ uniform mat4 projection; uniform float scaleFactor; uniform float minBillboardSize; +uniform vec2 screenSize; void main() { if ((psc_position[0].x == 0.0) && (psc_position[0].y == 0.0) && (psc_position[0].z == 0.0)) @@ -75,7 +76,6 @@ void main() { // Calculate the positions of the lower left and upper right corners of the // billboard in screen-space - const vec2 screenSize = vec2(#{rendererData.windowWidth}, #{rendererData.windowHeight}); vec2 ll = (((projPos[1].xy / projPos[1].w) + 1) / 2) * screenSize; vec2 ur = (((projPos[2].xy / projPos[2].w) + 1) / 2) * screenSize; diff --git a/modules/base/shaders/star_vs.glsl b/modules/space/shaders/star_vs.glsl similarity index 100% rename from modules/base/shaders/star_vs.glsl rename to modules/space/shaders/star_vs.glsl diff --git a/modules/space/spacemodule.cpp b/modules/space/spacemodule.cpp new file mode 100644 index 0000000000..48cb89e9ff --- /dev/null +++ b/modules/space/spacemodule.cpp @@ -0,0 +1,91 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +namespace openspace { + +SpaceModule::SpaceModule() + : OpenSpaceModule("Space") +{} + +void SpaceModule::internalInitialize() { + FactoryManager::ref().addFactory( + std::make_unique>(), + "PlanetGeometry" + ); + + auto fRenderable = FactoryManager::ref().factory(); + ghoul_assert(fRenderable, "Renderable factory was not created"); + + fRenderable->registerClass("RenderableConstellationBounds"); + fRenderable->registerClass("RenderablePlanet"); + fRenderable->registerClass("RenderableRings"); + fRenderable->registerClass("RenderableStars"); + + auto fTranslation = FactoryManager::ref().factory(); + ghoul_assert(fTranslation, "Ephemeris factory was not created"); + + fTranslation->registerClass("KeplerTranslation"); + fTranslation->registerClass("SpiceTranslation"); + fTranslation->registerClass("TLETranslation"); + + auto fRotation = FactoryManager::ref().factory(); + ghoul_assert(fRotation, "Rotation factory was not created"); + + fRotation->registerClass("SpiceRotation"); + + auto fPlanetGeometry = FactoryManager::ref().factory(); + ghoul_assert(fPlanetGeometry, "Planet geometry factory was not created"); + fPlanetGeometry->registerClass("SimpleSphere"); +} + +std::vector SpaceModule::documentations() const { + return { + SpiceRotation::Documentation(), + SpiceTranslation::Documentation(), + RenderableRings::Documentation(), + planetgeometry::PlanetGeometry::Documentation() + }; +} + +} // namespace openspace diff --git a/modules/base/shaders/hdr.glsl b/modules/space/spacemodule.h similarity index 82% rename from modules/base/shaders/hdr.glsl rename to modules/space/spacemodule.h index 4435f301b5..02bb96f1c1 100644 --- a/modules/base/shaders/hdr.glsl +++ b/modules/space/spacemodule.h @@ -21,15 +21,24 @@ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ - -uniform float exposure; -vec4 HDR(vec4 color) { - color *= exposure; +#ifndef __OPENSPACE_MODULE_SPACE___BASEMODULE___H__ +#define __OPENSPACE_MODULE_SPACE___BASEMODULE___H__ + +#include + +namespace openspace { + +class SpaceModule : public OpenSpaceModule { +public: + SpaceModule(); - color.r = color.r < 1.413 ? pow(color.r * 0.38317, 1.0 / 2.2) : 1.0 - exp(-color.r); - color.g = color.g < 1.413 ? pow(color.g * 0.38317, 1.0 / 2.2) : 1.0 - exp(-color.g); - color.b = color.b < 1.413 ? pow(color.b * 0.38317, 1.0 / 2.2) : 1.0 - exp(-color.b); - - return color; -} + std::vector documentations() const override; + +protected: + void internalInitialize() override; +}; + +} // namespace openspace + +#endif // __OPENSPACE_MODULE_SPACE___BASEMODULE___H__ diff --git a/modules/space/translation/keplertranslation.cpp b/modules/space/translation/keplertranslation.cpp new file mode 100644 index 0000000000..eb184ee198 --- /dev/null +++ b/modules/space/translation/keplertranslation.cpp @@ -0,0 +1,377 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include + +#include + +namespace { + const char* KeyEccentricity = "Eccentricity"; + const char* KeySemiMajorAxis = "SemiMajorAxis"; + const char* KeyInclination = "Inclination"; + const char* KeyAscendingNode = "AscendingNode"; + const char* KeyArgumentOfPeriapsis = "ArgumentOfPeriapsis"; + const char* KeyMeanAnomaly = "MeanAnomaly"; + const char* KeyEpoch = "Epoch"; + const char* KeyPeriod = "Period"; + + +template +T solveIteration(Func function, T x0, const T& err = 0.0, int maxIterations = 100) { + T x = 0; + T x2 = x0; + + for (int i = 0; i < maxIterations; ++i) { + x = x2; + x2 = function(x); + if (abs(x2 - x) < err) { + return x2; + } + } + + return x2; +} +} // namespace + +namespace openspace { + +KeplerTranslation::RangeError::RangeError(std::string offender) + : ghoul::RuntimeError("Value '" + offender + "' out of range", "KeplerTranslation") + , offender(std::move(offender)) +{} + +Documentation KeplerTranslation::Documentation() { + using namespace openspace::documentation; + return{ + "Kepler Translation", + "space_transform_kepler", + { + { + "Type", + new StringEqualVerifier("KeplerTranslation"), + "", + Optional::No + }, + { + KeyEccentricity, + new DoubleInRangeVerifier(0.0, 1.0), + "Specifies the eccentricity of the orbit; currently, OpenSpace does not " + "support hyperbolic orbits using Keplerian elements.", + Optional::No + }, + { + KeySemiMajorAxis, + new DoubleVerifier, + "Specifies the semi-major axis of the orbit in kilometers (semi-major " + "axis = average of periapsis and apoapsis).", + Optional::No + }, + { + KeyInclination, + new DoubleInRangeVerifier(0.0, 360.0), + "Specifies the inclination angle (degrees) of the orbit relative to the " + "reference plane (in the case of Earth, the equatorial plane.", + Optional::No + }, + { + KeyAscendingNode, + new DoubleInRangeVerifier(0.0, 360.0), + "Specifies the right ascension of the ascending node (in degrees!) " + "relative to the vernal equinox.", + Optional::No + }, + { + KeyArgumentOfPeriapsis, + new DoubleInRangeVerifier(0.0, 360.0), + "Specifies the argument of periapsis as angle (in degrees) from the " + "ascending.", + Optional::No + }, + { + KeyMeanAnomaly, + new DoubleInRangeVerifier(0.0, 360.0), + "Specifies the position of the orbiting body (in degrees) along the " + "elliptical orbit at epoch time.", + Optional::No + }, + { + KeyEpoch, + new StringVerifier, + "Specifies the epoch time used for position as a string of the form: " + "YYYY MM DD HH:mm:ss", + Optional::No + }, + { + KeyPeriod, + new DoubleGreaterVerifier(0.0), + "Specifies the orbital period (in seconds).", + Optional::No + }, + }, + Exhaustive::Yes + }; +} + +KeplerTranslation::KeplerTranslation() + : Translation() + , _eccentricity("eccentricity", "Eccentricity", 0.0, 0.0, 1.0) + , _semiMajorAxis("semimajorAxis", "Semi-major axis", 0.0, 0.0, 1e6) + , _inclination("inclination", "Inclination", 0.0, 0.0, 360.0) + , _ascendingNode( + "ascendingNode", + "Right ascension of ascending Node", + 0.0, + 0.0, + 360.0 + ) + , _argumentOfPeriapsis( + "argumentOfPeriapsis", + "Argument of Periapsis", + 0.0, + 0.0, + 360.0 + ) + , _meanAnomalyAtEpoch("meanAnomalyAtEpoch", "Mean anomaly at epoch", 0.0, 0.0, 360.0) + , _epoch("epoch", "Epoch", 0.0, 0.0, 1e9) + , _period("period", "Orbit period", 0.0, 0.0, 1e6) + , _orbitPlaneDirty(true) +{ + auto update = [this]() { + _orbitPlaneDirty = true; + }; + + // Only the eccentricity, semimajor axis, inclination, and location of ascending node + // invalidate the shape of the orbit. The other parameters only determine the location + // the spacecraft on that orbit + _eccentricity.onChange(update); + addProperty(_eccentricity); + + _semiMajorAxis.onChange(update); + addProperty(_semiMajorAxis); + + _inclination.onChange(update); + addProperty(_inclination); + + _ascendingNode.onChange(update); + addProperty(_ascendingNode); + + _argumentOfPeriapsis.onChange(update); + addProperty(_argumentOfPeriapsis); + + addProperty(_meanAnomalyAtEpoch); + addProperty(_epoch); + addProperty(_period); +} + +KeplerTranslation::KeplerTranslation(const ghoul::Dictionary& dictionary) + : KeplerTranslation() +{ + documentation::testSpecificationAndThrow( + Documentation(), + dictionary, + "KeplerTranslation" + ); + + setKeplerElements( + dictionary.value(KeyEccentricity), + dictionary.value(KeySemiMajorAxis), + dictionary.value(KeyInclination), + dictionary.value(KeyAscendingNode), + dictionary.value(KeyArgumentOfPeriapsis), + dictionary.value(KeyMeanAnomaly), + dictionary.value(KeyPeriod), + dictionary.value(KeyEpoch) + ); +} + +glm::dvec3 KeplerTranslation::position() const { + return _position; +} + +double KeplerTranslation::eccentricAnomaly(double meanAnomaly) const { + // Compute the eccentric anomaly (the location of the spacecraft taking the + // eccentricity of the orbit into account) using different solves for the regimes in + // which they are most efficient + + if (_eccentricity == 0.0) { + // In a circular orbit, the eccentric anomaly = mean anomaly + return meanAnomaly; + } + else if (_eccentricity < 0.2) { + auto solver = [this, &meanAnomaly](double x) -> double { + // For low eccentricity, using a first order solver sufficient + return meanAnomaly + _eccentricity * sin(x); + }; + return solveIteration(solver, meanAnomaly, 0.0, 5); + } + else if (_eccentricity < 0.9) { + auto solver = [this, &meanAnomaly](double x) -> double { + double e = _eccentricity; + return x + (meanAnomaly + e * sin(x) - x) / (1.0 - e * cos(x)); + }; + return solveIteration(solver, meanAnomaly, 0.0, 6); + } + else if (_eccentricity < 1.0) { + auto sign = [](double val) -> double { + return val > 0.0 ? 1.0 : ((val < 0.0) ? -1.0 : 0.0); + }; + double e = meanAnomaly + 0.85 * _eccentricity * sign(sin(meanAnomaly)); + + auto solver = [this, &meanAnomaly, &sign](double x) -> double { + double e = _eccentricity; + double s = e * sin(x); + double c = e * cos(x); + double f = x - s - meanAnomaly; + double f1 = 1 - c; + double f2 = s; + return x + (-5 * f / (f1 + sign(f1) * sqrt(abs(16 * f1 * f1 - 20 * f * f2)))); + }; + return solveIteration(solver, e, 0.0, 8); + } +} + +void KeplerTranslation::update(const UpdateData& data) { + if (_orbitPlaneDirty) { + computeOrbitPlane(); + _orbitPlaneDirty = false; + } + + double t = data.time - _epoch; + double meanMotion = 2.0 * glm::pi() / _period; + double meanAnomaly = glm::radians(_meanAnomalyAtEpoch.value()) + t * meanMotion; + double e = eccentricAnomaly(meanAnomaly); + + // Use the eccentric anomaly to compute the actual location + double a = _semiMajorAxis / (1.0 - _eccentricity) * 1000.0; + glm::dvec3 p = { + a * (cos(e) - _eccentricity), + a * sqrt(1.0 - _eccentricity * _eccentricity) * sin(e), + 0.0 + }; + _position = _orbitPlaneRotation * p; +} + +void KeplerTranslation::computeOrbitPlane() { + // We assume the following coordinate system: + // z = axis of rotation + // x = pointing towards the first point of Aries + // y completes the righthanded coordinate system + + // Perform three rotations: + // 1. Around the z axis to place the location of the ascending node + // 2. Around the x axis (now aligned with the ascending node) to get the correct + // inclination + // 3. Around the new z axis to place the closest approach to the correct location + + const glm::vec3 ascendingNodeAxisRot = { 0.f, 0.f, 1.f }; + const glm::vec3 inclinationAxisRot = { 1.f, 0.f, 0.f }; + const glm::vec3 argPeriapsisAxisRot = { 0.f, 0.f, 1.f }; + + const double asc = glm::radians(_ascendingNode.value()); + const double inc = glm::radians(_inclination.value()); + const double per = glm::radians(_argumentOfPeriapsis.value()); + + _orbitPlaneRotation = + glm::rotate(asc, glm::dvec3(ascendingNodeAxisRot)) * + glm::rotate(inc, glm::dvec3(inclinationAxisRot)) * + glm::rotate(per, glm::dvec3(argPeriapsisAxisRot)); + + notifyObservers(); + _orbitPlaneDirty = false; +} + +void KeplerTranslation::setKeplerElements(double eccentricity, double semiMajorAxis, + double inclination, double ascendingNode, + double argumentOfPeriapsis, + double meanAnomalyAtEpoch, + double orbitalPeriod, const std::string& epoch) +{ + setKeplerElements( + eccentricity, + semiMajorAxis, + inclination, + ascendingNode, + argumentOfPeriapsis, + meanAnomalyAtEpoch, + orbitalPeriod, + SpiceManager::ref().ephemerisTimeFromDate(epoch) + ); +} + +void KeplerTranslation::setKeplerElements(double eccentricity, double semiMajorAxis, + double inclination, double ascendingNode, + double argumentOfPeriapsis, + double meanAnomalyAtEpoch, + double orbitalPeriod, double epoch) +{ + auto isInRange = [](double val, double min, double max) -> bool { + return val >= min && val <= max; + }; + + if (isInRange(eccentricity, 0.0, 1.0)) { + _eccentricity = eccentricity; + } + else { + throw RangeError("Eccentricity"); + } + + _semiMajorAxis = semiMajorAxis; + + if (isInRange(inclination, 0.0, 360.0)) { + _inclination = inclination; + } + else { + throw RangeError("Inclination"); + } + + if (isInRange(_ascendingNode, 0.0, 360.0)) { + _ascendingNode = ascendingNode; + } + else { + throw RangeError("Ascending Node"); + } + if (isInRange(_argumentOfPeriapsis, 0.0, 360.0)) { + _argumentOfPeriapsis = argumentOfPeriapsis; + } + else { + throw RangeError("Argument of Periapsis"); + } + + if (isInRange(_meanAnomalyAtEpoch, 0.0, 360.0)) { + _meanAnomalyAtEpoch = meanAnomalyAtEpoch; + } + else { + throw RangeError("Mean anomaly at epoch"); + } + + _period = orbitalPeriod; + _epoch = epoch; + + computeOrbitPlane(); +} + +} // namespace openspace diff --git a/modules/space/translation/keplertranslation.h b/modules/space/translation/keplertranslation.h new file mode 100644 index 0000000000..8e74394fa0 --- /dev/null +++ b/modules/space/translation/keplertranslation.h @@ -0,0 +1,177 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_SPACE___KEPLERTRANSLATION___H__ +#define __OPENSPACE_MODULE_SPACE___KEPLERTRANSLATION___H__ + +#include + +#include + +#include +#include + +namespace openspace { + +/** + * The KeplerTranslation is a concrete Translation implementation that uses the 6 + * Keplerian elements (eccentricity, semi-major axis, inclination, right ascension of the + * ascending node, argument of periapsis, and mean anomaly at epoch) for computing the + * position of a space craft. So far, only eccentricities between [0, 1) are supoorted. + */ +class KeplerTranslation : public Translation { +public: + struct RangeError : public ghoul::RuntimeError { + explicit RangeError(std::string offender); + + std::string offender; + }; + + /** + * The constructor that retrieves the required Keplerian elements from the passed + * \p dictionary. These values are then apssed to the setKeplerElements method for + * further processing. + * The \p dictionary is tested against the Documentation for conformance. + * \param dictionary The ghoul::Dictionary containing all the information about the + * Keplerian elements (see Documentation) + */ + KeplerTranslation(const ghoul::Dictionary& dictionary); + + /// Default destructor + virtual ~KeplerTranslation() = default; + + /** + * This method returns the position of the object at the time that was passed to the + * last call of the #update method. The KeplerTranslation caches its position, thus + * repeated calls to this function are cheap. + * \return The position of the object at the time of last call to the #update method + */ + virtual glm::dvec3 position() const override; + + /** + * Updates the cached position of the object to correspond to the time passed in the + * \p data. + * \param data The UpdateData struct that contains all information necessary to update + * this Translation + */ + void update(const UpdateData& data) override; + + /** + * Method returning the openspace::Documentation that describes the ghoul::Dictinoary + * that can be passed to the constructor. + * \return The openspace::Documentation that describes the ghoul::Dicitonary that can + * be passed to the constructor + */ + static openspace::Documentation Documentation(); + +protected: + /// Default construct that initializes all the properties and member variables + KeplerTranslation(); + + /** + * Sets the internal values for the Keplerian elements and the epoch as a string of + * the form YYYY MM DD HH:mm:ss. + * \param eccentricity The eccentricity of the orbit + * \param semiMajorAxis The semi-major axis of the orbit + * \param inclination The inclination of the orbit relative to the (x-y) reference + * plane (in the case of J2000, the equator) + * \param ascendingNode The right ascension of the ascending node computed relative + * to the x axis (in the case of J2000, the first point of Aries) + * \param argumentOfPeriapsis The location on the orbit with the closes approach + * \param meanAnomalyAtEpoch The location of the space craft on the orbit at the time + * of the \p epoch + * \param orbitalPeriod The period of the orbit in seconds + * \param epoch The epoch to which the orbit is defined as a string of the form: + * YYYY MM DD HH:mm::ss + */ + void setKeplerElements(double eccentricity, double semiMajorAxis, double inclination, + double ascendingNode, double argumentOfPeriapsis, double meanAnomalyAtEpoch, + double orbitalPeriod, const std::string& epoch + ); + + /** + * Sets the internal values for the Keplerian elements and the epoch as seconds past + * J2000 epoch. + * \param eccentricity The eccentricity of the orbit + * \param semiMajorAxis The semi-major axis of the orbit + * \param inclination The inclination of the orbit relative to the (x-y) reference + * plane (in the case of J2000, the equator) + * \param ascendingNode The right ascension of the ascending node computed relative + * to the x axis (in the case of J2000, the first point of Aries) + * \param argumentOfPeriapsis The location on the orbit with the closes approach + * \param meanAnomalyAtEpoch The location of the space craft on the orbit at the time + * of the \p epoch + * \param orbitalPeriod The period of the orbit in seconds + * \param epoch The epoch to which the orbit is defined as number of seconds past the + * J2000 epoch + */ + void setKeplerElements(double eccentricity, double semiMajorAxis, double inclination, + double ascendingNode, double argumentOfPeriapsis, double meanAnomalyAtEpoch, + double orbitalPeriod, double epoch + ); + +private: + /// Recombutes the rotation matrix used in the update method + void computeOrbitPlane(); + + /** + * This method computes the eccentric anomaly (location of the space craft taking the + * eccentricity into acount) based on the mean anomaly (location of the space craft + * assuming an eccentricity of 0.0) + * \param meanAnomaly The mean anomaly for which the eccentric anomaly shall be + * computed + * \return The eccentric anomaly for the provided \p meanAnomaly + */ + double eccentricAnomaly(double meanAnomaly) const; + + /// The eccentricity of the orbit in [0, 1) + properties::DoubleProperty _eccentricity; + /// The semi-major axis in km + properties::DoubleProperty _semiMajorAxis; + /// The inclination of the orbit in [0, 360] + properties::DoubleProperty _inclination; + /// The right ascension of the ascending node in [0, 360] + properties::DoubleProperty _ascendingNode; + /// The argument of periapsis in [0, 360] + properties::DoubleProperty _argumentOfPeriapsis; + /// The mean anomaly at the epoch in [0, 360] + properties::DoubleProperty _meanAnomalyAtEpoch; + + /// The epoch in seconds relative to the J2000 epoch + properties::DoubleProperty _epoch; + /// The period of the orbit in seconds + properties::DoubleProperty _period; + + /// Dirty flag for the _orbitPlaneRotation parameters + bool _orbitPlaneDirty; + /// The rotation matrix that defines the plane of the orbit + glm::dmat3 _orbitPlaneRotation; + + /// The cached position for the last time with which the update method was called + glm::dvec3 _position; +}; + +} // namespace openspace + +#endif // __OPENSPACE_MODULE_SPACE___KEPLERTRANSLATION___H__ diff --git a/modules/base/ephemeris/spiceephemeris.cpp b/modules/space/translation/spicetranslation.cpp similarity index 77% rename from modules/base/ephemeris/spiceephemeris.cpp rename to modules/space/translation/spicetranslation.cpp index 59d6e6a1b4..7d1d9e451e 100644 --- a/modules/base/ephemeris/spiceephemeris.cpp +++ b/modules/space/translation/spicetranslation.cpp @@ -22,7 +22,7 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include +#include #include #include @@ -32,25 +32,26 @@ #include namespace { - const std::string KeyBody = "Body"; - const std::string KeyObserver = "Observer"; - const std::string KeyKernels = "Kernels"; + const char* KeyBody = "Body"; + const char* KeyObserver = "Observer"; + const char* KeyFrame = "Frame"; + const char* KeyKernels = "Kernels"; - const std::string ReferenceFrame = "GALACTIC"; + const char* DefaultReferenceFrame = "GALACTIC"; } namespace openspace { -Documentation SpiceEphemeris::Documentation() { +Documentation SpiceTranslation::Documentation() { using namespace openspace::documentation; - return { + return{ "Spice Translation", - "base_translation_spicetranslation", + "space_translation_spicetranslation", { { "Type", - new StringEqualVerifier("SpiceEphemeris"), + new StringEqualVerifier("SpiceTranslation"), "", Optional::No }, @@ -71,12 +72,19 @@ Documentation SpiceEphemeris::Documentation() { "integer id code (such as '0').", Optional::No }, + { + KeyFrame, + new StringAnnotationVerifier( + "A valid SPICE NAIF name for a reference frame" + ), + "This is the SPICE NAIF name for the reference frame in which the " + "position should be retrieved. The default value is GALACTIC", + Optional::Yes + }, { KeyKernels, new OrVerifier( - new TableVerifier({ - { "*", new StringVerifier } - }), + new StringListVerifier, new StringVerifier ), "A single kernel or list of kernels that this SpiceTranslation depends " @@ -89,20 +97,25 @@ Documentation SpiceEphemeris::Documentation() { }; } -SpiceEphemeris::SpiceEphemeris(const ghoul::Dictionary& dictionary) +SpiceTranslation::SpiceTranslation(const ghoul::Dictionary& dictionary) : _target("target", "Target", "") , _origin("origin", "Origin", "") + , _frame("frame", "Reference Frame", DefaultReferenceFrame) , _kernelsLoadedSuccessfully(true) { documentation::testSpecificationAndThrow( Documentation(), dictionary, - "SpiceEphemeris" + "SpiceTranslation" ); _target = dictionary.value(KeyBody); _origin = dictionary.value(KeyObserver); + if (dictionary.hasKey(KeyFrame)) { + _frame = dictionary.value(KeyFrame); + } + auto loadKernel = [](const std::string& kernel) { if (!FileSys.fileExists(kernel)) { throw SpiceManager::SpiceException("Kernel '" + kernel + "' does not exist"); @@ -130,16 +143,29 @@ SpiceEphemeris::SpiceEphemeris(const ghoul::Dictionary& dictionary) } } } + + auto update = [this](){ + notifyObservers(); + }; + + _target.onChange(update); + addProperty(_target); + + _origin.onChange(update); + addProperty(_origin); + + _frame.onChange(update); + addProperty(_frame); } -glm::dvec3 SpiceEphemeris::position() const { +glm::dvec3 SpiceTranslation::position() const { return _position; } -void SpiceEphemeris::update(const UpdateData& data) { +void SpiceTranslation::update(const UpdateData& data) { double lightTime = 0.0; _position = SpiceManager::ref().targetPosition( - _target, _origin, ReferenceFrame, {}, data.time, lightTime + _target, _origin, _frame, {}, data.time, lightTime ) * glm::pow(10.0, 3.0); } diff --git a/modules/base/ephemeris/spiceephemeris.h b/modules/space/translation/spicetranslation.h similarity index 87% rename from modules/base/ephemeris/spiceephemeris.h rename to modules/space/translation/spicetranslation.h index 92d9991e1e..d815a4613f 100644 --- a/modules/base/ephemeris/spiceephemeris.h +++ b/modules/space/translation/spicetranslation.h @@ -22,19 +22,19 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __SPICEEPHEMERIS_H__ -#define __SPICEEPHEMERIS_H__ +#ifndef __OPENSPACE_MODULE_SPACE___SPICETRANSLATION___H__ +#define __OPENSPACE_MODULE_SPACE___SPICETRANSLATION___H__ -#include +#include #include #include namespace openspace { -class SpiceEphemeris : public Ephemeris { +class SpiceTranslation : public Translation { public: - SpiceEphemeris(const ghoul::Dictionary& dictionary); + SpiceTranslation(const ghoul::Dictionary& dictionary); glm::dvec3 position() const; void update(const UpdateData& data) override; @@ -43,6 +43,7 @@ public: private: properties::StringProperty _target; properties::StringProperty _origin; + properties::StringProperty _frame; glm::dvec3 _position; bool _kernelsLoadedSuccessfully; @@ -50,4 +51,4 @@ private: } // namespace openspace -#endif // __SPICEEPHEMERIS_H__ +#endif // __OPENSPACE_MODULE_SPACE___SPICETRANSLATION___H__ diff --git a/modules/space/translation/tletranslation.cpp b/modules/space/translation/tletranslation.cpp new file mode 100644 index 0000000000..f3068f9b16 --- /dev/null +++ b/modules/space/translation/tletranslation.cpp @@ -0,0 +1,374 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include + +#include +#include +#include + +namespace { + const char* KeyFile = "File"; + + // The list of leap years only goes until 2056 as we need to touch this file then + // again anyway ;) + static const std::vector LeapYears = { + 1956, 1960, 1964, 1968, 1972, 1976, 1980, 1984, 1988, 1992, 1996, + 2000, 2004, 2008, 2012, 2016, 2020, 2024, 2028, 2032, 2036, 2040, + 2044, 2048, 2052, 2056 + }; + + // Count the number of full days since the beginning of 2000 to the beginning of + // the parameter 'year' + int countDays(int year) { + // Find the position of the current year in the vector, the difference + // between its position and the position of 2000 (for J2000) gives the + // number of leap years + const int Epoch = 2000; + const int DaysRegularYear = 365; + const int DaysLeapYear = 366; + + if (year == Epoch) { + return 0; + } + + // Get the position of the most recent leap year + auto lb = std::lower_bound(LeapYears.begin(), LeapYears.end(), year); + + // Get the position of the epoch + auto y2000 = std::find(LeapYears.begin(), LeapYears.end(), Epoch); + + // The distance between the two iterators gives us the number of leap years + int nLeapYears = std::abs(std::distance(y2000, lb)); + + int nYears = std::abs(year - Epoch); + int nRegularYears = nYears - nLeapYears; + + // Get the total number of days as the sum of leap years + non leap years + int result = nRegularYears * DaysRegularYear + nLeapYears * DaysLeapYear; + return result; + }; + + // Returns the number of leap seconds that lie between the {year, dayOfYear} + // time point and { 2000, 1 } + int countLeapSeconds(int year, int dayOfYear) { + // Find the position of the current year in the vector; its position in + // the vector gives the number of leap seconds + struct LeapSecond { + int year; + int dayOfYear; + bool operator<(const LeapSecond& rhs) const { + return + std::tie(year, dayOfYear) < std::tie(rhs.year, rhs.dayOfYear); + } + }; + + const LeapSecond Epoch = { 2000, 1}; + + // List taken from: https://www.ietf.org/timezones/data/leap-seconds.list + static const std::vector LeapSeconds = { + { 1972, 1 }, + { 1972, 183 }, + { 1973, 1 }, + { 1974, 1 }, + { 1975, 1 }, + { 1976, 1 }, + { 1977, 1 }, + { 1978, 1 }, + { 1979, 1 }, + { 1980, 1 }, + { 1981, 182 }, + { 1982, 182 }, + { 1983, 182 }, + { 1985, 182 }, + { 1988, 1 }, + { 1990, 1 }, + { 1991, 1 }, + { 1992, 183 }, + { 1993, 182 }, + { 1994, 182 }, + { 1996, 1 }, + { 1997, 182 }, + { 1999, 1 }, + { 2006, 1 }, + { 2009, 1 }, + { 2012, 183 }, + { 2015, 182 }, + { 2017, 1 } + }; + + // Get the position of the last leap second before the desired date + LeapSecond date { year, dayOfYear }; + auto it = std::lower_bound(LeapSeconds.begin(), LeapSeconds.end(), date); + + // Get the position of the Epoch + auto y2000 = std::lower_bound(LeapSeconds.begin(), LeapSeconds.end(), Epoch); + + // The distance between the two iterators gives us the number of leap years + int nLeapSeconds = std::abs(std::distance(y2000, it)); + return nLeapSeconds; + }; + + double epochFromSubstring(const std::string& epochString) { + // The epochString is in the form: + // YYDDD.DDDDDDDD + // With YY being the last two years of the launch epoch, the first DDD the day + // of the year and the remaning a fractional part of the day + + // The main overview of this function: + // 1. Reconstruct the full year from the YY part + // 2. Calculate the number of seconds since the beginning of the year + // 2.a Get the number of full days since the beginning of the year + // 2.b If the year is a leap year, modify the number of days + // 3. Convert the number of days to a number of seconds + // 4. Get the number of leap seconds since January 1st, 2000 and remove them + // 5. Adjust for the fact the epoch starts on 1st Januaray at 12:00:00, not + // midnight + + // According to https://celestrak.com/columns/v04n03/ + // Apparently, US Space Command sees no need to change the two-line element + // set format yet since no artificial earth satellites existed prior to 1957. + // By their reasoning, two-digit years from 57-99 correspond to 1957-1999 and + // those from 00-56 correspond to 2000-2056. We'll see each other again in 2057! + + // 1. Get the full year + std::string yearPrefix = [y = epochString.substr(0, 2)](){ + int year = std::atoi(y.c_str()); + return year >= 57 ? "19" : "20"; + }(); + int year = std::atoi((yearPrefix + epochString.substr(0, 2)).c_str()); + int daysSince2000 = countDays(year); + + // 2. + // 2.a + double daysInYear = std::atof(epochString.substr(2).c_str()); + + // 2.b + bool isInLeapYear = std::find( + LeapYears.begin(), + LeapYears.end(), + year + ) != LeapYears.end(); + if (isInLeapYear && daysInYear >= 60) { + // We are in a leap year, so we have an effective day more if we are + // beyond the end of february (= 31+29 days) + --daysInYear; + } + + // 3 + using namespace std::chrono; + int SecondsPerDay = seconds(hours(24)).count(); + double nSecondsSince2000 = (daysSince2000 + daysInYear) * SecondsPerDay; + + // 4 + // We need to remove additionbal leap seconds past 2000 and add them prior to + // 2000 to sync up the time zones + double nLeapSecondsOffset = -countLeapSeconds(year, std::floor(daysInYear)); + + // 5 + double nSecondsEpochOffset = seconds(hours(12)).count(); + + // Combine all of the values + double epoch = nSecondsSince2000 + nLeapSecondsOffset - nSecondsEpochOffset; + return epoch; + } + + double calculateSemiMajorAxis(double meanMotion) { + using namespace std::chrono; + const double GravitationalConstant = 6.6740831e-11; + const double MassEarth = 5.9721986e24; + const double muEarth = GravitationalConstant * MassEarth; + + // Use Kepler's 3rd law to calculate semimajor axis + // a^3 / P^2 = mu / (2pi)^2 + // <=> a = ((mu * P^2) / (2pi^2))^(1/3) + // with a = semimajor axis + // P = period in seconds + // mu = G*M_earth + using namespace std::chrono; + double period = seconds(hours(24)).count() / meanMotion; + + const double pisq = glm::pi() * glm::pi(); + double semiMajorAxis = pow((muEarth * period*period) / (4 * pisq), 1.0 / 3.0); + + // We need the semi major axis in km instead of m + return semiMajorAxis / 1000.0; + } +} + + +namespace openspace { + +Documentation TLETranslation::Documentation() { + using namespace openspace::documentation; + return { + "TLE Translation", + "space_transform_tle", + { + { + "Type", + new StringEqualVerifier("TLETranslation"), + "", + Optional::No + }, + { + KeyFile, + new StringVerifier, + "Specifies the filename of the Two-Line-Element file", + Optional::No + } + }, + Exhaustive::No + }; +} + + +TLETranslation::TLETranslation(const ghoul::Dictionary& dictionary) + : KeplerTranslation() +{ + documentation::testSpecificationAndThrow( + Documentation(), + dictionary, + "TLETranslation" + ); + + std::string file = dictionary.value(KeyFile); + readTLEFile(file); +} + +void TLETranslation::readTLEFile(const std::string& filename) { + ghoul_assert(FileSys.fileExists(filename), "The filename must exist"); + + std::ifstream file; + file.exceptions(std::ofstream::failbit | std::ofstream::badbit); + file.open(filename); + + // All of the Kepler element information + struct { + double inclination; + double semiMajorAxis; + double ascendingNode; + double eccentricity; + double argumentOfPeriapsis; + double meanAnomaly; + double meanMotion; + double epoch; + } keplerElements; + + std::string line; + while (std::getline(file, line)) { + if (line[0] == '1') { + // First line + // Field Columns Content + // 1 01-01 Line number + // 2 03-07 Satellite number + // 3 08-08 Classification (U = Unclassified) + // 4 10-11 International Designator (Last two digits of launch year) + // 5 12-14 International Designator (Launch number of the year) + // 6 15-17 International Designator(piece of the launch) A + // 7 19-20 Epoch Year(last two digits of year) + // 8 21-32 Epoch(day of the year and fractional portion of the day) + // 9 34-43 First Time Derivative of the Mean Motion divided by two + // 10 45-52 Second Time Derivative of Mean Motion divided by six + // 11 54-61 BSTAR drag term(decimal point assumed)[10] - 11606 - 4 + // 12 63-63 The "Ephemeris type" + // 13 65-68 Element set number.Incremented when a new TLE is generated + // 14 69-69 Checksum (modulo 10) + + keplerElements.epoch = epochFromSubstring(line.substr(18, 14)); + } + else if (line[0] == '2') { + // Second line + //Field Columns Content + // 1 01-01 Line number + // 2 03-07 Satellite number + // 3 09-16 Inclination (degrees) + // 4 18-25 Right ascension of the ascending node (degrees) + // 5 27-33 Eccentricity (decimal point assumed) + // 6 35-42 Argument of perigee (degrees) + // 7 44-51 Mean Anomaly (degrees) + // 8 53-63 Mean Motion (revolutions per day) + // 9 64-68 Revolution number at epoch (revolutions) + // 10 69-69 Checksum (modulo 10) + + std::stringstream stream; + stream.exceptions(std::ios::failbit); + + // Get inclination + stream.str(line.substr(8, 8)); + stream >> keplerElements.inclination; + stream.clear(); + + // Get Right ascension of the ascending node + stream.str(line.substr(17, 8)); + stream >> keplerElements.ascendingNode; + stream.clear(); + + // Get Eccentricity + stream.str("0." + line.substr(26, 7)); + stream >> keplerElements.eccentricity; + stream.clear(); + + // Get argument of periapsis + stream.str(line.substr(34, 8)); + stream >> keplerElements.argumentOfPeriapsis; + stream.clear(); + + // Get mean anomaly + stream.str(line.substr(43, 8)); + stream >> keplerElements.meanAnomaly; + stream.clear(); + + // Get mean motion + stream.str(line.substr(52, 11)); + stream >> keplerElements.meanMotion; + + break; + } + } + + // Calculate the semi major axis based on the mean motion using kepler's laws + keplerElements.semiMajorAxis = calculateSemiMajorAxis(keplerElements.meanMotion); + + // Converting the mean motion (revolutions per day) to period (seconds per revolution) + using namespace std::chrono; + double period = seconds(hours(24)).count() / keplerElements.meanMotion; + + setKeplerElements( + keplerElements.eccentricity, + keplerElements.semiMajorAxis, + keplerElements.inclination, + keplerElements.ascendingNode, + keplerElements.argumentOfPeriapsis, + keplerElements.meanAnomaly, + period, + keplerElements.epoch + ); +} + +} // namespace openspace diff --git a/modules/space/translation/tletranslation.h b/modules/space/translation/tletranslation.h new file mode 100644 index 0000000000..ba8a5cb023 --- /dev/null +++ b/modules/space/translation/tletranslation.h @@ -0,0 +1,75 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_SPACE___TLETRANSLATION___H__ +#define __OPENSPACE_MODULE_SPACE___TLETRANSLATION___H__ + +#include + +namespace openspace { + +/** + * A specialization of the KeplerTranslation that extracts the Keplerian elements from a + * two-line element as described by the US Space Command + * https://celestrak.com/columns/v04n03 + * The ghoul::Dictionary passed to the constructor must contain the pointer to a file that + * will be read. + */ +class TLETranslation : public KeplerTranslation { +public: + /** + * Constructor for the TLETranslation class. The \p dictionary must contain a key for + * the file that contains the TLE information. The ghoul::Dictionary will be tested + * against the openspace::Documentation returned by Documentation. + * \param The ghoul::Dictionary that contains the information for this TLETranslation + (*/ + TLETranslation(const ghoul::Dictionary& dictionary = ghoul::Dictionary()); + + /** + * Method returning the openspace::Documentation that describes the ghoul::Dictinoary + * that can be passed to the constructor. + * \return The openspace::Documentation that describes the ghoul::Dicitonary that can + * be passed to the constructor + */ + static openspace::Documentation Documentation(); + +private: + /** + * Reads the provided TLE file and calles the KeplerTranslation::setKeplerElments + * method with the correct values. If \p filename is a valid TLE file but contains + * disallowed values (see KeplerTranslation::setKeplerElements), a + * KeplerTranslation::RangeError is thrown. + * \param filename The path to the file that contains the TLE file. + * \throw std::system_error if the TLE file is malformed (does not contain at least + * two lines that start with \c 1 and \c 2. + * \throw KeplerTranslation::RangeError If the Keplerian elements are outside of + * the valid range supported by Kepler::setKeplerElements + * \pre The \p filename must exist + */ + void readTLEFile(const std::string& filename); +}; + +} // namespace openspace + +#endif // __OPENSPACE_MODULE_SPACE___TLETRANSLATION___H__ diff --git a/modules/toyvolume/include.cmake b/modules/toyvolume/include.cmake index 3ccace7c97..a8aaeb250d 100644 --- a/modules/toyvolume/include.cmake +++ b/modules/toyvolume/include.cmake @@ -1 +1,5 @@ set (DEFAULT_MODULE ON) + +set (OPENSPACE_DEPENDENCIES + space +) \ No newline at end of file diff --git a/modules/toyvolume/rendering/renderabletoyvolume.cpp b/modules/toyvolume/rendering/renderabletoyvolume.cpp index 0ce1f7b70a..45e23a47af 100644 --- a/modules/toyvolume/rendering/renderabletoyvolume.cpp +++ b/modules/toyvolume/rendering/renderabletoyvolume.cpp @@ -33,17 +33,10 @@ #include #include - -namespace { - const std::string GlslRayCastPath = "${MODULES}/toyvolume/shaders/rayCast.glsl"; - const std::string GlslBoundsVsPath = "${MODULES}/toyvolume/shaders/boundsVs.glsl"; - const std::string GlslBoundsFsPath = "${MODULES}/toyvolume/shaders/boundsFs.glsl"; -} - namespace openspace { - RenderableToyVolume::RenderableToyVolume(const ghoul::Dictionary& dictionary) - : Renderable(dictionary) +RenderableToyVolume::RenderableToyVolume(const ghoul::Dictionary& dictionary) + : Renderable(dictionary) , _scalingExponent("scalingExponent", "Scaling Exponent", 1, -10, 20) , _stepSize("stepSize", "Step Size", 0.02, 0.01, 1) , _scaling("scaling", "Scaling", glm::vec3(1.0, 1.0, 1.0), glm::vec3(0.0), glm::vec3(10.0)) @@ -137,4 +130,4 @@ void RenderableToyVolume::render(const RenderData& data, RendererTasks& tasks) { tasks.raycasterTasks.push_back(task); } -} +} // namespace openspace diff --git a/modules/toyvolume/rendering/renderabletoyvolume.h b/modules/toyvolume/rendering/renderabletoyvolume.h index 9c08f1af14..68f39da10a 100644 --- a/modules/toyvolume/rendering/renderabletoyvolume.h +++ b/modules/toyvolume/rendering/renderabletoyvolume.h @@ -22,18 +22,21 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RENDERABLETOYVOLUME_H__ -#define __RENDERABLETOYVOLUME_H__ +#ifndef __OPENSPACE_MODULE_TOYVOLUME___RENDERABLETOYVOLUME___H__ +#define __OPENSPACE_MODULE_TOYVOLUME___RENDERABLETOYVOLUME___H__ -#include +#include + +#include +#include +#include +#include #include #include -#include -#include - namespace openspace { +class ToyVolumeRaycaster; struct RenderData; class RenderableToyVolume : public Renderable { @@ -57,6 +60,7 @@ private: std::unique_ptr _raycaster; }; -} -#endif // __RENDERABLETOYVOLUME_H__ +} // namespace openspace + +#endif // __OPENSPACE_MODULE_TOYVOLUME___RENDERABLETOYVOLUME___H__ diff --git a/modules/toyvolume/rendering/toyvolumeraycaster.cpp b/modules/toyvolume/rendering/toyvolumeraycaster.cpp index 8687f93744..66944a1fbe 100644 --- a/modules/toyvolume/rendering/toyvolumeraycaster.cpp +++ b/modules/toyvolume/rendering/toyvolumeraycaster.cpp @@ -33,9 +33,9 @@ #include namespace { - const std::string GlslRaycastPath = "${MODULES}/toyvolume/shaders/raycast.glsl"; - const std::string GlslBoundsVsPath = "${MODULES}/toyvolume/shaders/boundsVs.glsl"; - const std::string GlslBoundsFsPath = "${MODULES}/toyvolume/shaders/boundsFs.glsl"; + const char* GlslRaycastPath = "${MODULES}/toyvolume/shaders/raycast.glsl"; + const char* GlslBoundsVsPath = "${MODULES}/toyvolume/shaders/boundsvs.glsl"; + const char* GlslBoundsFsPath = "${MODULES}/toyvolume/shaders/boundsfs.glsl"; } namespace openspace { diff --git a/modules/toyvolume/rendering/toyvolumeraycaster.h b/modules/toyvolume/rendering/toyvolumeraycaster.h index 4924276a20..b6159b0baf 100644 --- a/modules/toyvolume/rendering/toyvolumeraycaster.h +++ b/modules/toyvolume/rendering/toyvolumeraycaster.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __TOYVOLUMERAYCASTER_H__ -#define __TOYVOLUMERAYCASTER_H__ +#ifndef __OPENSPACE_MODULE_TOYVOLUME___TOYVOLUMERAYCASTER___H__ +#define __OPENSPACE_MODULE_TOYVOLUME___TOYVOLUMERAYCASTER___H__ #include #include @@ -77,4 +77,4 @@ private: } // openspace -#endif // __TOYVOLUMERAYCASTER_H__ +#endif // __OPENSPACE_MODULE_TOYVOLUME___TOYVOLUMERAYCASTER___H__ diff --git a/modules/toyvolume/shaders/boundsFs.glsl b/modules/toyvolume/shaders/boundsfs.glsl similarity index 100% rename from modules/toyvolume/shaders/boundsFs.glsl rename to modules/toyvolume/shaders/boundsfs.glsl diff --git a/modules/toyvolume/shaders/boundsVs.glsl b/modules/toyvolume/shaders/boundsvs.glsl similarity index 100% rename from modules/toyvolume/shaders/boundsVs.glsl rename to modules/toyvolume/shaders/boundsvs.glsl diff --git a/modules/toyvolume/shaders/raycast.glsl b/modules/toyvolume/shaders/raycast.glsl index e78478f058..28c53a33d7 100644 --- a/modules/toyvolume/shaders/raycast.glsl +++ b/modules/toyvolume/shaders/raycast.glsl @@ -27,30 +27,49 @@ uniform vec4 color#{id}; uniform float time#{id}; uniform float maxStepSize#{id} = 0.02; -vec4 sample#{id}(vec3 samplePos, vec3 dir, vec4 foregroundColor, inout float maxStepSize) { - maxStepSize = maxStepSize#{id}; +void sample#{id}(vec3 samplePos, + vec3 dir, + inout vec3 accumulatedColor, + inout vec3 accumulatedAlpha, + inout float stepSize) { - // Generate an arbitrary procedural volume. + // Generate a procedural placeholder volume. // In real situations, the sample function would sample a // 3D texture to retrieve the color contribution of a given point. vec3 fromCenter = vec3(0.5, 0.5, 0.5) - samplePos; - vec4 c = color#{id}; - float r = length(fromCenter); - c.a *= (1.0 - smoothstep(0.4, 0.45, r)); - c.a *= (1.0 - smoothstep(0.35, 0.3, r)); - c.a *= (1.0 - smoothstep(0.1, 0.2, abs(fromCenter.y))); - float theta = atan(fromCenter.x, fromCenter.z); float angularRatio = (theta + 3.1415) / 6.283; - angularRatio = mod(angularRatio + time#{id}*0.01, 1.0); - - c.a *= smoothstep(0.0, 0.2, clamp(angularRatio, 0.0, 1.0)); - c.a *= smoothstep(1.0, 0.8, clamp(angularRatio, 0.0, 1.0)); - return c; + + float timeWave = sin(mod(time#{id}*0.05, 2.0 * 3.1415)); + float rDisplacement = 0.1 * timeWave; + + vec4 c = color#{id}; + float r = length(fromCenter); + c.a *= (1.0 - smoothstep(0.35 + rDisplacement, 0.40 + rDisplacement, r)); + c.a *= (1.0 - smoothstep(0.30 + rDisplacement, 0.25 + rDisplacement, r)); + c.a *= (1.0 - smoothstep(0.1, 0.2, abs(fromCenter.y) / angularRatio * 0.5)); + + c.a *= 1.0 - smoothstep(0.0, 1.0, clamp(angularRatio, 0.0, 1.0)); + c.a *= smoothstep(0.0, 0.1, clamp(angularRatio, 0.0, 1.0)); + + vec3 backAlpha = c.aaa * 10.0; + vec3 backColor = c.rgb * backAlpha; + + backColor *= stepSize; + backAlpha *= stepSize; + + backColor = clamp(backColor, 0.0, 1.0); + backAlpha = clamp(backAlpha, 0.0, 1.0); + + vec3 oneMinusFrontAlpha = vec3(1.0) - accumulatedAlpha; + accumulatedColor += oneMinusFrontAlpha * backColor; + accumulatedAlpha += oneMinusFrontAlpha * backAlpha; + + stepSize = maxStepSize#{id}; } float stepSize#{id}(vec3 samplePos, vec3 dir) { diff --git a/modules/toyvolume/toyvolumemodule.h b/modules/toyvolume/toyvolumemodule.h index 510156fef2..f4fb27661e 100644 --- a/modules/toyvolume/toyvolumemodule.h +++ b/modules/toyvolume/toyvolumemodule.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __TOYVOLUMEMODULE_H__ -#define __TOYVOLUMEMODULE_H__ +#ifndef __OPENSPACE_MODULE_TOYVOLUME___TOYVOLUMEMODULE___H__ +#define __OPENSPACE_MODULE_TOYVOLUME___TOYVOLUMEMODULE___H__ #include @@ -37,4 +37,4 @@ public: } // namespace openspace -#endif // __TOYVOLUMEMODULE_H__ +#endif // __OPENSPACE_MODULE_TOYVOLUME___TOYVOLUMEMODULE___H__ diff --git a/modules/volume/CMakeLists.txt b/modules/volume/CMakeLists.txt index b6538d01b5..95cb375fb8 100644 --- a/modules/volume/CMakeLists.txt +++ b/modules/volume/CMakeLists.txt @@ -25,22 +25,27 @@ include(${OPENSPACE_CMAKE_EXT_DIR}/module_definition.cmake) set(HEADER_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/rawvolume.h + ${CMAKE_CURRENT_SOURCE_DIR}/rawvolume.h + ${CMAKE_CURRENT_SOURCE_DIR}/rawvolume.inl ${CMAKE_CURRENT_SOURCE_DIR}/rawvolumereader.h - ${CMAKE_CURRENT_SOURCE_DIR}/rawvolumewriter.h + ${CMAKE_CURRENT_SOURCE_DIR}/rawvolumereader.inl + ${CMAKE_CURRENT_SOURCE_DIR}/rawvolumewriter.h + ${CMAKE_CURRENT_SOURCE_DIR}/rawvolumewriter.inl ${CMAKE_CURRENT_SOURCE_DIR}/textureslicevolumereader.h + ${CMAKE_CURRENT_SOURCE_DIR}/textureslicevolumereader.inl ${CMAKE_CURRENT_SOURCE_DIR}/lrucache.h - ${CMAKE_CURRENT_SOURCE_DIR}/linearlrucache.h + ${CMAKE_CURRENT_SOURCE_DIR}/linearlrucache.h ${CMAKE_CURRENT_SOURCE_DIR}/volumesampler.h - ${CMAKE_CURRENT_SOURCE_DIR}/volumeutils.h + ${CMAKE_CURRENT_SOURCE_DIR}/volumesampler.inl + ${CMAKE_CURRENT_SOURCE_DIR}/volumeutils.h ) source_group("Header Files" FILES ${HEADER_FILES}) set(SOURCE_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/rawvolume.inl + ${CMAKE_CURRENT_SOURCE_DIR}/rawvolume.inl ${CMAKE_CURRENT_SOURCE_DIR}/rawvolumereader.inl ${CMAKE_CURRENT_SOURCE_DIR}/rawvolumewriter.inl - ${CMAKE_CURRENT_SOURCE_DIR}/textureslicevolumereader.inl + ${CMAKE_CURRENT_SOURCE_DIR}/textureslicevolumereader.inl ${CMAKE_CURRENT_SOURCE_DIR}/volumesampler.inl ${CMAKE_CURRENT_SOURCE_DIR}/volumeutils.cpp ) diff --git a/modules/volume/include.cmake b/modules/volume/include.cmake index 510dbef2a1..eb1651efed 100644 --- a/modules/volume/include.cmake +++ b/modules/volume/include.cmake @@ -1,3 +1,4 @@ set (OPENSPACE_DEPENDENCIES # kameleon + space ) diff --git a/modules/volume/linearlrucache.h b/modules/volume/linearlrucache.h index 437afa99e4..b3f7e4083b 100644 --- a/modules/volume/linearlrucache.h +++ b/modules/volume/linearlrucache.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014 - 2016 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __LRUCACHE_H__ -#define __LRUCACHE_H__ +#ifndef __OPENSPACE_MODULE_VOLUME___LINEARLRUCACHE___H__ +#define __OPENSPACE_MODULE_VOLUME___LINEARLRUCACHE___H__ #include #include @@ -86,6 +86,6 @@ private: size_t _capacity; }; -} +} // namespace openspace -#endif +#endif // __OPENSPACE_MODULE_VOLUME___LINEARLRUCACHE___H__ diff --git a/modules/volume/lrucache.h b/modules/volume/lrucache.h index c8a3fee41e..94d5a0deed 100644 --- a/modules/volume/lrucache.h +++ b/modules/volume/lrucache.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014 - 2016 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __LRUCACHE_H__ -#define __LRUCACHE_H__ +#ifndef __OPENSPACE_MODULE_VOLUME___LRUCACHE___H__ +#define __OPENSPACE_MODULE_VOLUME___LRUCACHE___H__ #include #include @@ -86,6 +86,6 @@ private: size_t _capacity; }; -} +} // namespace openspace -#endif +#endif // __OPENSPACE_MODULE_VOLUME___LRUCACHE___H__ diff --git a/modules/volume/rawvolume.h b/modules/volume/rawvolume.h index df5e3b9037..7cce0ae066 100644 --- a/modules/volume/rawvolume.h +++ b/modules/volume/rawvolume.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014 - 2016 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RAWVOLUME_H__ -#define __RAWVOLUME_H__ +#ifndef __OPENSPACE_MODULE_VOLUME___RAWVOLUME___H__ +#define __OPENSPACE_MODULE_VOLUME___RAWVOLUME___H__ namespace openspace { @@ -47,8 +47,8 @@ private: std::vector _data; }; -} +} // namespace openspace #include "rawvolume.inl" -#endif // __RAWVOLUME_H__ +#endif // __OPENSPACE_MODULE_VOLUME___RAWVOLUME___H__ diff --git a/modules/volume/rawvolume.inl b/modules/volume/rawvolume.inl index 5f8edbc50a..ba913e84bb 100644 --- a/modules/volume/rawvolume.inl +++ b/modules/volume/rawvolume.inl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014 - 2016 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * diff --git a/modules/volume/rawvolumereader.h b/modules/volume/rawvolumereader.h index fb394d7717..75ecb0b694 100644 --- a/modules/volume/rawvolumereader.h +++ b/modules/volume/rawvolumereader.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014 - 2016 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __RAWVOLUMEREADER_H__ -#define __RAWVOLUMEREADER_H__ +#ifndef __OPENSPACE_MODULE_VOLUME___RAWVOLUMEREADER___H__ +#define __OPENSPACE_MODULE_VOLUME___RAWVOLUMEREADER___H__ #include #include @@ -49,8 +49,8 @@ private: std::string _path; }; -} +} // namespace openspace #include "rawvolumereader.inl" -#endif // __RAWVOLUMEREADER_H__ +#endif // __OPENSPACE_MODULE_VOLUME___RAWVOLUMEREADER___H__ diff --git a/modules/volume/rawvolumereader.inl b/modules/volume/rawvolumereader.inl index fe16c09789..135a046c8a 100644 --- a/modules/volume/rawvolumereader.inl +++ b/modules/volume/rawvolumereader.inl @@ -1,3 +1,27 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + #include namespace openspace { @@ -6,7 +30,8 @@ template RawVolumeReader::RawVolumeReader(const std::string& path, const glm::ivec3& dimensions) : _path(path) - , _dimensions(dimensions) {} + , _dimensions(dimensions) +{} template glm::ivec3 RawVolumeReader::dimensions() const { @@ -70,4 +95,4 @@ std::unique_ptr> RawVolumeReader::read() { return volume; } -} +} // namespace openspace diff --git a/modules/volume/rawvolumewriter.h b/modules/volume/rawvolumewriter.h index 48bd3cae04..a173f53d9b 100644 --- a/modules/volume/rawvolumewriter.h +++ b/modules/volume/rawvolumewriter.h @@ -1,5 +1,29 @@ -#ifndef __RAWVOLUMEWRITER_H__ -#define __RAWVOLUMEWRITER_H__ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_VOLUME___RAWVOLUMEWRITER___H__ +#define __OPENSPACE_MODULE_VOLUME___RAWVOLUMEWRITER___H__ #include #include @@ -26,8 +50,8 @@ private: size_t _bufferSize; }; -} +} // namespace openspace #include "rawvolumewriter.inl"; -#endif +#endif // __OPENSPACE_MODULE_VOLUME___RAWVOLUMEWRITER___H__ diff --git a/modules/volume/rawvolumewriter.inl b/modules/volume/rawvolumewriter.inl index b3285ad176..1e1fc8294d 100644 --- a/modules/volume/rawvolumewriter.inl +++ b/modules/volume/rawvolumewriter.inl @@ -1,3 +1,27 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + #include #include @@ -76,5 +100,4 @@ void RawVolumeWriter::write(const RawVolume& volume) { file.close(); } - -} +} // namespace openspace diff --git a/modules/volume/textureslicevolumereader.h b/modules/volume/textureslicevolumereader.h index f5d1da2f18..c8a96a1e6d 100644 --- a/modules/volume/textureslicevolumereader.h +++ b/modules/volume/textureslicevolumereader.h @@ -1,5 +1,29 @@ -#ifndef __TEXTURESLICEVOLUMEREADER_H__ -#define __TEXTURESLICEVOLUMEREADER_H__ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_VOLUME___TEXTURESLICEVOLUMEREADER___H__ +#define __OPENSPACE_MODULE_VOLUME___TEXTURESLICEVOLUMEREADER___H__ #include #include @@ -27,8 +51,8 @@ private: bool _initialized; }; -} +} // namespace openspace #include "textureslicevolumereader.inl" -#endif // __TEXTURESLICEVOLUME_H__ +#endif // __OPENSPACE_MODULE_VOLUME___TEXTURESLICEVOLUMEREADER___H__ diff --git a/modules/volume/textureslicevolumereader.inl b/modules/volume/textureslicevolumereader.inl index 8f55678cb8..9c859905cf 100644 --- a/modules/volume/textureslicevolumereader.inl +++ b/modules/volume/textureslicevolumereader.inl @@ -1,3 +1,27 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + #include namespace openspace { @@ -55,4 +79,4 @@ ghoul::opengl::Texture& TextureSliceVolumeReader::getSlice(int sliceI return *_cache.get(sliceIndex).get(); } -} +} // namespace openspace diff --git a/modules/volume/volumemodule.cpp b/modules/volume/volumemodule.cpp index 42a04bdcde..10098fe698 100644 --- a/modules/volume/volumemodule.cpp +++ b/modules/volume/volumemodule.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * diff --git a/modules/volume/volumemodule.h b/modules/volume/volumemodule.h index 3319dadb3a..f21de012d3 100644 --- a/modules/volume/volumemodule.h +++ b/modules/volume/volumemodule.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2015 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __VOLUMEMODULE_H__ -#define __VOLUMEMODULE_H__ +#ifndef __OPENSPACE_MODULE_VOLUME___VOLUMEMODULE___H__ +#define __OPENSPACE_MODULE_VOLUME___VOLUMEMODULE___H__ #include @@ -39,4 +39,4 @@ protected: } // namespace openspace -#endif // __VOLUMEMODULE_H__ +#endif // __OPENSPACE_MODULE_VOLUME___VOLUMEMODULE___H__ diff --git a/modules/volume/volumesampler.h b/modules/volume/volumesampler.h index 1f394385c6..cc6bff50d5 100644 --- a/modules/volume/volumesampler.h +++ b/modules/volume/volumesampler.h @@ -1,5 +1,29 @@ -#ifndef __VOLUMESAMPLER_H__ -#define __VOLUMESAMPLER_H__ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_VOLUME___VOLUMESAMPLER___H__ +#define __OPENSPACE_MODULE_VOLUME___VOLUMESAMPLER___H__ namespace openspace { @@ -13,8 +37,8 @@ private: const VolumeType* _volume; }; -} +} // namespace openspace #include "volumesampler.inl" -#endif +#endif // __OPENSPACE_MODULE_VOLUME___VOLUMESAMPLER___H__ diff --git a/modules/volume/volumesampler.inl b/modules/volume/volumesampler.inl index 85fdde61f8..a214dbd82b 100644 --- a/modules/volume/volumesampler.inl +++ b/modules/volume/volumesampler.inl @@ -1,3 +1,27 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + namespace openspace { template @@ -54,4 +78,4 @@ typename VolumeType::VoxelType VolumeSampler::sample(const glm::vec3 return value; } -} +} // namespace openspace diff --git a/modules/volume/volumeutils.cpp b/modules/volume/volumeutils.cpp index 42eddf10c5..ab9ef9c500 100644 --- a/modules/volume/volumeutils.cpp +++ b/modules/volume/volumeutils.cpp @@ -1,3 +1,27 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + #include "volumeutils.h" namespace openspace { @@ -27,5 +51,6 @@ glm::vec3 indexToCoords(size_t index, const glm::ivec3& dims) { return glm::ivec3(x, y, z); } -} -} +} // namespace volumeutils + +} // namespace openspace diff --git a/modules/volume/volumeutils.h b/modules/volume/volumeutils.h index bcb16b4d23..6d7b3fce26 100644 --- a/modules/volume/volumeutils.h +++ b/modules/volume/volumeutils.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014 - 2016 * + * Copyright (c) 2014-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __VOLUMEUTILS_H__ -#define __VOLUMEUTILS_H__ +#ifndef __OPENSPACE_MODULE_VOLUME___VOLUMEUTILS___H__ +#define __OPENSPACE_MODULE_VOLUME___VOLUMEUTILS___H__ #include @@ -33,7 +33,8 @@ namespace volumeutils { size_t coordsToIndex(const glm::vec3& coords, const glm::ivec3& dimensions); glm::vec3 indexToCoords(size_t index, const glm::ivec3& dimensions); -} -} +} // namespace volumeutils -#endif // __VOLUMEUTILS__ +} // namespace openspace + +#endif // __OPENSPACE_MODULE_VOLUME___VOLUMEUTILS___H__ diff --git a/openspace.cfg b/openspace.cfg index 26fb6f447d..277e10f809 100644 --- a/openspace.cfg +++ b/openspace.cfg @@ -66,6 +66,8 @@ return { File = "${DOCUMENTATION}/FactoryDocumentation.html" }, ShutdownCountdown = 3, + -- OnScreenTextScaling = "framebuffer", + -- PerSceneCache = true, DownloadRequestURL = "http://data.openspaceproject.com/request.cgi", RenderingMethod = "Framebuffer" --RenderingMethod = "ABuffer" -- alternative: "Framebuffer" diff --git a/scripts/bind_common_keys.lua b/scripts/bind_common_keys.lua new file mode 100644 index 0000000000..3101b7945e --- /dev/null +++ b/scripts/bind_common_keys.lua @@ -0,0 +1,20 @@ +--[[ OpenSpace keybinding script ]]-- + +-- Load the common helper functions +dofile(openspace.absPath('${SCRIPTS}/common.lua')) + +openspace.clearKeys() +helper.setCommonKeys() +helper.setDeltaTimeKeys({ +-- 1 2 3 4 5 6 7 8 9 0 +-------------------------------------------------------------------------------------------------------------------------- +-- 1s 2s 5s 10s 30s 1m 2m 5m 10m 30m + 1, 2, 5, 10, 30, 60, 120, 300, 600, 1800, + +-- 1h 2h 3h 6h 12h 1d 2d 4d 1w 2w + 3600, 7200, 10800, 21600, 43200, 86400, 172800, 345600, 604800, 1209600, + +-- 1mo 2mo 3mo 6mo 1yr 2y 5y 10y 20y 50y + 2592000, 5184000, 7776000, 15552000, 31536000, 63072000, 157680000, 315360000, 630720000, 1576800000 +}) +-- OBS: One month (1mo) is approximated by 30 days. diff --git a/scripts/bind_keys.lua b/scripts/bind_keys.lua deleted file mode 100644 index 1a0c56dcad..0000000000 --- a/scripts/bind_keys.lua +++ /dev/null @@ -1,33 +0,0 @@ ---[[ OpenSpace keybinding script ]]-- - --- Load the common helper functions -dofile(openspace.absPath('${SCRIPTS}/common.lua')) - -openspace.clearKeys() -helper.setCommonKeys() -helper.setDeltaTimeKeys({ --- 1 2 3 4 5 6 7 8 9 0 --------------------------------------------------------------------------------------------------------------------------- --- 1s 2s 5s 10s 30s 1m 2m 5m 10m 30 min - 1, 2, 5, 10, 30, 60, 120, 300, 600, 1800, - --- 1h 2h 3h 6h 12h 1d 2d 4d 1w 2w - 3600, 7200, 10800, 21600, 43200, 86400, 172800, 345600, 604800, 1209600, - --- 1mo 2mo 3mo 6mo 1yr 2y 5y 10y 20y 50y - 2592000, 5184000, 7776000, 15552000, 31536000, 63072000, 157680000, 315360000, 630720000, 1576800000 -}) --- OBS: One month (1mo) is approximated by 30 days. - - -openspace.bindKey("q", helper.renderable.toggle('SunMarker')) -openspace.bindKey("e", helper.renderable.toggle('EarthMarker')) -openspace.bindKey("x", helper.renderable.toggle('Constellation Bounds')) - -openspace.bindKey("c", "openspace.parallel.setAddress('130.236.142.51');openspace.parallel.setPassword('newhorizons-20150714');openspace.parallel.connect();") - -openspace.bindKey("h", "openspace.iswa.setBaseUrl('https://iswa-demo-server.herokuapp.com/')"); -openspace.bindKey("g", "openspace.iswa.setBaseUrl('http://128.183.168.116:3000/')"); -openspace.bindKey("l", "openspace.iswa.setBaseUrl('http://localhost:3000/')"); - -openspace.bindKey("v", "openspace.time.setTime('2015-03-15T02:00:00.00')"); \ No newline at end of file diff --git a/scripts/bind_keys_newhorizons.lua b/scripts/bind_keys_newhorizons.lua index 246a526d3c..4d0310a146 100644 --- a/scripts/bind_keys_newhorizons.lua +++ b/scripts/bind_keys_newhorizons.lua @@ -1,74 +1,135 @@ ---[[ OpenSpace keybinding script ]]-- +--[[ OpenSpace keybinding script loaded from the newhorizons.scene file ]]-- -- Load the common helper functions dofile(openspace.absPath('${SCRIPTS}/common.lua')) openspace.clearKeys() helper.setCommonKeys() - helper.setDeltaTimeKeys({ 1, 5, 10, 20, 40, 60, 120, 360, 540, 1080, 2160, 4320, 8640 }) -openspace.bindKey("a", "openspace.setPropertyValue('Interaction.origin', 'NewHorizons')") -openspace.bindKey("s", "openspace.setPropertyValue('Interaction.origin', 'PlutoProjection')") -openspace.bindKey("d", "openspace.setPropertyValue('Interaction.origin', 'Charon')") -openspace.bindKey("z", "openspace.setPropertyValue('Interaction.origin', 'JupiterProjection')") -openspace.bindKey("x", "openspace.setPropertyValue('Interaction.origin', 'Europa')") - -openspace.bindKey("F5", "openspace.setPropertyValue('Interaction.coordinateSystem', 'Sun'); openspace.printInfo('Changing Viewpoint to Sun');"); -openspace.bindKey("F6", "openspace.setPropertyValue('Interaction.coordinateSystem', 'Jupiter'); openspace.printInfo('Changing Viewpoint to Jupiter');"); -openspace.bindKey("F7", "openspace.setPropertyValue('Interaction.coordinateSystem', 'Pluto'); openspace.printInfo('Changing Viewpoint to Pluto');"); - -openspace.bindKey("F8", "openspace.setPropertyValue('PlutoProjection.renderable.ProjectionComponent.clearAllProjections', true); openspace.setPropertyValue('Charon.renderable.ProjectionComponent.clearAllProjections', true);") - --- Quickfix backjumps in pluto sequence -openspace.bindKey("F9", "openspace.time.setTime('2015-07-14T09:00:00.00'); openspace.setPropertyValue('PlutoProjection.renderable.clearAllProjections', true); openspace.setPropertyValue('Charon.renderable.clearAllProjections', true);") -openspace.bindKey("F10", "openspace.time.setTime('2015-07-14T10:00:00.00'); openspace.setPropertyValue('PlutoProjection.renderable.clearAllProjections', true); openspace.setPropertyValue('Charon.renderable.clearAllProjections', true);") -openspace.bindKey("F11", "openspace.time.setTime('2015-07-14T11:17:00.00'); openspace.setPropertyValue('PlutoProjection.renderable.clearAllProjections', true); openspace.setPropertyValue('Charon.renderable.clearAllProjections', true);") -openspace.bindKey("F12", "openspace.time.setTime('2015-07-14T12:45:00.00'); openspace.setPropertyValue('PlutoProjection.renderable.clearAllProjections', true); openspace.setPropertyValue('Charon.renderable.clearAllProjections', true);") - -openspace.bindKey("r", helper.property.invert('PlutoProjection.renderable.fk')) - -openspace.bindKey("KP_8", helper.property.increment('PlutoProjection.renderable.heightExaggeration', 2)) -openspace.bindKey("KP_2", helper.property.decrement('PlutoProjection.renderable.heightExaggeration', 2)) - -openspace.bindKey("KP_9", helper.property.increment('Charon.renderable.heightExaggeration', 2)) -openspace.bindKey("KP_3", helper.property.decrement('Charon.renderable.heightExaggeration', 2)) - - -openspace.bindKey("g", "openspace.time.setTime('2007-02-28T11:40:00.00'); openspace.time.setDeltaTime(1);") - -openspace.bindKey("h", "openspace.time.setTime('2015-07-14T10:00:00.00'); openspace.time.setDeltaTime(1); openspace.setPropertyValue('Interaction.coordinateSystem', 'Pluto');openspace.setPropertyValue('Interaction.origin', 'PlutoProjection'); openspace.printInfo('Changing Viewpoint to Pluto-in-center');") - -openspace.bindKey("q", helper.property.invert('SunMarker.renderable.enabled')) -openspace.bindKey("e", helper.property.invert('EarthMarker.renderable.enabled')) -openspace.bindKey("o", helper.property.invert('PlutoTrail.renderable.enabled')) - -openspace.bindKey("k", - helper.renderable.toggle('HydraText') .. helper.renderable.toggle('NixText') .. helper.renderable.toggle('KerberosText') .. helper.renderable.toggle('StyxText') +openspace.bindKey( + "a", + "openspace.setPropertyValue('Interaction.origin', 'NewHorizons')", + "Sets the focus of the camera on 'NewHorizons'." +) +openspace.bindKey( + "s", + "openspace.setPropertyValue('Interaction.origin', 'PlutoProjection')", + "Sets the focus of the camera on 'Pluto'" +) +openspace.bindKey( + "d", + "openspace.setPropertyValue('Interaction.origin', 'Charon')", + "Sets the focus of the camera on 'Charon'." +) +openspace.bindKey( + "z", + "openspace.setPropertyValue('Interaction.origin', 'JupiterProjection')", + "Sets the focus of the camera on 'Jupiter'." +) +openspace.bindKey( + "x", + "openspace.setPropertyValue('Interaction.origin', 'Europa')", + "Sets the focus of the camera on 'Europa'." ) -openspace.bindKey("j", helper.renderable.toggle('PlutoText')) -openspace.bindKey("l", helper.property.invert('Labels.renderable.performFading')) +openspace.bindKey( + "F8", + "openspace.setPropertyValue('PlutoProjection.renderable.ProjectionComponent.clearAllProjections', true);" .. + "openspace.setPropertyValue('Charon.renderable.ProjectionComponent.clearAllProjections', true);", + "Removes all image projections from Pluto and Charon." +) + +openspace.bindKey( + "F9", + "openspace.time.setTime('2015-07-14T09:00:00.00');" .. + "openspace.setPropertyValue('PlutoProjection.renderable.clearAllProjections', true);" .. + "openspace.setPropertyValue('Charon.renderable.clearAllProjections', true);", + "Jumps to the 14th of July 2015 at 0900 UTC and clears all projections." +) + +openspace.bindKey( + "KP_8", + helper.property.increment('PlutoProjection.renderable.heightExaggeration', 2), + "Increases the height map exaggeration on Pluto." +) +openspace.bindKey( + "KP_2", + helper.property.decrement('PlutoProjection.renderable.heightExaggeration', 2), + "Decreases the height map exaggeration on Pluto." +) +openspace.bindKey( + "KP_9", + helper.property.increment('Charon.renderable.heightExaggeration', 2), + "Increases the height map exaggeration on Charon." +) +openspace.bindKey( + "KP_3", + helper.property.decrement('Charon.renderable.heightExaggeration', 2), + "Decreases the height map exaggeration on Charon." +) + +openspace.bindKey( + "q", + helper.property.invert('SunMarker.renderable.enabled'), + "Toggles the visibility of the text marking the location of the Sun." +) +openspace.bindKey( + "e", + helper.property.invert('EarthMarker.renderable.enabled'), + "Toggles the visibility of the text marking the location of the Earth." +) +openspace.bindKey( + "o", + helper.property.invert('PlutoTrail.renderable.enabled'), + "Toggles the visibility of the trail behind Pluto." +) + +openspace.bindKey( + "j", + helper.renderable.toggle('PlutoText') .. helper.renderable.toggle('CharonText') .. + helper.renderable.toggle('HydraText') .. helper.renderable.toggle('NixText') .. + helper.renderable.toggle('KerberosText') .. helper.renderable.toggle('StyxText'), + "Toggles the visibility of the text labels of Pluto, Charon, Hydra, Nix, Kerberos, and Styx." +) + +openspace.bindKey( + "l", + helper.property.invert('Labels.renderable.performFading'), + "Toggles the visibility of the labels for the New Horizons instruments." +) openspace.bindKey("m", - helper.property.invert('NH_LORRI.renderable.solidDraw') .. helper.property.invert('NH_RALPH_LEISA.renderable.solidDraw') .. - helper.property.invert('NH_RALPH_MVIC_PAN1.renderable.solidDraw') .. helper.property.invert('NH_RALPH_MVIC_PAN2.renderable.solidDraw') .. - helper.property.invert('NH_RALPH_MVIC_RED.renderable.solidDraw') .. helper.property.invert('NH_RALPH_MVIC_BLUE.renderable.solidDraw') .. - helper.property.invert('NH_RALPH_MVIC_FT.renderable.solidDraw') .. helper.property.invert('NH_RALPH_MVIC_METHANE.renderable.solidDraw') .. - helper.property.invert('NH_RALPH_MVIC_NIR.renderable.solidDraw') .. helper.property.invert('NH_ALICE_AIRGLOW.renderable.solidDraw') .. - helper.property.invert('NH_ALICE_SOC.renderable.solidDraw') + helper.property.invert('NH_LORRI.renderable.solidDraw') .. + helper.property.invert('NH_RALPH_LEISA.renderable.solidDraw') .. + helper.property.invert('NH_RALPH_MVIC_PAN1.renderable.solidDraw') .. + helper.property.invert('NH_RALPH_MVIC_PAN2.renderable.solidDraw') .. + helper.property.invert('NH_RALPH_MVIC_RED.renderable.solidDraw') .. + helper.property.invert('NH_RALPH_MVIC_BLUE.renderable.solidDraw') .. + helper.property.invert('NH_RALPH_MVIC_FT.renderable.solidDraw') .. + helper.property.invert('NH_RALPH_MVIC_METHANE.renderable.solidDraw') .. + helper.property.invert('NH_RALPH_MVIC_NIR.renderable.solidDraw') .. + helper.property.invert('NH_ALICE_AIRGLOW.renderable.solidDraw') .. + helper.property.invert('NH_ALICE_SOC.renderable.solidDraw'), + "Draws the instrument field of views in a solid color or as lines." ) -openspace.bindKey("t", helper.renderable.toggle('PlutoShadow') .. helper.renderable.toggle('CharonShadow')) +openspace.bindKey( + "t", + helper.renderable.toggle('PlutoShadow') .. helper.renderable.toggle('CharonShadow'), + "Toggles the visibility of the shadow visualization of Pluto and Charon." +) openspace.bindKey("p", - helper.property.invert('JupiterProjection.renderable.performProjection') .. helper.property.invert('Io.renderable.performProjection') .. - helper.property.invert('Ganymede.renderable.performProjection') .. helper.property.invert('Europa.renderable.performProjection') .. - helper.property.invert('Callisto.renderable.performProjection') .. helper.property.invert('PlutoProjection.renderable.performProjection') .. - helper.property.invert('Charon.renderable.performProjection') + helper.property.invert('JupiterProjection.renderable.performProjection') .. + helper.property.invert('Io.renderable.performProjection') .. + helper.property.invert('Ganymede.renderable.performProjection') .. + helper.property.invert('Europa.renderable.performProjection') .. + helper.property.invert('Callisto.renderable.performProjection') .. + helper.property.invert('PlutoProjection.renderable.performProjection') .. + helper.property.invert('Charon.renderable.performProjection'), + "Enables or disables the image projection on the different available objects." ) - -openspace.bindKey("c", "openspace.parallel.setAddress('130.236.142.51');openspace.parallel.setPassword('newhorizons-20150714');openspace.parallel.connect();") diff --git a/scripts/bind_keys_osirisrex.lua b/scripts/bind_keys_osirisrex.lua index 536a63cd1a..1963734dad 100644 --- a/scripts/bind_keys_osirisrex.lua +++ b/scripts/bind_keys_osirisrex.lua @@ -1,33 +1,59 @@ ---[[ OpenSpace keybinding script ]]-- +--[[ OpenSpace keybinding script loaded from the osirisrex.scene file ]]-- -- Load the common helper functions dofile(openspace.absPath('${SCRIPTS}/common.lua')) - ---openspace.clearKeys() ---helper.setCommonKeys() +dofile(openspace.absPath('${SCRIPTS}/bind_common_keys.lua')) -- Set focuses -openspace.bindKey("o", "openspace.setPropertyValue('Interaction.origin', 'OsirisRex')") -openspace.bindKey("b", "openspace.setPropertyValue('Interaction.origin', 'Bennu2')") +openspace.bindKey( + "a", + "openspace.setPropertyValue('Interaction.origin', 'OsirisRex')", + "Sets the focus of the camera on 'Osiris Rex'." +) +openspace.bindKey( + "s", + "openspace.setPropertyValue('Interaction.origin', 'BennuBarycenter')", + "Sets the focus of the camera on 'Bennu'." +) +openspace.bindKey( + "F6" , + "openspace.printInfo('Set time: Launch');openspace.time.setTime('2016 SEP 08 23:05:00');", + "Sets the time to the launch." +) +openspace.bindKey( + "F7", + "openspace.printInfo('Set time: Gravity Assist');openspace.time.setTime('2017 SEP 22 15:00:00');", + "Sets the time to the Earth gravity assist." +) +openspace.bindKey( + "F8", + "openspace.printInfo('Set time: Approach');openspace.time.setTime('2018-SEP-11 21:31:01.183');", + "Sets the time to the approach at Bennu." +) +openspace.bindKey( + "F9", + "openspace.printInfo('Set time: Preliminary Survey');openspace.time.setTime('2018-NOV-20 01:13:12.183');", + "Sets the time to the preliminary survey of Bennu." +) +openspace.bindKey( + "F10", + "openspace.printInfo('Set time: Orbital B');openspace.time.setTime('2019-APR-08 10:35:27.186');", + "Sets the time to the orbital B event." +) +openspace.bindKey( + "F11", + "openspace.printInfo('Set time: Recon');openspace.time.setTime('2019-MAY-25 03:50:31.195');", + "Sets the time to the recon event." +) --- Quickfix backjumps in Osiris rex -openspace.bindKey("F6" , "openspace.printInfo('Set time: Launch'); openspace.time.setTime('2016 SEP 08 23:05:00');") -openspace.bindKey("F7" , "openspace.printInfo('Set time: Gravity Assist'); openspace.time.setTime('2017 SEP 22 15:00:00');") -openspace.bindKey("F8" , "openspace.printInfo('Set time: Approach'); openspace.time.setTime('2018-SEP-11 21:31:01.183');") -openspace.bindKey("F9" , "openspace.printInfo('Set time: Preliminary Survey'); openspace.time.setTime('2018-NOV-20 01:13:12.183');") -openspace.bindKey("F10", "openspace.printInfo('Set time: Orbital B'); openspace.time.setTime('2019-APR-08 10:35:27.186');") -openspace.bindKey("F11", "openspace.printInfo('Set time: Recon'); openspace.time.setTime('2019-MAY-25 03:50:31.195');") --- OBS!! Avoid key F12 --- Pressing F12 triggers a breakpoint on AMNH Windows machine, with with the following stack trace: --- ntdll.dll!DbgBreakPoint() --- ntdll.dll!DbgUiRemoteBreakin() --- kernel32.dll!BaseThreadInitThunk() --- ntdll.dll!RtUserThreadStart() - -openspace.bindKey("F4", "openspace.scriptScheduler.clear(); openspace.scriptScheduler.load('${OPENSPACE_DATA}/scene/osirisrex/scheduled_scripts.lua');") - -openspace.bindKey("q", helper.property.invert('SunMarker.renderable.enabled')) -openspace.bindKey("e", helper.property.invert('EarthMarker.renderable.enabled')) - -openspace.bindKey("c", "openspace.parallel.setAddress('130.236.142.51');openspace.parallel.setPassword('osiris2016');openspace.parallel.connect();") +openspace.bindKey( + "q", + helper.property.invert('SunMarker.renderable.enabled'), + "Toggles the visibility of the text marking the location of the Sun." +) +openspace.bindKey( + "e", + helper.property.invert('EarthMarker.renderable.enabled'), + "Toggles the visibility of the text marking the location of the Earth." +) diff --git a/scripts/bind_keys_rosetta.lua b/scripts/bind_keys_rosetta.lua index 0837db0c7c..5683217018 100644 --- a/scripts/bind_keys_rosetta.lua +++ b/scripts/bind_keys_rosetta.lua @@ -1,4 +1,4 @@ ---[[ OpenSpace keybinding script ]]-- +--[[ OpenSpace keybinding script loaded from the rosetta.scene file ]]-- -- This script sets the default keybindings and is executed at startup -- Load the common helper functions @@ -12,16 +12,57 @@ helper.setDeltaTimeKeys({ 28800, 57600, 115200, 230400, 460800, 921600, 1843200, 3686400, 7372800, 14745600 }) -openspace.bindKey("a", "openspace.setPropertyValue('Interaction.origin', '67P')") -openspace.bindKey("s", "openspace.setPropertyValue('Interaction.origin', 'Rosetta')") +openspace.bindKey( + "a", + "openspace.setPropertyValue('Interaction.origin', '67P')", + "Sets the focus of the camera on '67P'." +) +openspace.bindKey( + "s", + "openspace.setPropertyValue('Interaction.origin', 'Rosetta')", + "Sets the focus of the camera on 'Rosetta'." +) --- openspace.bindKey("F5", "openspace.setPropertyValue('Interaction.coordinateSystem', 'Sun'); openspace.printInfo('Changing Viewpoint to Sun');"); -openspace.bindKey("F6", "openspace.setPropertyValue('Interaction.coordinateSystem', '67P'); openspace.printInfo('Changing Viewpoint to 67P');"); -openspace.bindKey("F8", "openspace.setPropertyValue('67P.renderable.ProjectionComponent.clearAllProjections', true);"); +openspace.bindKey( + "F5", + "openspace.time.setTime('2014-08-01T03:05:18.101')", + "Jumps to the time of initial approach of Rosetta to 67P." +) +openspace.bindKey( + "F6", + "openspace.time.setTime('2014-11-12T08:20:00.00')", + "Jumps to the time when the Philae lander is released." +) +openspace.bindKey( + "F8", + "openspace.setPropertyValue('67P.renderable.ProjectionComponent.clearAllProjections', true)", + "Removes all image projections from 67P." +) -openspace.bindKey("i", helper.renderable.toggle('ImagePlaneRosetta')) -openspace.bindKey("q", helper.renderable.toggle('SunMarker')) -openspace.bindKey("e", helper.renderable.toggle('JupiterTrail') .. helper.renderable.toggle('SaturnTrail') .. helper.renderable.toggle('UranusTrail') .. helper.renderable.toggle('NeptuneTrail')) -openspace.bindKey("f", helper.renderable.toggle('PhilaeTrail')) +openspace.bindKey( + "i", + helper.renderable.toggle('ImagePlaneRosetta'), + "Toggles the visibility of the free floating image plane." +) +openspace.bindKey( + "q", + helper.renderable.toggle('SunMarker'), + "Toggles the visibility of the text marking the location of the Sun." +) +openspace.bindKey( + "e", + helper.renderable.toggle('JupiterTrail') .. helper.renderable.toggle('SaturnTrail') .. + helper.renderable.toggle('UranusTrail') .. helper.renderable.toggle('NeptuneTrail'), + "Toggles the visibility of all trails further from the Sun than 67P." +) +openspace.bindKey( + "f", + helper.renderable.toggle('PhilaeTrail'), + "Toggles the visibility of Philae's trail." +) -openspace.bindKey("c", "openspace.parallel.setAddress('130.236.142.51');openspace.parallel.setPassword('newhorizons-20150714');openspace.parallel.connect();") +openspace.bindKey( + "p", + helper.property.invert('67P.renderable.ProjectionComponent.performProjection'), + "Enables or disables the image projection on 67P." +) diff --git a/scripts/common.lua b/scripts/common.lua index 265710859d..a20d54ad33 100644 --- a/scripts/common.lua +++ b/scripts/common.lua @@ -12,26 +12,67 @@ helper.scheduledScript.reversible = {} -- Function that sets the most common key bindings that are common to most (all?) -- scenes helper.setCommonKeys = function() - openspace.bindKey("F1", "openspace.gui.toggle()") - openspace.bindKey("F2", "openspace.setPerformanceMeasurement(true)") - openspace.bindKey("F3", "openspace.setPerformanceMeasurement(false)") + openspace.bindKeyLocal( + "F1", + helper.property.invert('Global Properties.OnScreenGUI.Main.enabled'), + "Toggles the visibility of the on-screen GUI." + ) + openspace.bindKeyLocal( + "F2", + helper.property.invert("RenderEngine.performanceMeasurements"), + "Toogles performance measurements that shows rendering time informations." + ) - openspace.bindKey("t", "openspace.toggleFrametimeType(1)") - openspace.bindKey("Shift+t", "openspace.toggleFrametimeType(0)") + openspace.bindKeyLocal( + "ESC", + "openspace.toggleShutdown()", + "Toggles the shutdown that will stop OpenSpace after a grace period. Press again to cancel the shutdown during this period." + ) - openspace.bindKey("ESC", "openspace.toggleShutdown()") + openspace.bindKeyLocal( + "PRINT_SCREEN", + "openspace.takeScreenshot()", + "Saves the contents of the screen to a file in the working directory." + ) + openspace.bindKey( + "SPACE", + "openspace.time.togglePause()", + "Starts and stops the simulation time." + ) - openspace.bindKey("PRINT_SCREEN", "openspace.takeScreenshot()") - openspace.bindKey("SPACE", "openspace.time.togglePause()") + openspace.bindKey( + "COMMA", + "openspace.setRenderer('Framebuffer');", + "Changes the currently used renderer to use the 'Framebuffer' implementation." + ) + openspace.bindKey( + "PERIOD", + "openspace.setRenderer('ABuffer');", + "Changes the currently used renderer to use the 'ABuffer' implementation." + ) - openspace.bindKey("COMMA", "openspace.setRenderer('Framebuffer');") - openspace.bindKey("PERIOD", "openspace.setRenderer('ABuffer');") + openspace.bindKey( + "f", + helper.property.invert('Interaction.horizontalFriction'), + "Toggles the horizontal friction of the camera. If it is disabled, the camera rotates around the focus object indefinitely." + ) + openspace.bindKey( + "Shift+f", + helper.property.invert('Interaction.verticalFriction'), + "Toggles the vertical friction of the camera. If it is disabled, the camera rises up from or closes in towards the focus object indefinitely." + ) + openspace.bindKey( + "Ctrl+f", + helper.property.invert('Interaction.rotationalFriction'), + "Toggles the rotational friction of the camera. If it is disabled, the camera rotates around its own axis indefinitely." + ) - openspace.bindKey("f", helper.property.invert('Interaction.rotationalFriction')) - openspace.bindKey("Shift+f", helper.property.invert('Interaction.zoomFriction')) - - openspace.bindKey("w", "openspace.toggleFade(3)") + openspace.bindKey( + "w", + "openspace.toggleFade(3)", + "Toggles the fade to black within 3 seconds or shows the rendering after 3 seconds." + ) end helper.setDeltaTimeKeys = function(t) @@ -48,7 +89,11 @@ helper.setDeltaTimeKeys = function(t) end for i, v in ipairs(t) do - openspace.bindKey(Keys[i], 'openspace.time.setDeltaTime(' .. v .. ")") + openspace.bindKey( + Keys[i], + 'openspace.time.setDeltaTime(' .. v .. ")", + 'Setting the simulation speed to ' .. v .. ' seconds per realtime second' + ) end end @@ -62,7 +107,7 @@ end helper.property.increment = function(property, value) local v = value or 1 local escaped_property = "'" .. property .. "'" - return "openspace.setPropertyValue(" .. escaped_property .. ", openspace.getPropertyValue(" .. escaped_property .. ") + " .. v .. ")" + return "openspace.setPropertyValue(" .. escaped_property .. ", openspace.getPropertyValue(" .. escaped_property .. ") + " .. v .. ");" end -- Function that returns the string that decrements the 'property' by the 'value' @@ -86,10 +131,8 @@ helper.scheduledScript.reversible.setEnabled = function(time, renderable, enable return { Time = time, - ReversibleLuaScript = { - Forward = helper.renderable.setEnabled(renderable, enabled), - Backward = helper.renderable.setEnabled(renderable, not enabled) - } + ForwardScript = helper.renderable.setEnabled(renderable, enabled), + BackwardScript = helper.renderable.setEnabled(renderable, not enabled) } end @@ -97,9 +140,6 @@ helper.scheduledScript.setEnabled = function(time, renderable, enabled) return { Time = time, - ReversibleLuaScript = { - Forward = helper.renderable.setEnabled(renderable, enabled), - Backward = "" - } + ForwardScript = helper.renderable.setEnabled(renderable, enabled) } -end \ No newline at end of file +end diff --git a/shaders/PowerScaling/powerScalingMath.hglsl b/shaders/PowerScaling/powerScalingMath.hglsl index 035b21a958..58ffd0d978 100644 --- a/shaders/PowerScaling/powerScalingMath.hglsl +++ b/shaders/PowerScaling/powerScalingMath.hglsl @@ -30,7 +30,7 @@ const float k = 10.0; const float FLT_MAX = 1e38; // Not max but large enough for the purpose float log10(float x) { - return log(x) / log(10); + return log(x) / log(10.0); } vec4 psc_normalization(vec4 v) { diff --git a/shaders/abuffer/postrenderabuffer.frag b/shaders/abuffer/postrenderabuffer.frag deleted file mode 100644 index 53136ea591..0000000000 --- a/shaders/abuffer/postrenderabuffer.frag +++ /dev/null @@ -1,130 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014 - 2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#include "fragment.glsl" -#include <#{fragmentPath}> -#include "abufferfragment.glsl" -#include "abufferresources.glsl" -#include "PowerScaling/powerScalingMath.hglsl" -#include "rand.glsl" -#include "resolveconstants.glsl" - -#include "resolvehelpers.glsl" - -#define RAYCASTING_ENABLED #{resolveData.raycastingEnabled} -uniform float blackoutFactor; -uniform sampler2DMS mainColorTexture; -uniform sampler2DMS mainDepthTexture; - -out vec4 _out_color_; - -void main() { - - Fragment newFrag = getFragment(); - int sampleMask = gl_SampleMaskIn[0]; - - float fboDepth = denormalizeFloat(texelFetch(mainDepthTexture, ivec2(gl_FragCoord), 0).x); - vec4 fboRgba = texelFetch(mainColorTexture, ivec2(gl_FragCoord), 0); - - if (newFrag.depth > fboDepth) { - discard; - } - - //newFrag.color *= countSamples(sampleMask) / nAaSamples; -/* - vec3 accumulatedColor = vec3(0.0); - - // One alpha channel per color channel to allow for - // absorption of different wavelengths. - // Always within the interval [0, 1] - vec3 accumulatedAlpha = vec3(0.0); - - - uint nFrags = loadFragments(); - uint raycasterMask; -#if RAYCASTING_ENABLED - bool insideAnyRaycaster = initRaycasterMask(raycasterMask); -#endif - - -#if RAYCASTING_ENABLED - retrieveRaycasterData(nFrags); - - if (insideAnyRaycaster) { - //raycast to the first fragment - float startDepth = 0; - float endDepth = min(_depth_(fragments[0]), newFrag.depth); - raycast(endDepth - startDepth, raycasterMask, accumulatedColor, accumulatedAlpha); - } -#endif - - for (uint i = 0; i < nFrags; i++) { - ABufferFragment frag = fragments[i]; - - if (_depth_(frag) > newFrag.depth) { - break; - } - - int type = _type_(frag); - uint blend = _blend_(frag); - - if (type == 0) { // geometry fragment - vec4 color = _color_(frag); - if (blend == BLEND_MODE_NORMAL) { - accumulatedColor += (1 - accumulatedAlpha) * color.rgb * color.a; - accumulatedAlpha += (1 - accumulatedAlpha) * color.aaa; - } else if (blend == BLEND_MODE_ADDITIVE) { - accumulatedColor += (1 - accumulatedAlpha) * color.rgb; - } - } -#if RAYCASTING_ENABLED - else if (type > 0) { // enter volume - int raycasterId = type - 1; - // only enter volume if a valid scale was detected - if (raycasterData[raycasterId].scale > 0) { - raycasterMask |= (1 << (raycasterId)); - } - } else { // exit volume - int raycasterId = -type - 1; - raycasterMask &= INT_MAX - (1 << (raycasterId)); - } - // Ray cast to next fragment - if (i + 1 < nFrags && raycasterMask != 0) { - float startDepth = _depth_(fragments[i]); - float endDepth = min(_depth_(fragments[i + 1]), newFrag.depth); - raycast(endDepth - startDepth, raycasterMask, accumulatedColor, accumulatedAlpha); - } -#endif - } -*/ - - - vec4 newColor = newFrag.color; - vec3 contribution = newColor.rgb * blackoutFactor; - - _out_color_ = vec4(contribution, 1.0); - // _out_color_ = vec4(1.0); - -} - diff --git a/shaders/fragment.glsl b/shaders/fragment.glsl index c409fbd073..1d122a49b9 100644 --- a/shaders/fragment.glsl +++ b/shaders/fragment.glsl @@ -25,8 +25,8 @@ #ifndef _FRAGMENT_GLSL_ #define _FRAGMENT_GLSL_ -#define BLEND_MODE_NORMAL 0 -#define BLEND_MODE_ADDITIVE 1 +#define BLEND_MODE_NORMAL 0u +#define BLEND_MODE_ADDITIVE 1u struct Fragment { vec4 color; diff --git a/shaders/framebuffer/raycastframebuffer.frag b/shaders/framebuffer/raycastframebuffer.frag index 0eab935531..375bed06b7 100644 --- a/shaders/framebuffer/raycastframebuffer.frag +++ b/shaders/framebuffer/raycastframebuffer.frag @@ -30,7 +30,7 @@ uniform sampler2DMS mainDepthTexture; uniform bool insideRaycaster; uniform vec3 cameraPosInRaycaster; - +uniform vec2 windowSize; #include "blending.glsl" #include "rand.glsl" @@ -56,8 +56,7 @@ uniform int nAaSamples; void main() { - vec2 texCoord = vec2(gl_FragCoord.x / #{rendererData.windowWidth}, - gl_FragCoord.y / #{rendererData.windowHeight}); + vec2 texCoord = vec2(gl_FragCoord.xy / windowSize); vec4 exitColorTexture = texture(exitColorTexture, texCoord); diff --git a/shaders/postRender.frag b/shaders/postRender.frag deleted file mode 100644 index d290bd70c7..0000000000 --- a/shaders/postRender.frag +++ /dev/null @@ -1,2 +0,0 @@ -#version __CONTEXT__ -#include <#{rendererData.postFragmentRendererPath}> \ No newline at end of file diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index adb4caf015..6522114623 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -47,14 +47,6 @@ set(OPENSPACE_SOURCE ${OPENSPACE_BASE_DIR}/src/interaction/keyboardcontroller.cpp ${OPENSPACE_BASE_DIR}/src/interaction/luaconsole.cpp ${OPENSPACE_BASE_DIR}/src/interaction/luaconsole_lua.inl - ${OPENSPACE_BASE_DIR}/src/interaction/mousecontroller.cpp - ${OPENSPACE_BASE_DIR}/src/interaction/externalcontrol/externalconnectioncontroller.cpp - ${OPENSPACE_BASE_DIR}/src/interaction/externalcontrol/externalcontrol.cpp - ${OPENSPACE_BASE_DIR}/src/interaction/externalcontrol/joystickexternalcontrol.cpp - ${OPENSPACE_BASE_DIR}/src/interaction/externalcontrol/keyboardexternalcontrol.cpp - ${OPENSPACE_BASE_DIR}/src/interaction/externalcontrol/mouseexternalcontrol.cpp - ${OPENSPACE_BASE_DIR}/src/interaction/externalcontrol/pythonexternalcontrol.cpp - ${OPENSPACE_BASE_DIR}/src/interaction/externalcontrol/randomexternalcontrol.cpp ${OPENSPACE_BASE_DIR}/src/mission/mission.cpp ${OPENSPACE_BASE_DIR}/src/mission/missionmanager.cpp ${OPENSPACE_BASE_DIR}/src/mission/missionmanager_lua.inl @@ -65,15 +57,61 @@ set(OPENSPACE_SOURCE ${OPENSPACE_BASE_DIR}/src/performance/performancemeasurement.cpp ${OPENSPACE_BASE_DIR}/src/performance/performancelayout.cpp ${OPENSPACE_BASE_DIR}/src/performance/performancemanager.cpp - ${OPENSPACE_BASE_DIR}/src/properties/matrixproperty.cpp ${OPENSPACE_BASE_DIR}/src/properties/optionproperty.cpp ${OPENSPACE_BASE_DIR}/src/properties/property.cpp ${OPENSPACE_BASE_DIR}/src/properties/propertyowner.cpp - ${OPENSPACE_BASE_DIR}/src/properties/scalarproperty.cpp ${OPENSPACE_BASE_DIR}/src/properties/selectionproperty.cpp ${OPENSPACE_BASE_DIR}/src/properties/stringproperty.cpp ${OPENSPACE_BASE_DIR}/src/properties/triggerproperty.cpp - ${OPENSPACE_BASE_DIR}/src/properties/vectorproperty.cpp + ${OPENSPACE_BASE_DIR}/src/properties/matrix/dmat2property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/matrix/dmat2x3property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/matrix/dmat2x4property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/matrix/dmat3x2property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/matrix/dmat3property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/matrix/dmat3x4property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/matrix/dmat4x2property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/matrix/dmat4x3property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/matrix/dmat4property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/matrix/mat2property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/matrix/mat2x3property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/matrix/mat2x4property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/matrix/mat3x2property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/matrix/mat3property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/matrix/mat3x4property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/matrix/mat4x2property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/matrix/mat4x3property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/matrix/mat4property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/scalar/boolproperty.cpp + ${OPENSPACE_BASE_DIR}/src/properties/scalar/charproperty.cpp + ${OPENSPACE_BASE_DIR}/src/properties/scalar/doubleproperty.cpp + ${OPENSPACE_BASE_DIR}/src/properties/scalar/floatproperty.cpp + ${OPENSPACE_BASE_DIR}/src/properties/scalar/intproperty.cpp + ${OPENSPACE_BASE_DIR}/src/properties/scalar/longdoubleproperty.cpp + ${OPENSPACE_BASE_DIR}/src/properties/scalar/longlongproperty.cpp + ${OPENSPACE_BASE_DIR}/src/properties/scalar/longproperty.cpp + ${OPENSPACE_BASE_DIR}/src/properties/scalar/shortproperty.cpp + ${OPENSPACE_BASE_DIR}/src/properties/scalar/signedcharproperty.cpp + ${OPENSPACE_BASE_DIR}/src/properties/scalar/ucharproperty.cpp + ${OPENSPACE_BASE_DIR}/src/properties/scalar/uintproperty.cpp + ${OPENSPACE_BASE_DIR}/src/properties/scalar/ulonglongproperty.cpp + ${OPENSPACE_BASE_DIR}/src/properties/scalar/ulongproperty.cpp + ${OPENSPACE_BASE_DIR}/src/properties/scalar/ushortproperty.cpp + ${OPENSPACE_BASE_DIR}/src/properties/scalar/wcharproperty.cpp + ${OPENSPACE_BASE_DIR}/src/properties/vector/bvec2property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/vector/bvec3property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/vector/bvec4property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/vector/dvec2property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/vector/dvec3property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/vector/dvec4property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/vector/ivec2property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/vector/ivec3property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/vector/ivec4property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/vector/uvec2property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/vector/uvec3property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/vector/uvec4property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/vector/vec2property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/vector/vec3property.cpp + ${OPENSPACE_BASE_DIR}/src/properties/vector/vec4property.cpp ${OPENSPACE_BASE_DIR}/src/query/query.cpp ${OPENSPACE_BASE_DIR}/src/rendering/abufferrenderer.cpp ${OPENSPACE_BASE_DIR}/src/rendering/framebufferrenderer.cpp @@ -83,7 +121,7 @@ set(OPENSPACE_SOURCE ${OPENSPACE_BASE_DIR}/src/rendering/renderengine_lua.inl ${OPENSPACE_BASE_DIR}/src/rendering/screenspacerenderable.cpp ${OPENSPACE_BASE_DIR}/src/rendering/transferfunction.cpp - ${OPENSPACE_BASE_DIR}/src/scene/ephemeris.cpp + ${OPENSPACE_BASE_DIR}/src/scene/translation.cpp ${OPENSPACE_BASE_DIR}/src/scene/rotation.cpp ${OPENSPACE_BASE_DIR}/src/scene/scale.cpp ${OPENSPACE_BASE_DIR}/src/scene/scene.cpp @@ -94,8 +132,9 @@ set(OPENSPACE_SOURCE ${OPENSPACE_BASE_DIR}/src/scene/scenegraphnode_doc.inl ${OPENSPACE_BASE_DIR}/src/scripting/lualibrary.cpp ${OPENSPACE_BASE_DIR}/src/scripting/scriptengine.cpp - ${OPENSPACE_BASE_DIR}/src/scripting/scriptscheduler.cpp ${OPENSPACE_BASE_DIR}/src/scripting/scriptengine_lua.inl + ${OPENSPACE_BASE_DIR}/src/scripting/scriptscheduler.cpp + ${OPENSPACE_BASE_DIR}/src/scripting/scriptscheduler_lua.inl ${OPENSPACE_BASE_DIR}/src/util/blockplaneintersectiongeometry.cpp ${OPENSPACE_BASE_DIR}/src/util/boxgeometry.cpp ${OPENSPACE_BASE_DIR}/src/util/camera.cpp @@ -113,9 +152,11 @@ set(OPENSPACE_SOURCE ${OPENSPACE_BASE_DIR}/src/util/syncdata.cpp ${OPENSPACE_BASE_DIR}/src/util/histogram.cpp ${OPENSPACE_BASE_DIR}/src/util/time.cpp + ${OPENSPACE_BASE_DIR}/src/util/timemanager.cpp ${OPENSPACE_BASE_DIR}/src/util/time_lua.inl ${OPENSPACE_BASE_DIR}/src/util/timerange.cpp ${OPENSPACE_BASE_DIR}/src/util/transformationmanager.cpp + ${OPENSPACE_BASE_DIR}/src/util/gpudata.cpp ) set(OPENSPACE_HEADER @@ -140,14 +181,6 @@ set(OPENSPACE_HEADER ${OPENSPACE_BASE_DIR}/include/openspace/interaction/interactionmode.h ${OPENSPACE_BASE_DIR}/include/openspace/interaction/keyboardcontroller.h ${OPENSPACE_BASE_DIR}/include/openspace/interaction/luaconsole.h - ${OPENSPACE_BASE_DIR}/include/openspace/interaction/mousecontroller.h - ${OPENSPACE_BASE_DIR}/include/openspace/interaction/externalcontrol/externalconnectioncontroller.h - ${OPENSPACE_BASE_DIR}/include/openspace/interaction/externalcontrol/externalcontrol.h - ${OPENSPACE_BASE_DIR}/include/openspace/interaction/externalcontrol/joystickexternalcontrol.h - ${OPENSPACE_BASE_DIR}/include/openspace/interaction/externalcontrol/keyboardexternalcontrol.h - ${OPENSPACE_BASE_DIR}/include/openspace/interaction/externalcontrol/mouseexternalcontrol.h - ${OPENSPACE_BASE_DIR}/include/openspace/interaction/externalcontrol/pythonexternalcontrol.h - ${OPENSPACE_BASE_DIR}/include/openspace/interaction/externalcontrol/randomexternalcontrol.h ${OPENSPACE_BASE_DIR}/include/openspace/mission/mission.h ${OPENSPACE_BASE_DIR}/include/openspace/mission/missionmanager.h ${OPENSPACE_BASE_DIR}/include/openspace/network/networkengine.h @@ -171,6 +204,55 @@ set(OPENSPACE_HEADER ${OPENSPACE_BASE_DIR}/include/openspace/properties/templateproperty.inl ${OPENSPACE_BASE_DIR}/include/openspace/properties/triggerproperty.h ${OPENSPACE_BASE_DIR}/include/openspace/properties/vectorproperty.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/matrix/dmat2property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/matrix/dmat2x3property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/matrix/dmat2x4property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/matrix/dmat3x2property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/matrix/dmat3property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/matrix/dmat3x4property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/matrix/dmat4x2property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/matrix/dmat4x3property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/matrix/dmat4property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/matrix/mat2property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/matrix/mat2x3property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/matrix/mat2x4property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/matrix/mat3x2property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/matrix/mat3property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/matrix/mat3x4property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/matrix/mat4x2property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/matrix/mat4x3property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/matrix/mat4property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/scalar/boolproperty.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/scalar/charproperty.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/scalar/doubleproperty.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/scalar/floatproperty.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/scalar/intproperty.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/scalar/longdoubleproperty.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/scalar/longlongproperty.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/scalar/longproperty.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/scalar/shortproperty.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/scalar/signedcharproperty.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/scalar/ucharproperty.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/scalar/uintproperty.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/scalar/ulonglongproperty.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/scalar/ulongproperty.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/scalar/ushortproperty.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/scalar/wcharproperty.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/vector/bvec2property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/vector/bvec3property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/vector/bvec4property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/vector/dvec2property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/vector/dvec3property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/vector/dvec4property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/vector/ivec2property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/vector/ivec3property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/vector/ivec4property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/vector/uvec2property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/vector/uvec3property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/vector/uvec4property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/vector/vec2property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/vector/vec3property.h + ${OPENSPACE_BASE_DIR}/include/openspace/properties/vector/vec4property.h ${OPENSPACE_BASE_DIR}/include/openspace/query/query.h ${OPENSPACE_BASE_DIR}/include/openspace/rendering/abufferrenderer.h ${OPENSPACE_BASE_DIR}/include/openspace/rendering/framebufferrenderer.h @@ -183,7 +265,7 @@ set(OPENSPACE_HEADER ${OPENSPACE_BASE_DIR}/include/openspace/rendering/screenspacerenderable.h ${OPENSPACE_BASE_DIR}/include/openspace/rendering/volumeraycaster.h ${OPENSPACE_BASE_DIR}/include/openspace/rendering/transferfunction.h - ${OPENSPACE_BASE_DIR}/include/openspace/scene/ephemeris.h + ${OPENSPACE_BASE_DIR}/include/openspace/scene/translation.h ${OPENSPACE_BASE_DIR}/include/openspace/scene/rotation.h ${OPENSPACE_BASE_DIR}/include/openspace/scene/scale.h ${OPENSPACE_BASE_DIR}/include/openspace/scene/scene.h @@ -210,9 +292,12 @@ set(OPENSPACE_HEADER ${OPENSPACE_BASE_DIR}/include/openspace/util/syncbuffer.h ${OPENSPACE_BASE_DIR}/include/openspace/util/syncdata.h ${OPENSPACE_BASE_DIR}/include/openspace/util/time.h + ${OPENSPACE_BASE_DIR}/include/openspace/util/timemanager.h + ${OPENSPACE_BASE_DIR}/include/openspace/util/timerange.h ${OPENSPACE_BASE_DIR}/include/openspace/util/updatestructures.h ${OPENSPACE_BASE_DIR}/include/openspace/util/transformationmanager.h ${OPENSPACE_BASE_DIR}/include/openspace/util/histogram.h + ${OPENSPACE_BASE_DIR}/include/openspace/util/gpudata.h ) # Place files into source groups diff --git a/src/documentation/core_registration.cpp b/src/documentation/core_registration.cpp index 8f89f4621e..946a87e494 100644 --- a/src/documentation/core_registration.cpp +++ b/src/documentation/core_registration.cpp @@ -26,23 +26,34 @@ #include #include +#include +#include +#include +#include +#include #include +#include #include #include -#include #include #include #include #include +#include +#include +#include +#include +#include #include +#ifdef OPENSPACE_MODULE_ONSCREENGUI_ENABLED +#include +#endif namespace openspace { -namespace documentation { void registerCoreClasses(documentation::DocumentationEngine& engine) { engine.addDocumentation(ConfigurationManager::Documentation()); - engine.addDocumentation(Ephemeris::Documentation()); engine.addDocumentation(Mission::Documentation()); engine.addDocumentation(Renderable::Documentation()); engine.addDocumentation(Rotation::Documentation()); @@ -51,7 +62,22 @@ void registerCoreClasses(documentation::DocumentationEngine& engine) { engine.addDocumentation(SceneGraphNode::Documentation()); engine.addDocumentation(ScreenSpaceRenderable::Documentation()); engine.addDocumentation(TimeRange::Documentation()); + engine.addDocumentation(Translation::Documentation()); +} + +void registerCoreClasses(scripting::ScriptEngine& engine) { + engine.addLibrary(OpenSpaceEngine::luaLibrary()); + engine.addLibrary(SpiceManager::luaLibrary()); + engine.addLibrary(RenderEngine::luaLibrary()); + engine.addLibrary(Scene::luaLibrary()); + engine.addLibrary(Time::luaLibrary()); + engine.addLibrary(interaction::InteractionHandler::luaLibrary()); + engine.addLibrary(LuaConsole::luaLibrary()); + engine.addLibrary(ParallelConnection::luaLibrary()); + engine.addLibrary(ModuleEngine::luaLibrary()); + engine.addLibrary(scripting::ScriptScheduler::luaLibrary()); + engine.addLibrary(WindowWrapper::luaLibrary()); + engine.addLibrary(MissionManager::luaLibrary()); } -} // namespace documentation } // namespace openspace diff --git a/src/documentation/documentationengine.cpp b/src/documentation/documentationengine.cpp index d82fdcca01..0181f0178d 100644 --- a/src/documentation/documentationengine.cpp +++ b/src/documentation/documentationengine.cpp @@ -24,14 +24,26 @@ #include +#include #include #include +#include #include +#include #include +namespace { + const std::string MainTemplateFilename = "${OPENSPACE_DATA}/web/documentation/main.hbs"; + const std::string DocumentationTemplateFilename = "${OPENSPACE_DATA}/web/documentation/documentation.hbs"; + const std::string HandlebarsFilename = "${OPENSPACE_DATA}/web/common/handlebars-v4.0.5.js"; + const std::string JsFilename = "${OPENSPACE_DATA}/web/documentation/script.js"; + const std::string BootstrapFilename = "${OPENSPACE_DATA}/web/common/bootstrap.min.css"; + const std::string CssFilename = "${OPENSPACE_DATA}/web/common/style.css"; +} + namespace openspace { namespace documentation { @@ -71,8 +83,27 @@ std::string generateTextDocumentation(const Documentation& d, int& indentLevel) result += indentMessage("Key", (p.key == "*") ? p.key : "\"" + p.key + "\""); result += indentMessage("Optional", (p.optional ? "true" : "false")); result += indentMessage("Type", p.verifier->type()); + result += indentMessage("Documentation", p.documentation); TableVerifier* tv = dynamic_cast(p.verifier.get()); - if (tv) { + ReferencingVerifier* rv = dynamic_cast(p.verifier.get()); + + // We have to check ReferencingVerifier first as a ReferencingVerifier is also a + // TableVerifier + if (rv) { + std::vector documentations = DocEng.documentations(); + auto it = std::find_if( + documentations.begin(), + documentations.end(), + [rv](const Documentation& doc) { return doc.id == rv->identifier; } + ); + + if (it == documentations.end()) { + result += indentMessage("Referencing", rv->identifier + "(NOT FOUND)"); + } + else { + result += indentMessage("Referencing", it->name); + } + } else if (tv) { // We have a TableVerifier, so we need to recurse ++indentLevel; result += generateTextDocumentation({ "", "", tv->documentations }, indentLevel); @@ -97,22 +128,48 @@ std::string generateJsonDocumentation(const Documentation& d) { result << "{"; result << "\"name\": \"" << d.name << "\","; + result << "\"id\": \"" << d.id << "\","; result << "\"entries\": ["; for (const auto& p : d.entries) { result << "{"; result << "\"key\": \"" << p.key << "\","; - result << "\"optional\": \"" << (p.optional ? "true" : "false") << "\","; + result << "\"optional\": " << (p.optional ? "true" : "false") << ","; result << "\"type\": \"" << p.verifier->type() << "\","; + result << "\"documentation\": \"" << p.documentation << "\","; TableVerifier* tv = dynamic_cast(p.verifier.get()); - if (tv) { + ReferencingVerifier* rv = dynamic_cast(p.verifier.get()); + + if (rv) { + std::vector documentations = DocEng.documentations(); + auto it = std::find_if( + documentations.begin(), + documentations.end(), + [rv](const Documentation& doc) { return doc.id == rv->identifier; } + ); + + if (it == documentations.end()) { + result << "\"reference\": { \"found\": false }"; + } else { + result << "\"reference\": {" + << "\"found\": true," + << "\"name\": \"" << it->name << "\"," + << "\"identifier\": \"" << rv->identifier << "\"" + << "}"; + } + } + else if (tv) { std::string json = generateJsonDocumentation({ "", "", tv->documentations }); // We have a TableVerifier, so we need to recurse - result << "\"restrictions\": " << json << ","; + result << "\"restrictions\": " << json; } else { - result << "\"restrictions\": \"" << p.verifier->documentation() << "\","; + result << "\"description\": \"" << p.verifier->documentation() << "\""; } - result << "},"; + result << "}"; + if (&p != &d.entries.back()) { + result << ", "; + } + } result << ']'; @@ -132,6 +189,7 @@ std::string generateHtmlDocumentation(const Documentation& d) { << "\t\t\n" << "\t\t" << p.key << "\n" << "\t\t" << (p.optional ? "Optional" : "Required") << "\n" + << "\t\t" << p.documentation << "\n" << "\t\t" << p.verifier->type() << "\n"; TableVerifier* tv = dynamic_cast(p.verifier.get()); @@ -163,7 +221,7 @@ std::string generateHtmlDocumentation(const Documentation& d) { } else if (tv) { // We have a TableVerifier, so we need to recurse - html << "\n" + html << "
\n" << "\t\n" << "\t\t\n" << "\t\t\t\n" @@ -203,33 +261,87 @@ void DocumentationEngine::writeDocumentation(const std::string& f, const std::st } } else if (t == "html") { + std::ifstream handlebarsInput(absPath(HandlebarsFilename)); + std::ifstream jsInput(absPath(JsFilename)); + + std::string jsContent; + std::back_insert_iterator jsInserter(jsContent); + + std::copy(std::istreambuf_iterator{handlebarsInput}, std::istreambuf_iterator(), jsInserter); + std::copy(std::istreambuf_iterator{jsInput}, std::istreambuf_iterator(), jsInserter); + + std::ifstream bootstrapInput(absPath(BootstrapFilename)); + std::ifstream cssInput(absPath(CssFilename)); + + std::string cssContent; + std::back_insert_iterator cssInserter(cssContent); + + std::copy(std::istreambuf_iterator{bootstrapInput}, std::istreambuf_iterator(), cssInserter); + std::copy(std::istreambuf_iterator{cssInput}, std::istreambuf_iterator(), cssInserter); + + std::ifstream mainTemplateInput(absPath(MainTemplateFilename)); + std::string mainTemplateContent{ std::istreambuf_iterator{mainTemplateInput}, + std::istreambuf_iterator{}}; + + std::ifstream documentationTemplateInput(absPath(DocumentationTemplateFilename)); + std::string documentationTemplateContent{ std::istreambuf_iterator{documentationTemplateInput}, + std::istreambuf_iterator{} }; + std::ofstream file; file.exceptions(~std::ofstream::goodbit); file.open(f); -#ifdef JSON std::stringstream json; json << "["; for (const Documentation& d : _documentations) { json << generateJsonDocumentation(d); - json << ","; + if (&d != &_documentations.back()) { + json << ", "; + } } json << "]"; - std::string jsonText = json.str(); -#else - std::stringstream html; + std::string jsonString = ""; + for (const char& c : json.str()) { + if (c == '\'') { + jsonString += "\\'"; + } else { + jsonString += c; + } + } - html << "\n" + std::stringstream html; + html << "\n" + << "\n" << "\t\n" + << "\t\t\n" + << "\t\t\n" + << "\t\n" + << "\t\n" << "\t\tDocumentation\n" << "\t\n" - << "\n"; + << "\t\n" + << "\t\n" + << "\n"; + file << html.str(); - html << "
\n" +/* + Use this for generating documentation in raw html: + + html << "
\n" << "\t\n\n" << "\t\n" << "\t\t\n" @@ -253,16 +365,18 @@ void DocumentationEngine::writeDocumentation(const std::string& f, const std::st html << "\t\n" << "
Documentation
\n"; - - html << "\n"; - html << "\n"; - - file << html.str(); -#endif +*/ } } void DocumentationEngine::addDocumentation(Documentation doc) { + for (const DocumentationEntry& e : doc.entries) { + ghoul_assert( + e.documentation.find('"') == std::string::npos, + "Documentation cannot contain \" character" + ); + } + if (doc.id.empty()) { _documentations.push_back(std::move(doc)); } diff --git a/src/documentation/verifier.cpp b/src/documentation/verifier.cpp index 4a525f97a8..28b83f13d1 100644 --- a/src/documentation/verifier.cpp +++ b/src/documentation/verifier.cpp @@ -41,6 +41,16 @@ template struct Vector4Verifier; template struct Vector4Verifier; template struct Vector4Verifier; +template struct Matrix2x2Verifier; +template struct Matrix2x3Verifier; +template struct Matrix2x4Verifier; +template struct Matrix3x2Verifier; +template struct Matrix3x3Verifier; +template struct Matrix3x4Verifier; +template struct Matrix4x2Verifier; +template struct Matrix4x3Verifier; +template struct Matrix4x4Verifier; + template struct LessVerifier; template struct LessVerifier; template struct LessEqualVerifier; @@ -159,7 +169,7 @@ TestResult TableVerifier::operator()(const ghoul::Dictionary& dict, const std::string& key) const { if (dict.hasKeyAndValue(key)) { ghoul::Dictionary d = dict.value(key); - TestResult res = testSpecification({ "", documentations, exhaustive }, d); + TestResult res = testSpecification({documentations, exhaustive}, d); // Add the 'key' as a prefix to make the new offender a fully qualified identifer for (TestResult::Offense& s : res.offenses) { @@ -188,6 +198,14 @@ std::string TableVerifier::type() const { return "Table"; } +StringListVerifier::StringListVerifier(std::string elementDocumentation) + : TableVerifier({{ "*", new StringVerifier, std::move(elementDocumentation) }}) +{} + +std::string StringListVerifier::type() const { + return "List of strings"; +} + ReferencingVerifier::ReferencingVerifier(std::string id) : identifier(std::move(id)) { diff --git a/src/engine/configurationmanager.cpp b/src/engine/configurationmanager.cpp index fb0972d471..8463283a9a 100644 --- a/src/engine/configurationmanager.cpp +++ b/src/engine/configurationmanager.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include @@ -70,8 +71,18 @@ const string ConfigurationManager::KeyCapabilitiesVerbosity = const string ConfigurationManager::KeyShutdownCountdown = "ShutdownCountdown"; const string ConfigurationManager::KeyDisableMasterRendering = "DisableRenderingOnMaster"; const string ConfigurationManager::KeyDownloadRequestURL = "DownloadRequestURL"; +const string ConfigurationManager::KeyPerSceneCache = "PerSceneCache"; const string ConfigurationManager::KeyRenderingMethod = "RenderingMethod"; +const string ConfigurationManager::KeyOnScreenTextScaling = "OnScreenTextScaling"; + +const string ConfigurationManager::KeyHttpProxy = "HttpProxy"; +const string ConfigurationManager::PartHttpProxyAddress = "Address"; +const string ConfigurationManager::PartHttpProxyPort = "Port"; +const string ConfigurationManager::PartHttpProxyAuthentication = "Authentication"; +const string ConfigurationManager::PartHttpProxyUser = "User"; +const string ConfigurationManager::PartHttpProxyPassword = "Password"; + string ConfigurationManager::findConfiguration(const string& filename) { using ghoul::filesystem::Directory; diff --git a/src/engine/configurationmanager_doc.inl b/src/engine/configurationmanager_doc.inl index e83cda2239..28c2980a6e 100644 --- a/src/engine/configurationmanager_doc.inl +++ b/src/engine/configurationmanager_doc.inl @@ -31,6 +31,7 @@ Documentation ConfigurationManager::Documentation() { return { "OpenSpace Configuration", + "openspace_configuraion", { { ConfigurationManager::KeyConfigSgct, @@ -41,7 +42,8 @@ Documentation ConfigurationManager::Documentation() { { ConfigurationManager::KeyConfigScene, new StringAnnotationVerifier( - "A valid scene file as described in the Scene documentation"), + "A valid scene file as described in the Scene documentation" + ), "The scene description that is used to populate the application after " "startup. The scene determines which objects are loaded, the startup " "time and other scene-specific settings. More information is provided in " @@ -49,9 +51,7 @@ Documentation ConfigurationManager::Documentation() { }, { ConfigurationManager::KeyPaths, - new TableVerifier({ - { "*", new StringVerifier } - }), + new StringListVerifier, "A list of paths that are automatically registered with the file system. " "If a key X is used in the table, it is then useable by referencing ${X} " "in all other configuration files or scripts.", @@ -59,9 +59,7 @@ Documentation ConfigurationManager::Documentation() { }, { ConfigurationManager::KeyFonts, - new TableVerifier({ - { "*", new StringVerifier, "Font paths loadable by FreeType" } - }), + new StringListVerifier("Font paths loadable by FreeType"), "A list of all fonts that will automatically be loaded on startup. Each " "key-value pair contained in the table will become the name and the file " "for a font.", @@ -74,7 +72,7 @@ Documentation ConfigurationManager::Documentation() { ConfigurationManager::PartLogLevel, new StringInListVerifier( // List from logmanager.cpp::levelFromString - {"Debug", "Info", "Warning", "Error", "Fatal", "None" } + { "Debug", "Info", "Warning", "Error", "Fatal", "None" } ), "The severity of log messages that will be displayed. Only " "messages of the selected level or higher will be displayed. All " @@ -201,8 +199,8 @@ Documentation ConfigurationManager::Documentation() { new StringInListVerifier( // List taken from ScriptEngine::writeLog { "text" } - ), - "The type of logfile that will be created." + ), + "The type of logfile that will be created." }, { ConfigurationManager::PartFile, @@ -284,7 +282,8 @@ Documentation ConfigurationManager::Documentation() { }), "This defines the location and type of the factory documentation file, which " "shows the different types of objects that can be created in the current " - "application configuration." + "application configuration.", + Optional::Yes }, { ConfigurationManager::KeyShutdownCountdown, @@ -294,13 +293,32 @@ Documentation ConfigurationManager::Documentation() { "shutdown is aborted.", Optional::Yes }, + { + ConfigurationManager::KeyPerSceneCache, + new BoolVerifier, + "If this is set to 'true', the name of the scene will be appended to the " + "cache directory, thus not reusing the same directory. This is useful in " + "cases where the same instance of OpenSpace is run with multiple scenes, but " + "the caches should be retained. This value defaults to 'false'.", + Optional::Yes + }, + { + ConfigurationManager::KeyOnScreenTextScaling, + new StringInListVerifier({ + // Values from RenderEngine:updateRenderer + "window", "framebuffer" + }), + "The method for scaling the onscreen text in the window. As the resolution " + "of the rendering can be different from the size of the window, the onscreen " + "text can either be scaled according to the window size ('window'), or the " + "rendering resolution ('framebuffer'). This value defaults to 'window'.", + Optional::Yes + }, { ConfigurationManager::KeyDownloadRequestURL, new OrVerifier( new StringVerifier, - new TableVerifier({ - { "*", new StringVerifier } - }) + new StringListVerifier ), "The URL from which files will be downloaded by the Launcher. This can " "either be a single URL or a list of possible URLs from which the " @@ -324,7 +342,45 @@ Documentation ConfigurationManager::Documentation() { "or just managing the state of the network. This is desired in cases where " "the master computer does not have the resources to render a scene.", Optional::Yes - } + }, + { + ConfigurationManager::KeyHttpProxy, + new TableVerifier({ + { + ConfigurationManager::PartHttpProxyAddress, + new StringVerifier, + "The address of the http proxy" + }, + { + ConfigurationManager::PartHttpProxyPort, + new StringVerifier, + "The port of the http proxy" + }, + { + ConfigurationManager::PartHttpProxyAuthentication, + new StringInListVerifier( + { "basic", "ntlm", "digest", "any" } + ), + "The authentication method of the http proxy", + Optional::Yes + }, + { + ConfigurationManager::PartHttpProxyUser, + new StringVerifier, + "The user of the http proxy", + Optional::Yes + }, + { + ConfigurationManager::PartHttpProxyPassword, + new StringVerifier, + "The password of the http proxy", + Optional::Yes + } + }), + "This defines the use for a proxy when fetching data over http." + "No proxy will be used if this is left out.", + Optional::Yes + } } }; }; diff --git a/src/engine/logfactory.cpp b/src/engine/logfactory.cpp index ffc145d95e..7cf10928ee 100644 --- a/src/engine/logfactory.cpp +++ b/src/engine/logfactory.cpp @@ -27,30 +27,37 @@ #include #include #include +#include #include #include namespace { - const std::string keyType = "Type"; - const std::string keyFilename = "File"; - const std::string keyAppend = "Append"; - const std::string keyTimeStamping = "TimeStamping"; - const std::string keyDateStamping = "DateStamping"; - const std::string keyCategoryStamping = "CategoryStamping"; - const std::string keyLogLevelStamping = "LogLevelStamping"; + const char* keyType = "Type"; + const char* keyFilename = "File"; + const char* keyAppend = "Append"; + const char* keyTimeStamping = "TimeStamping"; + const char* keyDateStamping = "DateStamping"; + const char* keyCategoryStamping = "CategoryStamping"; + const char* keyLogLevelStamping = "LogLevelStamping"; + const char* keyLogLevel = "LogLevel"; - const std::string valueHtmlLog = "html"; - const std::string valueTextLog = "Text"; + const char* valueHtmlLog = "html"; + const char* valueTextLog = "Text"; + + const char* BootstrapPath = "${OPENSPACE_DATA}/web/common/bootstrap.min.css"; + const char* CssPath = "${OPENSPACE_DATA}/web/log/style.css"; + const char* JsPath = "${OPENSPACE_DATA}/web/log/script.js"; } namespace openspace { std::unique_ptr createLog(const ghoul::Dictionary& dictionary) { + using namespace std::string_literals; std::string type; bool typeSuccess = dictionary.getValue(keyType, type); if (!typeSuccess) { throw ghoul::RuntimeError( - "Requested log did not contain key '" + keyType + "'", "LogFactory" + "Requested log did not contain key '"s + keyType + "'", "LogFactory" ); } @@ -58,7 +65,7 @@ std::unique_ptr createLog(const ghoul::Dictionary& dictiona bool filenameSuccess = dictionary.getValue(keyFilename, filename); if (!filenameSuccess) { throw ghoul::RuntimeError( - "Requested log did not contain key '" + keyFilename + "'", "LogFactory" + "Requested log did not contain key '"s + keyFilename + "'", "LogFactory" ); } filename = absPath(filename); @@ -73,6 +80,8 @@ std::unique_ptr createLog(const ghoul::Dictionary& dictiona dictionary.getValue(keyCategoryStamping, categoryStamp); bool logLevelStamp = true; dictionary.getValue(keyLogLevelStamping, logLevelStamp); + std::string logLevel; + dictionary.getValue(keyLogLevel, logLevel); using Append = ghoul::logging::TextLog::Append; using TimeStamping = ghoul::logging::Log::TimeStamping; @@ -81,24 +90,56 @@ std::unique_ptr createLog(const ghoul::Dictionary& dictiona using LogLevelStamping = ghoul::logging::Log::LogLevelStamping; if (type == valueHtmlLog) { - return std::make_unique( - filename, - append ? Append::Yes : Append::No, - timeStamp ? TimeStamping::Yes : TimeStamping::No, - dateStamp ? DateStamping::Yes : DateStamping::No, - categoryStamp ? CategoryStamping::Yes : CategoryStamping::No, - logLevelStamp ? LogLevelStamping::Yes : LogLevelStamping::No - ); + + std::vector cssFiles{absPath(BootstrapPath), absPath(CssPath)}; + std::vector jsFiles{absPath(JsPath)}; + + if (logLevel.empty()) { + return std::make_unique( + filename, + append ? Append::Yes : Append::No, + timeStamp ? TimeStamping::Yes : TimeStamping::No, + dateStamp ? DateStamping::Yes : DateStamping::No, + categoryStamp ? CategoryStamping::Yes : CategoryStamping::No, + logLevelStamp ? LogLevelStamping::Yes : LogLevelStamping::No, + cssFiles, jsFiles + ); + } + else { + return std::make_unique( + filename, + append ? Append::Yes : Append::No, + timeStamp ? TimeStamping::Yes : TimeStamping::No, + dateStamp ? DateStamping::Yes : DateStamping::No, + categoryStamp ? CategoryStamping::Yes : CategoryStamping::No, + logLevelStamp ? LogLevelStamping::Yes : LogLevelStamping::No, + cssFiles, jsFiles, + ghoul::logging::levelFromString(logLevel) + ); + } } else if (type == valueTextLog) { - return std::make_unique( - filename, - append ? Append::Yes : Append::No, - timeStamp ? TimeStamping::Yes : TimeStamping::No, - dateStamp ? DateStamping::Yes : DateStamping::No, - categoryStamp ? CategoryStamping::Yes : CategoryStamping::No, - logLevelStamp ? LogLevelStamping::Yes : LogLevelStamping::No - ); + if (logLevel.empty()) { + return std::make_unique( + filename, + append ? Append::Yes : Append::No, + timeStamp ? TimeStamping::Yes : TimeStamping::No, + dateStamp ? DateStamping::Yes : DateStamping::No, + categoryStamp ? CategoryStamping::Yes : CategoryStamping::No, + logLevelStamp ? LogLevelStamping::Yes : LogLevelStamping::No + ); + } + else { + return std::make_unique( + filename, + append ? Append::Yes : Append::No, + timeStamp ? TimeStamping::Yes : TimeStamping::No, + dateStamp ? DateStamping::Yes : DateStamping::No, + categoryStamp ? CategoryStamping::Yes : CategoryStamping::No, + logLevelStamp ? LogLevelStamping::Yes : LogLevelStamping::No, + ghoul::logging::levelFromString(logLevel) + ); + } } else { throw ghoul::RuntimeError( diff --git a/src/engine/moduleengine.cpp b/src/engine/moduleengine.cpp index 7cc15c84d5..4527c6041f 100644 --- a/src/engine/moduleengine.cpp +++ b/src/engine/moduleengine.cpp @@ -40,8 +40,9 @@ namespace { namespace openspace { void ModuleEngine::initialize() { - for (OpenSpaceModule* m : AllModules()) + for (OpenSpaceModule* m : AllModules()) { registerModule(std::unique_ptr(m)); + } } void ModuleEngine::deinitialize() { @@ -77,11 +78,25 @@ void ModuleEngine::registerModule(std::unique_ptr module) { std::vector ModuleEngine::modules() const { std::vector result; - for (auto& m : _modules) + for (auto& m : _modules) { result.push_back(m.get()); + } return result; } +ghoul::systemcapabilities::OpenGLCapabilitiesComponent::Version +ModuleEngine::requiredOpenGLVersion() const +{ + using Version = ghoul::systemcapabilities::OpenGLCapabilitiesComponent::Version; + Version version = { 0,0 }; + + for (const auto& m : _modules) { + version = std::max(version, m->requiredOpenGLVersion()); + } + + return version; +} + scripting::LuaLibrary ModuleEngine::luaLibrary() { return { "modules", diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index 36455ffcf8..3759113f64 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -38,17 +38,19 @@ #include #include #include -#include +#include #include #include #include #include +#include #include #include -#include +#include #include #include #include +#include #include #include #include @@ -76,7 +78,7 @@ #endif #ifdef OPENSPACE_MODULE_ISWA_ENABLED -#include +#include #include #endif @@ -139,11 +141,12 @@ OpenSpaceEngine::OpenSpaceEngine(std::string programName, , _console(new LuaConsole) , _moduleEngine(new ModuleEngine) , _settingsEngine(new SettingsEngine) + , _timeManager(new TimeManager) , _downloadManager(nullptr) #ifdef OPENSPACE_MODULE_ONSCREENGUI_ENABLED , _gui(new gui::GUI) #endif - , _parallelConnection(new network::ParallelConnection) + , _parallelConnection(new ParallelConnection) , _windowWrapper(std::move(windowWrapper)) , _globalPropertyNamespace(new properties::PropertyOwner) , _isMaster(false) @@ -156,6 +159,7 @@ OpenSpaceEngine::OpenSpaceEngine(std::string programName, _interactionHandler->setPropertyOwner(_globalPropertyNamespace.get()); _globalPropertyNamespace->addPropertySubOwner(_interactionHandler.get()); _globalPropertyNamespace->addPropertySubOwner(_settingsEngine.get()); + _globalPropertyNamespace->addPropertySubOwner(_renderEngine.get()); FactoryManager::initialize(); FactoryManager::ref().addFactory( @@ -163,12 +167,20 @@ OpenSpaceEngine::OpenSpaceEngine(std::string programName, "Renderable" ); FactoryManager::ref().addFactory( - std::make_unique>(), - "Ephemeris" + std::make_unique>(), + "Translation" ); + FactoryManager::ref().addFactory( + std::make_unique>(), + "Rotation" + ); + FactoryManager::ref().addFactory( + std::make_unique>(), + "Scale" + ); + SpiceManager::initialize(); Time::initialize(); - ghoul::systemcapabilities::SystemCapabilities::initialize(); TransformationManager::initialize(); } @@ -178,6 +190,7 @@ OpenSpaceEngine::~OpenSpaceEngine() { #ifdef OPENSPACE_MODULE_ONSCREENGUI_ENABLED _gui->deinitializeGL(); #endif + _interactionHandler->deinitialize(); _renderEngine->deinitialize(); _globalPropertyNamespace = nullptr; @@ -218,7 +231,7 @@ bool OpenSpaceEngine::create(int argc, char** argv, // configuration file, we will deinitialize this LogManager and reinitialize it later // with the correct LogLevel LogManager::initialize( - LogManager::LogLevel::Debug, + LogLevel::Debug, ghoul::logging::LogManager::ImmediateFlush::Yes ); LogMgr.addLog(std::make_unique()); @@ -283,10 +296,32 @@ bool OpenSpaceEngine::create(int argc, char** argv, return false; } - if (!commandlineArgumentPlaceholders.cacheFolder.empty()) { + bool hasCacheCommandline = !commandlineArgumentPlaceholders.cacheFolder.empty(); + bool hasCacheConfiguration = _engine->configurationManager().hasKeyAndValue( + ConfigurationManager::KeyPerSceneCache + ); + std::string cacheFolder = absPath("${CACHE}"); + if (hasCacheCommandline) { + cacheFolder = commandlineArgumentPlaceholders.cacheFolder; + //FileSys.registerPathToken( + // "${CACHE}", + // commandlineArgumentPlaceholders.cacheFolder, + // ghoul::filesystem::FileSystem::Override::Yes + //); + } + if (hasCacheConfiguration) { + std::string scene = _engine->configurationManager().value( + ConfigurationManager::KeyConfigScene + ); + cacheFolder += "-" + ghoul::filesystem::File(scene).baseName(); + } + + if (hasCacheCommandline || hasCacheConfiguration) { + LINFO("Old cache: " << absPath("${CACHE}")); + LINFO("New cache: " << cacheFolder); FileSys.registerPathToken( "${CACHE}", - commandlineArgumentPlaceholders.cacheFolder, + cacheFolder, ghoul::filesystem::FileSystem::Override::Yes ); } @@ -312,7 +347,7 @@ bool OpenSpaceEngine::create(int argc, char** argv, // Register modules _engine->_moduleEngine->initialize(); - documentation::registerCoreClasses(DocEng); + registerCoreClasses(DocEng); // After registering the modules, the documentations for the available classes // can be added as well for (OpenSpaceModule* m : _engine->_moduleEngine->modules()) { @@ -357,11 +392,12 @@ void OpenSpaceEngine::destroy() { _engine->_scriptEngine->deinitialize(); delete _engine; - ghoul::systemcapabilities::SystemCapabilities::deinitialize(); FactoryManager::deinitialize(); Time::deinitialize(); SpiceManager::deinitialize(); + ghoul::fontrendering::FontRenderer::deinitialize(); + LogManager::deinitialize(); ghoul::deinitialize(); @@ -398,7 +434,17 @@ bool OpenSpaceEngine::initialize() { verbosity = verbosityMap[v]; } SysCap.logCapabilities(verbosity); - + + // Check the required OpenGL versions of the registered modules + ghoul::systemcapabilities::OpenGLCapabilitiesComponent::Version version = + _engine->_moduleEngine->requiredOpenGLVersion(); + LINFO("Required OpenGL version: " << version.toString()); + + if (OpenGLCap.openGLVersion() < version) { + LFATAL("Module required higher OpenGL version than is supported"); + return false; + } + std::string requestURL = ""; bool success = configurationManager().getValue(ConfigurationManager::KeyDownloadRequestURL, requestURL); if (success) { @@ -407,18 +453,7 @@ bool OpenSpaceEngine::initialize() { // Register Lua script functions LDEBUG("Registering Lua libraries"); - _scriptEngine->addLibrary(OpenSpaceEngine::luaLibrary()); - _scriptEngine->addLibrary(SpiceManager::luaLibrary()); - _scriptEngine->addLibrary(RenderEngine::luaLibrary()); - _scriptEngine->addLibrary(Scene::luaLibrary()); - _scriptEngine->addLibrary(Time::luaLibrary()); - _scriptEngine->addLibrary(interaction::InteractionHandler::luaLibrary()); - _scriptEngine->addLibrary(LuaConsole::luaLibrary()); - _scriptEngine->addLibrary(gui::GUI::luaLibrary()); - _scriptEngine->addLibrary(network::ParallelConnection::luaLibrary()); - _scriptEngine->addLibrary(ModuleEngine::luaLibrary()); - _scriptEngine->addLibrary(ScriptScheduler::luaLibrary()); - _scriptEngine->addLibrary(WindowWrapper::luaLibrary()); + registerCoreClasses(*_scriptEngine); #ifdef OPENSPACE_MODULE_ISWA_ENABLED _scriptEngine->addLibrary(IswaManager::luaLibrary()); @@ -427,54 +462,7 @@ bool OpenSpaceEngine::initialize() { // TODO: Maybe move all scenegraph and renderengine stuff to initializeGL scriptEngine().initialize(); - // If a LuaDocumentationFile was specified, generate it now - const std::string LuaDocumentationType = - ConfigurationManager::KeyLuaDocumentation + "." + ConfigurationManager::PartType; - const std::string LuaDocumentationFile = - ConfigurationManager::KeyLuaDocumentation + "." + ConfigurationManager::PartFile; - - const bool hasLuaDocType = configurationManager().hasKey(LuaDocumentationType); - const bool hasLuaDocFile = configurationManager().hasKey(LuaDocumentationFile); - if (hasLuaDocType && hasLuaDocFile) { - std::string luaDocumentationType; - configurationManager().getValue(LuaDocumentationType, luaDocumentationType); - std::string luaDocumentationFile; - configurationManager().getValue(LuaDocumentationFile, luaDocumentationFile); - - luaDocumentationFile = absPath(luaDocumentationFile); - _scriptEngine->writeDocumentation(luaDocumentationFile, luaDocumentationType); - } - - // If a general documentation was specified, generate it now - const std::string DocumentationType = - ConfigurationManager::KeyDocumentation + '.' + ConfigurationManager::PartType; - const std::string DocumentationFile = - ConfigurationManager::KeyDocumentation + '.' + ConfigurationManager::PartFile; - - const bool hasDocumentationType = configurationManager().hasKey(DocumentationType); - const bool hasDocumentationFile = configurationManager().hasKey(DocumentationFile); - if (hasDocumentationType && hasDocumentationFile) { - std::string documentationType; - configurationManager().getValue(DocumentationType, documentationType); - std::string documentationFile; - configurationManager().getValue(DocumentationFile, documentationFile); - documentationFile = absPath(documentationFile); - DocEng.writeDocumentation(documentationFile, documentationType); - } - - const std::string FactoryDocumentationType = - ConfigurationManager::KeyFactoryDocumentation + '.' + ConfigurationManager::PartType; - - const std::string FactoryDocumentationFile = - ConfigurationManager::KeyFactoryDocumentation + '.' + ConfigurationManager::PartFile; - bool hasFactoryDocumentationType = configurationManager().hasKey(FactoryDocumentationType); - bool hasFactoryDocumentationFile = configurationManager().hasKey(FactoryDocumentationFile); - if (hasFactoryDocumentationType && hasFactoryDocumentationFile) { - std::string type = configurationManager().value(FactoryDocumentationType); - std::string file = configurationManager().value(FactoryDocumentationFile); - - FactoryManager::ref().writeDocumentation(absPath(file), type); - } + writeDocumentation(); bool disableMasterRendering = false; configurationManager().getValue( @@ -494,6 +482,9 @@ bool OpenSpaceEngine::initialize() { _settingsEngine->initialize(); _settingsEngine->setModules(_moduleEngine->modules()); + // Initialize the InteractionHandler + _interactionHandler->initialize(); + // Load a light and a monospaced font loadFonts(); @@ -511,13 +502,13 @@ bool OpenSpaceEngine::initialize() { _renderEngine->setGlobalBlackOutFactor(0.0); _renderEngine->startFading(1, 3.0); - - //_interactionHandler->setKeyboardController(new interaction::KeyboardControllerFixed); - //_interactionHandler->setMouseController(new interaction::OrbitalMouseController); - // Run start up scripts - runPreInitializationScripts(scenePath); - + try { + runPreInitializationScripts(scenePath); + } + catch (const ghoul::RuntimeError& e) { + LFATALC(e.component, e.message); + } #ifdef OPENSPACE_MODULE_ONSCREENGUI_ENABLED LINFO("Initializing GUI"); @@ -526,7 +517,8 @@ bool OpenSpaceEngine::initialize() { [&]() { std::vector res = { _settingsEngine.get(), - _interactionHandler.get() + _interactionHandler.get(), + _renderEngine.get() }; return res; } @@ -578,6 +570,58 @@ bool OpenSpaceEngine::initialize() { return true; } + +void OpenSpaceEngine::writeDocumentation() { + // If a LuaDocumentationFile was specified, generate it now + const std::string LuaDocumentationType = + ConfigurationManager::KeyLuaDocumentation + "." + ConfigurationManager::PartType; + const std::string LuaDocumentationFile = + ConfigurationManager::KeyLuaDocumentation + "." + ConfigurationManager::PartFile; + + const bool hasLuaDocType = configurationManager().hasKey(LuaDocumentationType); + const bool hasLuaDocFile = configurationManager().hasKey(LuaDocumentationFile); + if (hasLuaDocType && hasLuaDocFile) { + std::string luaDocumentationType; + configurationManager().getValue(LuaDocumentationType, luaDocumentationType); + std::string luaDocumentationFile; + configurationManager().getValue(LuaDocumentationFile, luaDocumentationFile); + + luaDocumentationFile = absPath(luaDocumentationFile); + _scriptEngine->writeDocumentation(luaDocumentationFile, luaDocumentationType); + } + + // If a general documentation was specified, generate it now + const std::string DocumentationType = + ConfigurationManager::KeyDocumentation + '.' + ConfigurationManager::PartType; + const std::string DocumentationFile = + ConfigurationManager::KeyDocumentation + '.' + ConfigurationManager::PartFile; + + const bool hasDocumentationType = configurationManager().hasKey(DocumentationType); + const bool hasDocumentationFile = configurationManager().hasKey(DocumentationFile); + if (hasDocumentationType && hasDocumentationFile) { + std::string documentationType; + configurationManager().getValue(DocumentationType, documentationType); + std::string documentationFile; + configurationManager().getValue(DocumentationFile, documentationFile); + documentationFile = absPath(documentationFile); + DocEng.writeDocumentation(documentationFile, documentationType); + } + + const std::string FactoryDocumentationType = + ConfigurationManager::KeyFactoryDocumentation + '.' + ConfigurationManager::PartType; + + const std::string FactoryDocumentationFile = + ConfigurationManager::KeyFactoryDocumentation + '.' + ConfigurationManager::PartFile; + bool hasFactoryDocumentationType = configurationManager().hasKey(FactoryDocumentationType); + bool hasFactoryDocumentationFile = configurationManager().hasKey(FactoryDocumentationFile); + if (hasFactoryDocumentationType && hasFactoryDocumentationFile) { + std::string type = configurationManager().value(FactoryDocumentationType); + std::string file = configurationManager().value(FactoryDocumentationFile); + + FactoryManager::ref().writeDocumentation(absPath(file), type); + } +} + bool OpenSpaceEngine::isInitialized() { return _engine != nullptr; } @@ -630,23 +674,6 @@ void OpenSpaceEngine::runScripts(const ghoul::Dictionary& scripts) { scripts.getValue(key, scriptPath); std::string&& absoluteScriptPath = absPath(scriptPath); _engine->scriptEngine().runScriptFile(absoluteScriptPath); - - //@JK - //temporary solution to ensure that startup scripts may be syncrhonized over parallel connection - std::ifstream scriptFile; - scriptFile.open(absoluteScriptPath.c_str()); - std::string line; - - while(getline(scriptFile,line)){ - //valid line and not a comment - if(line.size() > 0 && line.at(0) != '-'){ - std::string lib, func; - if(_engine->scriptEngine().parseLibraryAndFunctionNames(lib, func, line) && - _engine->scriptEngine().shouldScriptBeSent(lib, func)){ - _engine->scriptEngine().cacheScript(lib, func, line); - } - } - } } } @@ -736,12 +763,18 @@ void OpenSpaceEngine::loadFonts() { LERROR("Error registering font '" << font << "' with key '" << key << "'"); } - bool initSuccess = ghoul::fontrendering::FontRenderer::initialize(); - if (!initSuccess) - LERROR("Error initializing default font renderer"); - - ghoul::fontrendering::FontRenderer::defaultRenderer().setFramebufferSize(glm::vec2(_windowWrapper->currentDrawBufferResolution())); - + try { + bool initSuccess = ghoul::fontrendering::FontRenderer::initialize(); + if (!initSuccess) + LERROR("Error initializing default font renderer"); + + ghoul::fontrendering::FontRenderer::defaultRenderer().setFramebufferSize( + _renderEngine->fontResolution() + ); + } + catch (const ghoul::RuntimeError& err) { + LERRORC(err.component, err.message); + } } void OpenSpaceEngine::configureLogging() { @@ -752,8 +785,6 @@ void OpenSpaceEngine::configureLogging() { const std::string KeyLogs = ConfigurationManager::KeyLogging + '.' + ConfigurationManager::PartLogs; - - if (configurationManager().hasKeyAndValue(KeyLogLevel)) { std::string logLevel; configurationManager().getValue(KeyLogLevel, logLevel); @@ -761,7 +792,7 @@ void OpenSpaceEngine::configureLogging() { bool immediateFlush = false; configurationManager().getValue(KeyLogImmediateFlush, immediateFlush); - LogManager::LogLevel level = LogManager::levelFromString(logLevel); + LogLevel level = ghoul::logging::levelFromString(logLevel); LogManager::deinitialize(); using ImmediateFlush = ghoul::logging::LogManager::ImmediateFlush; LogManager::initialize( @@ -841,21 +872,19 @@ void OpenSpaceEngine::preSynchronization() { _syncEngine->presync(_isMaster); if (_isMaster) { double dt = _windowWrapper->averageDeltaTime(); - - Time::ref().advanceTime(dt); + _timeManager->preSynchronization(dt); auto scheduledScripts = _scriptScheduler->progressTo(Time::ref().j2000Seconds()); - while(scheduledScripts.size()){ - auto scheduledScript = scheduledScripts.front(); - LINFO(scheduledScript); - _scriptEngine->queueScript(scheduledScript); - scheduledScripts.pop(); + for (auto it = scheduledScripts.first; it != scheduledScripts.second; ++it) { + _scriptEngine->queueScript( + *it, ScriptEngine::RemoteScripting::Yes + ); } _interactionHandler->updateInputStates(dt); _renderEngine->updateSceneGraph(); - _interactionHandler->updateCamera(); + _interactionHandler->updateCamera(dt); _renderEngine->camera()->invalidateCache(); _parallelConnection->preSynchronization(); @@ -873,40 +902,33 @@ void OpenSpaceEngine::postSynchronizationPreDraw() { _shutdownCountdown -= _windowWrapper->averageDeltaTime(); } + _renderEngine->updateSceneGraph(); _renderEngine->updateFade(); _renderEngine->updateRenderer(); _renderEngine->updateScreenSpaceRenderables(); _renderEngine->updateShaderPrograms(); if (!_isMaster) { - _renderEngine->updateSceneGraph(); _renderEngine->camera()->invalidateCache(); } // Step the camera using the current mouse velocities which are synced //_interactionHandler->updateCamera(); - - - #ifdef OPENSPACE_MODULE_ONSCREENGUI_ENABLED - if (_isMaster && _gui->isEnabled() && _windowWrapper->isRegularRendering()) { + if (_isMaster && _windowWrapper->isRegularRendering()) { glm::vec2 mousePosition = _windowWrapper->mousePosition(); - glm::ivec2 drawBufferResolution = _windowWrapper->currentDrawBufferResolution(); + //glm::ivec2 drawBufferResolution = _windowWrapper->currentDrawBufferResolution(); glm::ivec2 windowSize = _windowWrapper->currentWindowSize(); + glm::ivec2 renderingSize = _windowWrapper->currentWindowResolution(); uint32_t mouseButtons = _windowWrapper->mouseButtons(2); - - glm::vec2 windowBufferCorrectionFactor = glm::vec2( - static_cast(drawBufferResolution.x) / static_cast(windowSize.x), - static_cast(drawBufferResolution.y) / static_cast(windowSize.y) - ); - double dt = _windowWrapper->averageDeltaTime(); + double dt = std::max(_windowWrapper->averageDeltaTime(), 0.0); _gui->startFrame( static_cast(dt), - glm::vec2(drawBufferResolution), - windowBufferCorrectionFactor, + glm::vec2(windowSize), + _windowWrapper->dpiScaling(), mousePosition, mouseButtons ); @@ -916,9 +938,9 @@ void OpenSpaceEngine::postSynchronizationPreDraw() { // Testing this every frame has minimal impact on the performance --- abock // Debug build: 1-2 us ; Release build: <= 1 us using ghoul::logging::LogManager; - int warningCounter = LogMgr.messageCounter(LogManager::LogLevel::Warning); - int errorCounter = LogMgr.messageCounter(LogManager::LogLevel::Error); - int fatalCounter = LogMgr.messageCounter(LogManager::LogLevel::Fatal); + int warningCounter = LogMgr.messageCounter(LogLevel::Warning); + int errorCounter = LogMgr.messageCounter(LogLevel::Error); + int fatalCounter = LogMgr.messageCounter(LogLevel::Fatal); if (warningCounter > 0) LWARNINGC("Logging", "Number of Warnings raised: " << warningCounter); @@ -944,7 +966,7 @@ void OpenSpaceEngine::postDraw() { if (_console->isVisible()) _console->render(); #ifdef OPENSPACE_MODULE_ONSCREENGUI_ENABLED - if (_gui->isEnabled() && _isMaster && _windowWrapper->isRegularRendering()) + if (_isMaster && _windowWrapper->isRegularRendering()) _gui->endFrame(); #endif } @@ -965,18 +987,18 @@ void OpenSpaceEngine::keyboardCallback(Key key, KeyModifier mod, KeyAction actio #ifdef OPENSPACE_MODULE_ONSCREENGUI_ENABLED if (_gui->isEnabled()) { bool isConsumed = _gui->keyCallback(key, mod, action); - if (isConsumed) + if (isConsumed) { return; + } } #endif - - if (key == _console->commandInputButton() && (action == KeyAction::Press || action == KeyAction::Repeat)) - _console->toggleVisibility(); - - if (!_console->isVisible()) { + if (key == _console->commandInputButton()) { + if (action == KeyAction::Press) { + _console->toggleMode(); + } + } else if (!_console->isVisible()) { _interactionHandler->keyboardCallback(key, mod, action); - } - else { + } else { _console->keyboardCallback(key, mod, action); } } @@ -1002,7 +1024,7 @@ void OpenSpaceEngine::mouseButtonCallback(MouseButton button, MouseAction action #ifdef OPENSPACE_MODULE_ONSCREENGUI_ENABLED if (_gui->isEnabled()) { const bool isConsumed = _gui->mouseButtonCallback(button, action); - if (isConsumed && action != MouseAction::Release) + if (isConsumed /*&& action != MouseAction::Release*/) return; } #endif @@ -1073,6 +1095,12 @@ scripting::LuaLibrary OpenSpaceEngine::luaLibrary() { "", "Toggles the shutdown mode that will close the application after the count" "down timer is reached" + }, + { + "writeDocumentation", + &luascriptfunctions::writeDocumentation, + "", + "Writes out documentation files" } } }; @@ -1141,7 +1169,7 @@ gui::GUI& OpenSpaceEngine::gui() { } #endif -network::ParallelConnection& OpenSpaceEngine::parallelConnection() { +ParallelConnection& OpenSpaceEngine::parallelConnection() { ghoul_assert(_parallelConnection, "ParallelConnection must not be nullptr"); return *_parallelConnection; } @@ -1169,5 +1197,10 @@ DownloadManager& OpenSpaceEngine::downloadManager() { return *_downloadManager; } +TimeManager& OpenSpaceEngine::timeManager() { + ghoul_assert(_timeManager, "Download Manager must not be nullptr"); + return *_timeManager; +} + } // namespace openspace diff --git a/src/engine/openspaceengine_lua.inl b/src/engine/openspaceengine_lua.inl index 7d33f6af76..3d4de94b78 100644 --- a/src/engine/openspaceengine_lua.inl +++ b/src/engine/openspaceengine_lua.inl @@ -41,5 +41,21 @@ int toggleShutdown(lua_State* L) { return 1; } +/** +* \ingroup LuaScripts +* writeDocumentation(): +* Writes out documentation files +*/ +int writeDocumentation(lua_State* L) { + int nArguments = lua_gettop(L); + if (nArguments != 0) + return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments); + + OsEng.writeDocumentation(); + + return 1; +} + + } // namespace luascriptfunctions } // namespace openspace diff --git a/src/engine/settingsengine.cpp b/src/engine/settingsengine.cpp index 45e76077ee..808a2fb5ca 100644 --- a/src/engine/settingsengine.cpp +++ b/src/engine/settingsengine.cpp @@ -28,8 +28,10 @@ #include #include #include +#include #include + #include #include #include @@ -41,20 +43,28 @@ namespace { const std::string _loggerCat = "SettingsEngine"; } - namespace openspace { - - SettingsEngine::SettingsEngine() : _eyeSeparation("eyeSeparation", "Eye Separation" , 0.f, 0.f, 10.f) - , _scenes("scenes", "Scene", properties::OptionProperty::DisplayType::DROPDOWN) + , _scenes("scenes", "Scene", properties::OptionProperty::DisplayType::Dropdown) , _showFrameNumber("showFrameNumber", "Show frame number", false) , _busyWaitForDecode("busyWaitForDecode", "Busy Wait for decode", false) , _logSGCTOutOfOrderErrors("logSGCTOutOfOrderErrors", "Log SGCT out-of-order", false) , _useDoubleBuffering("useDoubleBuffering", "Use double buffering", false) + , _spiceUseExceptions("enableSpiceExceptions", "Enable Spice Exceptions", false) { setName("Global Properties"); + + _spiceUseExceptions.onChange([this]{ + if (_spiceUseExceptions) { + SpiceManager::ref().setExceptionHandling(SpiceManager::UseException::Yes); + } + else { + SpiceManager::ref().setExceptionHandling(SpiceManager::UseException::No); + } + }); + addProperty(_spiceUseExceptions); } void SettingsEngine::initialize() { @@ -133,7 +143,8 @@ void SettingsEngine::initSceneFiles() { std::string sceneDir = "${SCENE}"; std::vector scenes = ghoul::filesystem::Directory(sceneDir).readFiles(); for (std::size_t i = 0; i < scenes.size(); ++i) { - _scenes.addOption(i, scenes[i]); + std::size_t found = scenes[i].find_last_of("/\\"); + _scenes.addOption(i, scenes[i].substr(found+1)); } // Set interaction to change ConfigurationManager and schedule the load diff --git a/src/engine/wrapper/sgctwindowwrapper.cpp b/src/engine/wrapper/sgctwindowwrapper.cpp index c6a2f8a9cd..d70db6044d 100644 --- a/src/engine/wrapper/sgctwindowwrapper.cpp +++ b/src/engine/wrapper/sgctwindowwrapper.cpp @@ -90,12 +90,28 @@ uint32_t SGCTWindowWrapper::mouseButtons(int maxNumber) const { } glm::ivec2 SGCTWindowWrapper::currentWindowSize() const { - return glm::ivec2(sgct::Engine::instance()->getCurrentWindowPtr()->getXResolution(), - sgct::Engine::instance()->getCurrentWindowPtr()->getYResolution()); + auto window = sgct::Engine::instance()->getCurrentWindowPtr(); + switch (window->getStereoMode()) { + case sgct::SGCTWindow::Side_By_Side_Stereo: + case sgct::SGCTWindow::Side_By_Side_Inverted_Stereo: + return glm::ivec2( + window->getXResolution() / 2, + window->getYResolution()); + case sgct::SGCTWindow::Top_Bottom_Stereo: + case sgct::SGCTWindow::Top_Bottom_Inverted_Stereo: + return glm::ivec2( + window->getXResolution(), + window->getYResolution() / 2); + default: + return glm::ivec2( + window->getXResolution(), + window->getYResolution()); + } } glm::ivec2 SGCTWindowWrapper::currentWindowResolution() const { - int x,y; + auto window = sgct::Engine::instance()->getCurrentWindowPtr(); + int x, y; sgct::Engine::instance()->getCurrentWindowPtr()->getFinalFBODimensions(x, y); return glm::ivec2(x, y); } @@ -112,6 +128,13 @@ glm::ivec2 SGCTWindowWrapper::currentDrawBufferResolution() const { } throw WindowWrapperException("No viewport available"); } + +glm::vec2 SGCTWindowWrapper::dpiScaling() const { + return glm::vec2( + sgct::Engine::instance()->getCurrentWindowPtr()->getXScale(), + sgct::Engine::instance()->getCurrentWindowPtr()->getYScale() + ); +} int SGCTWindowWrapper::currentNumberOfAaSamples() const { return sgct::Engine::instance()->getCurrentWindowPtr()->getNumberOfAASamples(); diff --git a/src/engine/wrapper/windowwrapper.cpp b/src/engine/wrapper/windowwrapper.cpp index 6a2ac79009..436c34d87f 100644 --- a/src/engine/wrapper/windowwrapper.cpp +++ b/src/engine/wrapper/windowwrapper.cpp @@ -108,6 +108,10 @@ glm::ivec2 WindowWrapper::currentWindowResolution() const { glm::ivec2 WindowWrapper::currentDrawBufferResolution() const { return currentWindowSize(); } + +glm::vec2 WindowWrapper::dpiScaling() const { + return glm::vec2(1.f); +} int WindowWrapper::currentNumberOfAaSamples() const { return 1; diff --git a/src/interaction/deviceidentifier.cpp b/src/interaction/deviceidentifier.cpp index def1c670a2..2da4ec2509 100644 --- a/src/interaction/deviceidentifier.cpp +++ b/src/interaction/deviceidentifier.cpp @@ -1,3 +1,26 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ // open space includes #include diff --git a/src/interaction/externalcontrol/externalconnectioncontroller.cpp b/src/interaction/externalcontrol/externalconnectioncontroller.cpp deleted file mode 100644 index 5482c9b3de..0000000000 --- a/src/interaction/externalcontrol/externalconnectioncontroller.cpp +++ /dev/null @@ -1,12 +0,0 @@ -#include - -namespace openspace { - -ExternalConnectionController::ExternalConnectionController() { -} - -ExternalConnectionController::~ExternalConnectionController() { - -} - -} // namespace openspace \ No newline at end of file diff --git a/src/interaction/externalcontrol/externalcontrol.cpp b/src/interaction/externalcontrol/externalcontrol.cpp deleted file mode 100644 index 1c279a0dfb..0000000000 --- a/src/interaction/externalcontrol/externalcontrol.cpp +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include -#include -#include - -namespace openspace { - -ExternalControl::ExternalControl() { - -} - -ExternalControl::~ExternalControl() { -} - -void ExternalControl::update() { - -} - -void ExternalControl::rotate(const glm::quat &rotation) { - //OsEng.interactionHandler().rotate(rotation); -} - -void ExternalControl::orbit(const glm::quat &rotation) { - //OsEng.interactionHandler().orbit(rotation); -} - -void ExternalControl::distance(const PowerScaledScalar &distance) { - //OsEng.interactionHandler().distance(distance); -} - - -} // namespace openspace - diff --git a/src/interaction/externalcontrol/joystickexternalcontrol.cpp b/src/interaction/externalcontrol/joystickexternalcontrol.cpp deleted file mode 100644 index 0e5f4500ca..0000000000 --- a/src/interaction/externalcontrol/joystickexternalcontrol.cpp +++ /dev/null @@ -1,63 +0,0 @@ -//#include "externalcontrol/joystickexternalcontrol.h" -//#include "deviceidentifier.h" -// -//// workaround since Python debug does not work on windows -//#ifdef _DEBUG -//#undef _DEBUG -//#include -//#define _DEBUG -//#else -//#include -//#endif -// -//namespace openspace { -// -// -//JoystickExternalControl::JoystickExternalControl(const char *filename): PythonExternalControl(filename) { -//} -// -//void JoystickExternalControl::setInputDevice(const int device) { -// if(device >= 0 && device <= 16) { -// inputDevice_ = device; -// numberOfButtons_ = DeviceIdentifier::ref().getButtons(inputDevice_); -// numberOfAxes_ = DeviceIdentifier::ref().getAxes(inputDevice_); -// clear(); -// pyarrSize_ = numberOfButtons_ + numberOfAxes_; -// pyarr_ = new PyObject*[pyarrSize_]; -// } -// -//} -// -//void JoystickExternalControl::update() { -// -// if(inputDevice_ != -1) { -// float *axesPos; -// unsigned char *buttons; -// DeviceIdentifier::ref().getButtons(inputDevice_, &buttons); -// DeviceIdentifier::ref().getAxes(inputDevice_, &axesPos); -// -// // init array -// for(int i = 0; i < numberOfButtons_; ++i){ -// pyarr_[i] = PyLong_FromLong(buttons[i]); -// } -// for(int i = 0; i < numberOfAxes_; ++i){ -// pyarr_[i+numberOfButtons_] = PyFloat_FromDouble(axesPos[i]); -// } -// } -// -// run(); -// -// if(inputDevice_ != -1) { -// // cleanup -// for(int i = 0; i < pyarrSize_; ++i) { -// Py_DECREF(pyarr_[i]); -// } -// } -// -//} -// -//JoystickExternalControl::~JoystickExternalControl() { -//} -// -//} // namespace openspace -// diff --git a/src/interaction/externalcontrol/keyboardexternalcontrol.cpp b/src/interaction/externalcontrol/keyboardexternalcontrol.cpp deleted file mode 100644 index 3b27afc66e..0000000000 --- a/src/interaction/externalcontrol/keyboardexternalcontrol.cpp +++ /dev/null @@ -1,62 +0,0 @@ -//#include "externalcontrol/keyboardexternalcontrol.h" -// -//// workaround since Python debug does not work on windows -//#ifdef _DEBUG -//#undef _DEBUG -//#include -//#define _DEBUG -//#else -//#include -//#endif -// -// -//namespace openspace { -// -// -//KeyboardExternalControl::KeyboardExternalControl(const char *filename): PythonExternalControl(filename) { -// clear(); -// pyarrSize_ = 'Z' - 'A' + 80; // all letters, 69 special keys, space and 10 numbers -// pyarr_ = new PyObject*[pyarrSize_]; -// for(int i = 0; i < pyarrSize_; ++i) { -// pyarr_[i] = PyLong_FromLong(0); -// } -//} -// -//void KeyboardExternalControl::keyboardCallback(int key, int action) { -// -// //printf("key: %i\n",key); -// int pos = -1; -// if(key >= '0' && key <= '9') { -// pos = key - '0'; -// Py_XDECREF(pyarr_[pos]); -// pyarr_[pos] = PyLong_FromLong(action); -// } else if(key >= 'A' && key <= 'Z') { -// pos = key - 'A' + 10; -// Py_XDECREF(pyarr_[pos]); -// pyarr_[pos] = PyLong_FromLong(action); -// } else if (key > 256 && key < 256+69) { -// pos = key - 256 + 'Z'-'A' +10; -// Py_XDECREF(pyarr_[pos]); -// pyarr_[pos] = PyLong_FromLong(action); -// } else if (key == 32) { -// pos = 'Z' - 'A' + 11; -// Py_XDECREF(pyarr_[pos]); -// pyarr_[pos] = PyLong_FromLong(action); -// } -// //printf("pos: %i\n",pos); -//} -// -// -// -//void KeyboardExternalControl::update() { -// run(); -//} -// -//KeyboardExternalControl::~KeyboardExternalControl() { -// for(int i = 0; i < pyarrSize_; ++i) { -// Py_XDECREF(pyarr_[i]); -// } -//} -// -//} // namespace openspace -// diff --git a/src/interaction/externalcontrol/mouseexternalcontrol.cpp b/src/interaction/externalcontrol/mouseexternalcontrol.cpp deleted file mode 100644 index 41d93bd951..0000000000 --- a/src/interaction/externalcontrol/mouseexternalcontrol.cpp +++ /dev/null @@ -1,79 +0,0 @@ -//#include "externalcontrol/mouseexternalcontrol.h" -// -//// workaround since Python debug does not work on windows -//#ifdef _DEBUG -//#undef _DEBUG -//#include -//#define _DEBUG -//#else -//#include -//#endif -// -// -//namespace openspace { -// -// -//MouseExternalControl::MouseExternalControl(const char *filename): PythonExternalControl(filename) { -// clear(); -// pyarrSize_ = 6*2; -// pyarr_ = new PyObject*[pyarrSize_]; -// x_ = 0; -// y_ = 0; -// pos_ = 0; -// button1_ = 0; -// button2_ = 0; -// button3_ = 0; -// for(int i = 0; i < pyarrSize_; ++i) { -// pyarr_[i] = PyLong_FromLong(0);; -// } -// -//} -// -//void MouseExternalControl::mouseButtonCallback(int key, int action) { -// if(key == 0) -// button1_ = action; -// if(key == 1) -// button2_ = action; -// if(key == 2) -// button3_ = action; -//} -// -//void MouseExternalControl::mousePosCallback(int x, int y) { -// x_ = x; -// y_ = y; -//} -// -//void MouseExternalControl::mouseScrollCallback(int pos) { -// pos_ = pos; -//} -// -//void MouseExternalControl::update() { -// -// pyarr_[6] = pyarr_[0]; -// pyarr_[7] = pyarr_[1]; -// pyarr_[8] = pyarr_[2]; -// pyarr_[9] = pyarr_[3]; -// pyarr_[10] = pyarr_[4]; -// pyarr_[11] = pyarr_[5]; -// pyarr_[0] = PyLong_FromLong(button1_); -// pyarr_[1] = PyLong_FromLong(button2_); -// pyarr_[2] = PyLong_FromLong(button3_); -// pyarr_[3] = PyLong_FromLong(pos_); -// pyarr_[4] = PyLong_FromLong(x_); -// pyarr_[5] = PyLong_FromLong(y_); -// -// run(); -// -// // cleanup -// for(int i = pyarrSize_ / 2; i < pyarrSize_; ++i) { -// Py_XDECREF(pyarr_[i]); -// } -// -//} -// -//MouseExternalControl::~MouseExternalControl() { -// -//} -// -//} // namespace openspace -// diff --git a/src/interaction/externalcontrol/pythonexternalcontrol.cpp b/src/interaction/externalcontrol/pythonexternalcontrol.cpp deleted file mode 100644 index 541421b6d0..0000000000 --- a/src/interaction/externalcontrol/pythonexternalcontrol.cpp +++ /dev/null @@ -1,147 +0,0 @@ -//#include "externalcontrol/pythonexternalcontrol.h" -// -//// workaround since Python debug does not work on windows -//#ifdef _DEBUG -//#undef _DEBUG -//#include -//#define _DEBUG -//#else -//#include -//#endif -// -//#include -//#include -//#include -//#include -//#include "deviceidentifier.h" -// -//#include "util/pss.h" -//#include "externalcontrol/externalcontrol.h" -//#include "interactionhandler.h" -// -//namespace openspace { -// -// -//// defining python callback functions -//static PyObject* pyexcontrol_numargs(PyObject *self, PyObject *args) { -// if(!PyArg_ParseTuple(args, ":pyexcontrol_numargs")) -// return NULL; -// return PyLong_FromLong(10); -//} -// -//static PyObject* pyexcontrol_message(PyObject *self, PyObject *args) -//{ -// char* text = 0; -// if(!PyArg_ParseTuple(args, "s:pyexcontrol_yeah",&text)) -// Py_RETURN_NONE; -// -// PythonExternalControl * ext = 0; -// ext->message(text); -// -// Py_RETURN_NONE; -//} -// -//static PyObject* pyexcontrol_rotateCamera(PyObject *self, PyObject *args) -//{ -// char* text = 0; -// float f1 = 0; -// float f2 = 0; -// float f3 = 0; -// float f4 = 0; -// if(!PyArg_ParseTuple(args, "fff:pyexcontrol_rotateCamera",&f1,&f2,&f3)) -// Py_RETURN_NONE; -// -// double dt = InteractionHandler::ref().getDt(); -// glm::vec3 EulerAngles(f1*dt,f2*dt, f3*dt); -// glm::quat rot = glm::quat(EulerAngles); -// ExternalControl * ext = 0; -// ext->rotate(rot); -// -// Py_RETURN_NONE; -//} -// -//static PyObject* pyexcontrol_orbitCamera(PyObject *self, PyObject *args) -//{ -// char* text = 0; -// float f1 = 0; -// float f2 = 0; -// float f3 = 0; -// if(!PyArg_ParseTuple(args, "fff:pyexcontrol_rotateCamera",&f1,&f2,&f3)) -// Py_RETURN_NONE; -// -// double dt = InteractionHandler::ref().getDt(); -// glm::vec3 EulerAngles(f1*dt,f2*dt, f3*dt); -// glm::quat rot = glm::quat(EulerAngles); -// ExternalControl * ext = 0; -// ext->orbit(rot); -// -// Py_RETURN_NONE; -//} -// -//static PyObject* pyexcontrol_distance(PyObject *self, PyObject *args) -//{ -// char* text = 0; -// float f1 = 0; -// float f2 = 0; -// if(!PyArg_ParseTuple(args, "ff:pyexcontrol_rotateCamera",&f1,&f2)) -// Py_RETURN_NONE; -// -// float dt = static_cast(InteractionHandler::ref().getDt()); -// pss dist(f1*dt,f2); -// ExternalControl * ext = 0; -// ext->distance(dist); -// -// Py_RETURN_NONE; -//} -// -//PyMethodDef* PythonExternalControl::getMethodDef() { -// // creating the python callback function table -// static PyMethodDef pyexcontrol_methods[] = { -// {"numargs", pyexcontrol_numargs, METH_VARARGS, "function"}, -// {"message", pyexcontrol_message, METH_VARARGS, "function"}, -// {"rotate", pyexcontrol_rotateCamera, METH_VARARGS, "function"}, -// {"orbit", pyexcontrol_orbitCamera, METH_VARARGS, "function"}, -// {"distance", pyexcontrol_distance, METH_VARARGS, "function"}, -// {NULL, NULL, 0, NULL} -// }; -// return pyexcontrol_methods; -//} -// -//void PythonExternalControl::message(const char *text) { -// -// printf("Input message from PythonScript: %s\n", text); -//} -// -//PythonExternalControl::PythonExternalControl(const char *filename) { -// pyarr_ = nullptr; -// ps_.load(filename, true); -//} -// -// -//void PythonExternalControl::update() { -// run(); -//} -// -//void PythonExternalControl::run() { -// if(pyarrSize_ > 0) -// ps_.run(pyarrSize_, pyarr_); -// else -// ps_.run(); -//} -// -// -//void PythonExternalControl::clear() { -// if(pyarr_ != nullptr) { -// // cleanup -// delete pyarr_; -// pyarr_ = nullptr; -// pyarrSize_ = 0; -// } -//} -// -//PythonExternalControl::~PythonExternalControl() { -// clear(); -//} -// -//} // namespace openspace -// diff --git a/src/interaction/externalcontrol/randomexternalcontrol.cpp b/src/interaction/externalcontrol/randomexternalcontrol.cpp deleted file mode 100644 index c0d9a1d33c..0000000000 --- a/src/interaction/externalcontrol/randomexternalcontrol.cpp +++ /dev/null @@ -1,60 +0,0 @@ -#include - -#include -#ifndef _WIN32 - #include -#endif - -namespace openspace { - -typedef struct -{ - bool *keepGoing; - double *dx; -} parm; - -void *updatedx(void * arg) { - parm *p = (parm*) arg; - bool *kg = p->keepGoing; - double *dx = p->dx; - while( *kg ) { - //printf("Hello world!\n"); - *dx = *dx + 0.5; - - -#ifndef _WIN32 - // random sleep time - int diff = rand() % 200; - - usleep(10000*diff); -#endif - } - delete p; - return NULL; -} - - -RandomExternalControl::RandomExternalControl() { - /* - inputGuard = PTHREAD_MUTEX_INITIALIZER; - - pthread_attr_t pthread_custom_attr; - pthread_attr_init(&pthread_custom_attr); - keepGoing_ = new bool; - *keepGoing_ = true; - parm *p = (parm*)malloc(sizeof(parm)); - p->keepGoing = keepGoing_; - p->dx = &dx_; - - pthread_create(&backgroundThread, &pthread_custom_attr, updatedx, (void*)p); - */ -} - -RandomExternalControl::~RandomExternalControl() { - *keepGoing_ = false; - //pthread_join(backgroundThread, NULL); - delete keepGoing_; -} - -} // namespace openspace - diff --git a/src/interaction/interactionhandler.cpp b/src/interaction/interactionhandler.cpp index 246ab64d32..94be1f99dd 100644 --- a/src/interaction/interactionhandler.cpp +++ b/src/interaction/interactionhandler.cpp @@ -23,9 +23,12 @@ ****************************************************************************************/ #include +#include +#include #include #include +#include #include #include #include @@ -35,9 +38,12 @@ #include #include + #include -//#include +#ifdef OPENSPACE_MODULE_GLOBEBROWSING_ENABLED +#include +#endif #include @@ -49,6 +55,13 @@ namespace { const std::string KeyFocus = "Focus"; const std::string KeyPosition = "Position"; const std::string KeyRotation = "Rotation"; + + const std::string MainTemplateFilename = "${OPENSPACE_DATA}/web/keybindings/main.hbs"; + const std::string KeybindingTemplateFilename = "${OPENSPACE_DATA}/web/keybindings/keybinding.hbs"; + const std::string HandlebarsFilename = "${OPENSPACE_DATA}/web/common/handlebars-v4.0.5.js"; + const std::string JsFilename = "${OPENSPACE_DATA}/web/keybindings/script.js"; + const std::string BootstrapFilename = "${OPENSPACE_DATA}/web/common/bootstrap.min.css"; + const std::string CssFilename = "${OPENSPACE_DATA}/web/common/style.css"; } #include "interactionhandler_lua.inl" @@ -56,574 +69,6 @@ namespace { namespace openspace { namespace interaction { -#ifdef USE_OLD_INTERACTIONHANDLER - - -InteractionHandler::InteractionHandler() - : properties::PropertyOwner() - , _camera(nullptr) - , _focusNode(nullptr) - , _deltaTime(0.0) - //, _validKeyLua(false) - , _controllerSensitivity(1.f) - , _invertRoll(true) - , _invertRotation(false) - , _keyboardController(nullptr) - , _mouseController(nullptr) - , _origin("origin", "Origin", "") - , _coordinateSystem("coordinateSystem", "Coordinate System", "") - , _currentKeyframeTime(-1.0) -{ - setName("Interaction"); - - _origin.onChange([this](){ - SceneGraphNode* node = sceneGraphNode(_origin.value()); - if (!node) { - LWARNING("Could not find a node in scenegraph called '" << _origin.value() <<"'"); - return; - } - setFocusNode(node); - }); - addProperty(_origin); - - _coordinateSystem.onChange([this](){ - OsEng.renderEngine().changeViewPoint(_coordinateSystem.value()); - }); - addProperty(_coordinateSystem); -} - -InteractionHandler::~InteractionHandler() { - delete _keyboardController; - delete _mouseController; - for (size_t i = 0; i < _controllers.size(); ++i) - delete _controllers[i]; -} - -void InteractionHandler::setKeyboardController(KeyboardController* controller) { - assert(controller); - delete _keyboardController; - _keyboardController = controller; - _keyboardController->setHandler(this); -} - -void InteractionHandler::setMouseController(MouseController* controller) { - assert(controller); - delete _mouseController; - _mouseController = controller; - _mouseController->setHandler(this); -} - -void InteractionHandler::addController(Controller* controller) { - assert(controller); - _controllers.push_back(controller); - controller->setHandler(this); -} - -void InteractionHandler::lockControls() { - _mutex.lock(); -} - -void InteractionHandler::unlockControls() { - _mutex.unlock(); -} - -void InteractionHandler::update(double deltaTime) { - _deltaTime = deltaTime; - _mouseController->update(deltaTime); - - bool hasKeys = false; - psc pos; - glm::quat q; - - _keyframeMutex.lock(); - - if (_keyframes.size() > 4){ //wait until enough samples are buffered - hasKeys = true; - - openspace::network::datamessagestructures::PositionKeyframe p0, p1, p2, p3; - - p0 = _keyframes[0]; - p1 = _keyframes[1]; - p2 = _keyframes[2]; - p3 = _keyframes[3]; - - //interval check - if (_currentKeyframeTime < p1._timeStamp){ - _currentKeyframeTime = p1._timeStamp; - } - - double t0 = p1._timeStamp; - double t1 = p2._timeStamp; - double fact = (_currentKeyframeTime - t0) / (t1 - t0); - - - - //glm::dvec4 v = positionInterpCR.interpolate(fact, _keyframes[0]._position.dvec4(), _keyframes[1]._position.dvec4(), _keyframes[2]._position.dvec4(), _keyframes[3]._position.dvec4()); - glm::dvec4 v = ghoul::interpolateLinear(fact, p1._position.dvec4(), p2._position.dvec4()); - - pos = psc(v.x, v.y, v.z, v.w); - q = ghoul::interpolateLinear(fact, p1._viewRotationQuat, p2._viewRotationQuat); - - //we're done with this sample interval - if (_currentKeyframeTime >= p2._timeStamp){ - _keyframes.erase(_keyframes.begin()); - _currentKeyframeTime = p1._timeStamp; - } - - _currentKeyframeTime += deltaTime; - - } - - _keyframeMutex.unlock(); - - if (hasKeys) { - _camera->setPosition(pos); - _camera->setRotation(q); - } - - - - - -} - -void InteractionHandler::setFocusNode(SceneGraphNode* node) { - - if (_focusNode == node){ - return; - } - - _focusNode = node; - - //orient the camera to the new node - psc focusPos = node->worldPosition(); - psc camToFocus = focusPos - _camera->position(); - glm::vec3 viewDir = glm::normalize(camToFocus.vec3()); - glm::vec3 cameraView = glm::normalize(_camera->viewDirectionWorldSpace()); - //set new focus position - _camera->setFocusPosition(node->worldPosition()); - float dot = glm::dot(viewDir, cameraView); - - //static const float Epsilon = 0.001f; - if (dot < 1.f && dot > -1.f) { - //if (glm::length(viewDir - cameraView) < 0.001) { - //if (viewDir != cameraView) { - glm::vec3 rotAxis = glm::normalize(glm::cross(viewDir, cameraView)); - float angle = glm::angle(viewDir, cameraView); - glm::quat q = glm::angleAxis(angle, rotAxis); - - //rotate view to target new focus - _camera->rotate(q); - } -} - -const SceneGraphNode* const InteractionHandler::focusNode() const { - return _focusNode; -} - -void InteractionHandler::setCamera(Camera* camera) { - assert(camera); - _camera = camera; -} -const Camera* const InteractionHandler::camera() const { - return _camera; -} - -//void InteractionHandler::keyboardCallback(int key, int action) { -// if (_keyboardController) { -// auto start = ghoul::HighResClock::now(); -// _keyboardController->keyPressed(KeyAction(action), Key(key), KeyModifier::None); -// auto end = ghoul::HighResClock::now(); -// LINFO("Keyboard timing: " << std::chrono::duration_cast(end - start).count() << "ns"); -// } -//} - -void InteractionHandler::mouseButtonCallback(MouseButton button, MouseAction action) { - if (_mouseController) - _mouseController->button(button, action); -} - -void InteractionHandler::mousePositionCallback(double x, double y) { - if (_mouseController) - // TODO Remap screen coordinates to [0,1] - _mouseController->move(static_cast(x), static_cast(y)); -} - -void InteractionHandler::mouseScrollWheelCallback(double pos) { - if (_mouseController) - _mouseController->scrollWheel(static_cast(pos)); -} - -void InteractionHandler::orbit(const float &dx, const float &dy, const float &dz, const float &dist){ - - lockControls(); - - glm::vec3 cameraUp = glm::normalize((glm::inverse(_camera->viewRotationMatrix()) * glm::vec4(_camera->lookUpVectorCameraSpace(), 0))).xyz(); - glm::vec3 cameraRight = glm::cross(glm::vec3(_camera->viewDirectionWorldSpace()), cameraUp); - - glm::mat4 transform; - transform = glm::rotate(glm::radians(dx * 100.f), cameraUp) * transform; - transform = glm::rotate(glm::radians(dy * 100.f), cameraRight) * transform; - transform = glm::rotate(glm::radians(dz * 100.f), glm::vec3(_camera->viewDirectionWorldSpace())) * transform; - - //get "old" focus position - - psc camPos = _camera->position(); - psc focusPos = _camera->focusPosition(); - float distToFocusNodeCenter = (focusPos - camPos).length().lengthf(); - float focusNodeBounds = _focusNode ? _focusNode->boundingSphere().lengthf() : 0.f; - - float speedFactor = distToFocusNodeCenter - 0.098*focusNodeBounds; - - float rotationSpeed = glm::min(0.00001f * speedFactor, 100.0f); - float zoomSpeed = glm::min(0.0000001f * speedFactor, 1.0f); - float rollSpeed = 100.0f; - - - glm::mat4 transform; - transform = glm::rotate(glm::radians(dx * rotationSpeed), cameraUp) * transform; - transform = glm::rotate(glm::radians(dy * rotationSpeed), cameraRight) * transform; - transform = glm::rotate(glm::radians(dz * rollSpeed), _camera->viewDirection()) * transform; - - - - - //// get camera position - //psc relative = _camera->position(); - - // get camera position (UNSYNCHRONIZED) - psc relative = _camera->unsynchedPosition(); - - //get relative vector - psc relative_focus_coordinate = relative - focusPos; - //rotate relative vector - relative_focus_coordinate = glm::inverse(transform) * relative_focus_coordinate.vec4(); - - //get new new position of focus node - psc origin; - if (_focusNode) { - origin = _focusNode->worldPosition(); - } - - //new camera position - relative = origin + relative_focus_coordinate; - - - psc target = relative + relative_focus_coordinate * dist * zoomSpeed; - - //don't fly into objects - if ((target - origin).length() < focusNodeBounds){ - //target = relative; - } - - unlockControls(); - - - _camera->setFocusPosition(origin); - _camera->setPosition(target); - _camera->rotate(glm::quat_cast(transform)); - -} - -//void InteractionHandler::distance(const float &d){ -// -// lockControls(); -// -// psc relative = _camera->position(); -// const psc origin = (_focusNode) ? _focusNode->worldPosition() : psc(); -// psc relative_origin_coordinate = relative - origin; -// // addition 100% of bounds (fix later to something node specific?) -// float bounds = 2.f * (_focusNode ? _focusNode->boundingSphere().lengthf() : 0.f); -// -// psc target = relative + relative_origin_coordinate * d;// *fmaxf(bounds, (1.f - d)); -// //don't fly into objects -// if ((target - origin).length() < bounds){ -// target = relative; -// } -// _camera->setPosition(target); -// -// unlockControls(); -//} - -void InteractionHandler::orbitDelta(const glm::quat& rotation) -{ - lockControls(); - - // the camera position - psc relative = _camera->position(); - - // should be changed to something more dynamic =) - psc origin; - if (_focusNode) { - origin = _focusNode->worldPosition(); - } - - psc relative_origin_coordinate = relative - origin; - //glm::mat4 rotation_matrix = glm::mat4_cast(glm::inverse(rotation)); - //relative_origin_coordinate = relative_origin_coordinate.vec4() * glm::inverse(rotation); - relative_origin_coordinate = glm::inverse(rotation) * relative_origin_coordinate.vec4(); - relative = relative_origin_coordinate + origin; - glm::mat4 la = glm::lookAt(_camera->position().vec3(), origin.vec3(), glm::rotate(rotation, glm::vec3(_camera->lookUpVectorCameraSpace()))); - - unlockControls(); - - _camera->setPosition(relative); - //camera_->rotate(rotation); - //camera_->setRotation(glm::mat4_cast(rotation)); - - - _camera->setRotation(glm::quat_cast(la)); - //camera_->setLookUpVector(); - - -} - -//<<<<<<< HEAD -//void InteractionHandler::distance(const PowerScaledScalar &dist, size_t iterations) { -// if (iterations > 5) -// return; -// //assert(this_); -// lockControls(); -// -// psc relative = _camera->position(); -// const psc origin = (_node) ? _node->worldPosition() : psc(); -// -// psc relative_origin_coordinate = relative - origin; -// const glm::vec3 dir(relative_origin_coordinate.direction()); -// glm::vec3 newdir = dir * dist[0]; -//======= -void InteractionHandler::rotateDelta(const glm::quat& rotation) -{ - _camera->rotate(rotation); -} - -void InteractionHandler::distanceDelta(const PowerScaledScalar& distance, size_t iterations) -{ - if (iterations > 5) - return; - //assert(this_); - lockControls(); - - psc relative = _camera->position(); - const psc origin = (_focusNode) ? _focusNode->worldPosition() : psc(); - - unlockControls(); - - psc relative_origin_coordinate = relative - origin; - const glm::vec3 dir(relative_origin_coordinate.direction()); - glm::vec3 newdir = dir * distance[0]; - - relative_origin_coordinate = newdir; - relative_origin_coordinate[3] = distance[1]; - relative = relative + relative_origin_coordinate; - - relative_origin_coordinate = relative - origin; - if (relative_origin_coordinate.vec4().x == 0.f && relative_origin_coordinate.vec4().y == 0.f && relative_origin_coordinate.vec4().z == 0.f) - // TODO: this shouldn't be allowed to happen; a mechanism to prevent the camera to coincide with the origin is necessary (ab) - return; - - newdir = relative_origin_coordinate.direction(); - - // update only if on the same side of the origin - if (glm::angle(newdir, dir) < 90.0f) { - _camera->setPosition(relative); - } - else { - PowerScaledScalar d2 = distance; - d2[0] *= 0.75f; - d2[1] *= 0.85f; - distanceDelta(d2, iterations + 1); - } -} - -void InteractionHandler::lookAt(const glm::quat& rotation) -{ -} - -void InteractionHandler::keyboardCallback(Key key, KeyModifier modifier, KeyAction action) { - // TODO package in script - const float speed = _controllerSensitivity; - const float dt = static_cast(_deltaTime); - if (action == KeyAction::Press || action == KeyAction::Repeat) { - if ((key == Key::Right) && (modifier == KeyModifier::NoModifier)) { - glm::vec3 euler(0.0, speed * dt*0.4, 0.0); - glm::quat rot = glm::quat(euler); - rotateDelta(rot); - } - if ((key == Key::Left) && (modifier == KeyModifier::NoModifier)) { - glm::vec3 euler(0.0, -speed * dt*0.4, 0.0); - glm::quat rot = glm::quat(euler); - rotateDelta(rot); - } - if ((key == Key::Down) && (modifier == KeyModifier::NoModifier)) { - glm::vec3 euler(speed * dt*0.4, 0.0, 0.0); - glm::quat rot = glm::quat(euler); - rotateDelta(rot); - } - if ((key == Key::Up) && (modifier == KeyModifier::NoModifier)) { - glm::vec3 euler(-speed * dt*0.4, 0.0, 0.0); - glm::quat rot = glm::quat(euler); - rotateDelta(rot); - } - if ((key == Key::KeypadSubtract) && (modifier == KeyModifier::NoModifier)) { - glm::vec2 s = OsEng.renderEngine().camera()->scaling(); - s[1] -= 0.5f; - OsEng.renderEngine().camera()->setScaling(s); - } - if ((key == Key::KeypadAdd) && (modifier == KeyModifier::NoModifier)) { - glm::vec2 s = OsEng.renderEngine().camera()->scaling(); - s[1] += 0.5f; - OsEng.renderEngine().camera()->setScaling(s); - } - - // iterate over key bindings - //_validKeyLua = true; - auto ret = _keyLua.equal_range({ key, modifier }); - for (auto it = ret.first; it != ret.second; ++it) { - //OsEng.scriptEngine()->runScript(it->second); - OsEng.scriptEngine().queueScript(it->second); - //if (!_validKeyLua) { - // break; - //} - } - } -} - -void InteractionHandler::resetKeyBindings() { - _keyLua.clear(); - //_validKeyLua = false; -} - -void InteractionHandler::bindKey(Key key, KeyModifier modifier, std::string lua) { - _keyLua.insert({ - {key, modifier}, - lua - }); -} - -scripting::LuaLibrary InteractionHandler::luaLibrary() { - return { - "", - { - { - "clearKeys", - &luascriptfunctions::clearKeys, - "", - "Clear all key bindings" - }, - { - "bindKey", - &luascriptfunctions::bindKey, - "string, string", - "Binds a key by name to a lua string command" - }, - { - "dt", - &luascriptfunctions::dt, - "", - "Get current frame time" - }, - { - "distance", - &luascriptfunctions::distance, - "number", - "Change distance to origin", - true - }, - { - "setInteractionSensitivity", - &luascriptfunctions::setInteractionSensitivity, - "number", - "Sets the global interaction sensitivity" - }, - { - "interactionSensitivity", - &luascriptfunctions::interactionSensitivity, - "", - "Gets the current global interaction sensitivity" - }, - { - "setInvertRoll", - &luascriptfunctions::setInvertRoll, - "bool", - "Sets the setting if roll movements are inverted" - }, - { - "invertRoll", - &luascriptfunctions::invertRoll, - "", - "Returns the status of roll movement inversion" - }, - { - "setInvertRotation", - &luascriptfunctions::setInvertRotation, - "bool", - "Sets the setting if rotation movements are inverted" - }, - { - "invertRotation", - &luascriptfunctions::invertRotation, - "", - "Returns the status of rotation movement inversion" - } - - } - }; -} - -void InteractionHandler::setRotation(const glm::quat& rotation) -{ - _camera->setRotation(rotation); -} - -double InteractionHandler::deltaTime() const { - return _deltaTime; -} - -void InteractionHandler::setInteractionSensitivity(float sensitivity) { - _controllerSensitivity = sensitivity; -} - -float InteractionHandler::interactionSensitivity() const { - return _controllerSensitivity; -} - -void InteractionHandler::setInvertRoll(bool invert) { - _invertRoll = invert; -} - -bool InteractionHandler::invertRoll() const { - return _invertRoll; -} - -void InteractionHandler::setInvertRotation(bool invert) { - _invertRotation = invert; -} - -bool InteractionHandler::invertRotation() const { - return _invertRotation; -} - - void InteractionHandler::addKeyframe(const network::datamessagestructures::PositionKeyframe &kf){ - _keyframeMutex.lock(); - - //save a maximum of 10 samples (1 seconds of buffer) - if (_keyframes.size() >= 10){ - _keyframes.erase(_keyframes.begin()); - } - _keyframes.push_back(kf); - - _keyframeMutex.unlock(); -} - -void InteractionHandler::clearKeyframes(){ - _keyframeMutex.lock(); - _keyframes.clear(); - _keyframeMutex.unlock(); -} - -#else // USE_OLD_INTERACTIONHANDLER - // InteractionHandler InteractionHandler::InteractionHandler() : _origin("origin", "Origin", "") @@ -631,7 +76,7 @@ InteractionHandler::InteractionHandler() , _rotationalFriction("rotationalFriction", "Rotational Friction", true) , _horizontalFriction("horizontalFriction", "Horizontal Friction", true) , _verticalFriction("verticalFriction", "Vertical Friction", true) - , _sensitivity("sensitivity", "Sensitivity", 0.002, 0.0001, 0.02) + , _sensitivity("sensitivity", "Sensitivity", 0.5, 0.001, 1) , _rapidness("rapidness", "Rapidness", 1, 0.1, 60) { setName("Interaction"); @@ -653,7 +98,7 @@ InteractionHandler::InteractionHandler() // Create the interactionModes _inputState = std::make_unique(); // Inject the same mouse states to both orbital and global interaction mode - _mouseStates = std::make_unique(0.002, 1); + _mouseStates = std::make_unique(_sensitivity * pow(10.0,-4), 1); _interactionModes.insert( std::pair>( "Orbital", @@ -664,6 +109,11 @@ InteractionHandler::InteractionHandler() "GlobeBrowsing", std::make_shared(_mouseStates) )); + _interactionModes.insert( + std::pair>( + "Keyframe", + std::make_shared() + )); // Set the interactionMode _currentInteractionMode = _interactionModes["Orbital"]; @@ -679,7 +129,7 @@ InteractionHandler::InteractionHandler() _mouseStates->setVerticalFriction(_verticalFriction); }); _sensitivity.onChange([&]() { - _mouseStates->setSensitivity(_sensitivity); + _mouseStates->setSensitivity(_sensitivity * pow(10.0,-4)); }); _rapidness.onChange([&]() { _mouseStates->setVelocityScaleFactor(_rapidness); @@ -700,6 +150,25 @@ InteractionHandler::~InteractionHandler() { } +void InteractionHandler::initialize() { + OsEng.parallelConnection().connectionEvent()->subscribe("interactionHandler", "statusChanged", [this]() { + if (OsEng.parallelConnection().status() == ParallelConnection::Status::ClientWithHost) { + setInteractionMode("Keyframe"); + } else { + auto keyframeModeIter = _interactionModes.find("Keyframe"); + if (keyframeModeIter != _interactionModes.end()) { + if (_currentInteractionMode == keyframeModeIter->second) { + setInteractionMode("Orbital"); + } + } + } + }); +} + +void InteractionHandler::deinitialize() { + OsEng.parallelConnection().connectionEvent()->unsubscribe("interactionHandler"); +} + void InteractionHandler::setFocusNode(SceneGraphNode* node) { _currentInteractionMode->setFocusNode(node); } @@ -710,30 +179,7 @@ void InteractionHandler::setCamera(Camera* camera) { void InteractionHandler::resetCameraDirection() { LINFO("Setting camera direction to point at focus node."); - - glm::dquat rotation = _camera->rotationQuaternion(); - glm::dvec3 focusPosition = focusNode()->worldPosition(); - glm::dvec3 cameraPosition = _camera->positionVec3(); - glm::dvec3 lookUpVector = _camera->lookUpVectorWorldSpace(); - - glm::dvec3 directionToFocusNode = glm::normalize(focusPosition - cameraPosition); - - // To make sure the lookAt function won't fail - static const double epsilon = 0.000001; - if (glm::dot(lookUpVector, directionToFocusNode) > 1.0 - epsilon) { - // Change the look up vector a little bit - lookUpVector = glm::normalize(lookUpVector + glm::dvec3(epsilon)); - } - - // Create the rotation to look at focus node - glm::dmat4 lookAtMat = glm::lookAt( - glm::dvec3(0, 0, 0), - directionToFocusNode, - lookUpVector); - glm::dquat rotationLookAtFocusNode = normalize(quat_cast(inverse(lookAtMat))); - - // Update camera Rotation - _camera->setRotation(rotationLookAtFocusNode); + _currentInteractionMode->rotateToFocusNodeInterpolator().start(); } void InteractionHandler::setInteractionMode(std::shared_ptr interactionMode) { @@ -761,6 +207,35 @@ void InteractionHandler::setInteractionMode(const std::string& interactionModeKe "' is not a valid interaction mode. Candidates are " << listInteractionModes); } } + +void InteractionHandler::goToChunk(int x, int y, int level) { + std::shared_ptr gbim = + std::dynamic_pointer_cast (_currentInteractionMode); + + if (gbim) { +#ifdef OPENSPACE_MODULE_GLOBEBROWSING_ENABLED + gbim->goToChunk(*_camera, globebrowsing::TileIndex(x,y,level), glm::vec2(0.5,0.5), true); +#endif + } else { + LWARNING("Interaction mode must be set to 'GlobeBrowsing'"); + } +} + +void InteractionHandler::goToGeo(double latitude, double longitude) { + std::shared_ptr gbim = + std::dynamic_pointer_cast (_currentInteractionMode); + + if (gbim) { +#ifdef OPENSPACE_MODULE_GLOBEBROWSING_ENABLED + gbim->goToGeodetic2( + *_camera, + globebrowsing::Geodetic2(latitude, longitude) / 180 * glm::pi(), true + ); +#endif + } else { + LWARNING("Interaction mode must be set to 'GlobeBrowsing'"); + } +} void InteractionHandler::lockControls() { @@ -776,7 +251,7 @@ void InteractionHandler::updateInputStates(double timeSinceLastUpdate) { _currentInteractionMode->updateMouseStatesFromInput(*_inputState, timeSinceLastUpdate); } -void InteractionHandler::updateCamera() { +void InteractionHandler::updateCamera(double deltaTime) { ghoul_assert(_inputState != nullptr, "InputState cannot be null!"); ghoul_assert(_camera != nullptr, "Camera cannot be null!"); @@ -785,7 +260,7 @@ void InteractionHandler::updateCamera() { } else { if (_camera && focusNode()) { - _currentInteractionMode->updateCameraStateFromMouseStates(*_camera); + _currentInteractionMode->updateCameraStateFromMouseStates(*_camera, deltaTime); _camera->setFocusPositionVec3(focusNode()->worldPosition()); } } @@ -823,8 +298,11 @@ void InteractionHandler::keyboardCallback(Key key, KeyModifier modifier, KeyActi // iterate over key bindings auto ret = _keyLua.equal_range({ key, modifier }); for (auto it = ret.first; it != ret.second; ++it) { - //OsEng.scriptEngine()->runScript(it->second); - OsEng.scriptEngine().queueScript(it->second); + auto remote = it->second.synchronization ? + scripting::ScriptEngine::RemoteScripting::Yes : + scripting::ScriptEngine::RemoteScripting::No; + + OsEng.scriptEngine().queueScript(it->second.command, remote); } } } @@ -928,14 +406,27 @@ void InteractionHandler::resetKeyBindings() { _keyLua.clear(); } -void InteractionHandler::bindKey(Key key, KeyModifier modifier, std::string lua) { +void InteractionHandler::bindKeyLocal(Key key, KeyModifier modifier, + std::string luaCommand, std::string documentation) +{ _keyLua.insert({ { key, modifier }, - lua + { std::move(luaCommand), Synchronized::No, std::move(documentation) } }); } + +void InteractionHandler::bindKey(Key key, KeyModifier modifier, + std::string luaCommand, std::string documentation) +{ + _keyLua.insert({ + { key, modifier }, + { std::move(luaCommand), Synchronized::Yes, std::move(documentation) } + }); +} + -void InteractionHandler::writeKeyboardDocumentation(const std::string& type, const std::string& file) +void InteractionHandler::writeKeyboardDocumentation(const std::string& type, + const std::string& file) { if (type == "text") { std::ofstream f; @@ -943,8 +434,15 @@ void InteractionHandler::writeKeyboardDocumentation(const std::string& type, con f.open(absPath(file)); for (const auto& p : _keyLua) { - f << std::to_string(p.first) << ": " << - p.second << std::endl; + std::string remoteScriptingInfo; + bool remoteScripting = p.second.synchronization; + + if (!remoteScripting) { + remoteScriptingInfo = " (LOCAL)"; + } + f << std::to_string(p.first) << ": " + << p.second.command << remoteScriptingInfo << '\n' + << p.second.documentation << '\n'; } } else if (type == "html") { @@ -952,51 +450,95 @@ void InteractionHandler::writeKeyboardDocumentation(const std::string& type, con f.exceptions(~std::ofstream::goodbit); f.open(absPath(file)); -#ifdef JSON + std::ifstream handlebarsInput(absPath(HandlebarsFilename)); + std::ifstream jsInput(absPath(JsFilename)); + + std::string jsContent; + std::back_insert_iterator jsInserter(jsContent); + + std::copy(std::istreambuf_iterator{handlebarsInput}, std::istreambuf_iterator(), jsInserter); + std::copy(std::istreambuf_iterator{jsInput}, std::istreambuf_iterator(), jsInserter); + + std::ifstream bootstrapInput(absPath(BootstrapFilename)); + std::ifstream cssInput(absPath(CssFilename)); + + std::string cssContent; + std::back_insert_iterator cssInserter(cssContent); + + std::copy(std::istreambuf_iterator{bootstrapInput}, std::istreambuf_iterator(), cssInserter); + std::copy(std::istreambuf_iterator{cssInput}, std::istreambuf_iterator(), cssInserter); + + std::ifstream mainTemplateInput(absPath(MainTemplateFilename)); + std::string mainTemplateContent{ std::istreambuf_iterator{mainTemplateInput}, + std::istreambuf_iterator{} }; + + std::ifstream keybindingTemplateInput(absPath(KeybindingTemplateFilename)); + std::string keybindingTemplateContent{ std::istreambuf_iterator{keybindingTemplateInput}, + std::istreambuf_iterator{} }; + std::stringstream json; json << "["; + bool first = true; for (const auto& p : _keyLua) { + if (!first) { + json << ","; + } + first = false; json << "{"; json << "\"key\": \"" << std::to_string(p.first) << "\","; - json << "\"script\": \"" << p.second << "\","; - json << "},"; + json << "\"script\": \"" << p.second.command << "\","; + json << "\"remoteScripting\": " << (p.second.synchronization ? "true," : "false,"); + json << "\"documentation\": \"" << p.second.documentation << "\""; + json << "}"; } json << "]"; - std::string jsonText = json.str(); + std::string jsonString = ""; + for (const char& c : json.str()) { + if (c == '\'') { + jsonString += "\\'"; + } else { + jsonString += c; + } + } + -#else std::stringstream html; + html << "\n" + << "\n" + << "\t\n" + << "\t\t\n" + << "\t\t\n" + << "\t\n" + << "\t\n" + << "\t\tDocumentation\n" + << "\t\n" + << "\t\n" + << "\t\n" + << "\n"; - html << "\n" - << "\t\n" - << "\t\tKey Bindings\n" - << "\t\n" - << "\n" - << "\n" - << "\t\n\n" - << "\t\n" - << "\t\t\n" - << "\t\t\t\n" - << "\t\t\t\n" - << "\t\t\n" - << "\t\n" - << "\t\n"; + f << html.str(); + + /* for (const auto& p : _keyLua) { html << "\t\t\n" << "\t\t\t\n" - << "\t\t\t\n" + << "\t\t\t\n" + << "\t\t\t\n" << "\t\t\n"; - } - - html << "\t\n" - << "
Key Bindings
KeyBinding
" << std::to_string(p.first) << "" << p.second << "" << p.second.first << "" << (p.second.second ? "Yes" : "No") << "
\n" - << ""; - - f << html.str(); -#endif - + }*/ } else { throw ghoul::RuntimeError( @@ -1019,8 +561,21 @@ scripting::LuaLibrary InteractionHandler::luaLibrary() { { "bindKey", &luascriptfunctions::bindKey, - "string, string", - "Binds a key by name to a lua string command" + "string, string [,string]", + "Binds a key by name to a lua string command to execute both locally " + "and to broadcast to clients if this is the host of a parallel session. " + "The first argument is the key, the second argument is the Lua command " + "that is to be executed, and the optional third argument is a human " + "readable description of the command for documentation purposes." + }, + { + "bindKeyLocal", + &luascriptfunctions::bindKeyLocal, + "string, string [,string]", + "Binds a key by name to a lua string command to execute only locally. " + "The first argument is the key, the second argument is the Lua command " + "that is to be executed, and the optional third argument is a human " + "readable description of the command for documentation purposes." }, { "setInteractionMode", @@ -1046,11 +601,23 @@ scripting::LuaLibrary InteractionHandler::luaLibrary() { "void", "Reset the camera direction to point at the focus node" }, + { + "goToChunk", + &luascriptfunctions::goToChunk, + "void", + "Go to chunk with given index x, y, level" + }, + { + "goToGeo", + &luascriptfunctions::goToGeo, + "void", + "Go to geographic coordinates latitude and longitude" + }, } }; } -void InteractionHandler::addKeyframe(const network::datamessagestructures::PositionKeyframe &kf) { +void InteractionHandler::addKeyframe(const datamessagestructures::CameraKeyframe &kf) { _inputState->addKeyframe(kf); } @@ -1058,21 +625,5 @@ void InteractionHandler::clearKeyframes() { _inputState->clearKeyframes(); } -//void InteractionHandler::serialize(SyncBuffer* syncBuffer) { -// for (auto var : _interactionModes) -// { -// var.second->serialize(syncBuffer); -// } -//} -// -//void InteractionHandler::deserialize(SyncBuffer* syncBuffer) { -// for (auto var : _interactionModes) -// { -// var.second->deserialize(syncBuffer); -// } -//} - -#endif // USE_OLD_INTERACTIONHANDLER - } // namespace interaction } // namespace openspace diff --git a/src/interaction/interactionhandler_lua.inl b/src/interaction/interactionhandler_lua.inl index 5c52f33131..b810761ecb 100644 --- a/src/interaction/interactionhandler_lua.inl +++ b/src/interaction/interactionhandler_lua.inl @@ -60,21 +60,28 @@ int setOrigin(lua_State* L) { /** * \ingroup LuaScripts * bindKey(): -* Binds a key to Lua command +* Binds a key to Lua command to both execute locally +* and broadcast to all clients if this node is hosting +* a parallel connection. */ int bindKey(lua_State* L) { using ghoul::lua::luaTypeToString; int nArguments = lua_gettop(L); - if (nArguments != 2) - return luaL_error(L, "Expected %i arguments, got %i", 2, nArguments); + if (nArguments != 2 && nArguments != 3) { + return luaL_error(L, "Expected %i or %i arguments, got %i", 2, 3, nArguments); + } + int KeyLocation = nArguments == 3 ? -3 : -2; + int CommandLocation = nArguments == 3 ? -2 : -1; + int DocumentationLocation = -1; - std::string key = luaL_checkstring(L, -2); - std::string command = luaL_checkstring(L, -1); + std::string key = luaL_checkstring(L, KeyLocation); + std::string command = luaL_checkstring(L, CommandLocation); - if (command.empty()) + if (command.empty()) { return luaL_error(L, "Command string is empty"); + } openspace::KeyWithModifier iKey = openspace::stringToKey(key); @@ -83,16 +90,68 @@ int bindKey(lua_State* L) { return 0; } + std::string documentation; + if (nArguments == 3) { + documentation = luaL_checkstring(L, DocumentationLocation); + } OsEng.interactionHandler().bindKey( iKey.key, iKey.modifier, - command + std::move(command), + std::move(documentation) ); return 0; } +/** +* \ingroup LuaScripts +* bindKey(): +* Binds a key to Lua command to execute only locally +*/ +int bindKeyLocal(lua_State* L) { + using ghoul::lua::luaTypeToString; + + int nArguments = lua_gettop(L); + if (nArguments != 2 && nArguments != 3) { + return luaL_error(L, "Expected %i or %i arguments, got %i", 2, 3, nArguments); + } + + int KeyLocation = nArguments == 3 ? -3 : -2; + int CommandLocation = nArguments == 3 ? -2 : -1; + int DocumentationLocation = -1; + + std::string key = luaL_checkstring(L, KeyLocation); + std::string command = luaL_checkstring(L, CommandLocation); + + + if (command.empty()) + return luaL_error(L, "Command string is empty"); + + openspace::KeyWithModifier iKey = openspace::stringToKey(key); + + if (iKey.key == openspace::Key::Unknown) { + LERRORC("lua.bindKey", "Could not find key '" << key << "'"); + return 0; + } + + std::string documentation; + if (nArguments == 3) { + documentation = luaL_checkstring(L, DocumentationLocation); + } + + OsEng.interactionHandler().bindKeyLocal( + iKey.key, + iKey.modifier, + std::move(command), + std::move(documentation) + ); + + return 0; +} + + /** * \ingroup LuaScripts * clearKeys(): @@ -132,6 +191,37 @@ int setInteractionMode(lua_State* L) { return 0; } +int goToChunk(lua_State* L) { + using ghoul::lua::luaTypeToString; + + int nArguments = lua_gettop(L); + if (nArguments != 3) + return luaL_error(L, "Expected %i arguments, got %i", 3, nArguments); + + int x = lua_tonumber(L, 1); + int y = lua_tonumber(L, 2); + int level = lua_tonumber(L, 3); + + OsEng.interactionHandler().goToChunk(x, y, level); + + return 0; +} + +int goToGeo(lua_State* L) { + using ghoul::lua::luaTypeToString; + + int nArguments = lua_gettop(L); + if (nArguments != 2) + return luaL_error(L, "Expected %i arguments, got %i", 2, nArguments); + + double latitude = lua_tonumber(L, 1); + double longitude = lua_tonumber(L, 2); + + OsEng.interactionHandler().goToGeo(latitude, longitude); + + return 0; +} + int restoreCameraStateFromFile(lua_State* L) { using ghoul::lua::luaTypeToString; const std::string _loggerCat = "lua.restoreCameraStateFromFile"; @@ -176,120 +266,7 @@ int resetCameraDirection(lua_State* L) { OsEng.interactionHandler().resetCameraDirection(); } -#ifdef USE_OLD_INTERACTIONHANDLER -/** -* \ingroup LuaScripts -* dt(bool): -* Get current frame time -*/ -int dt(lua_State* L) { - /* - int nArguments = lua_gettop(L); - if (nArguments != 0) - return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments); - - lua_pushnumber(L,OsEng.interactionHandler().deltaTime()); - */return 1; -} - -/** -* \ingroup LuaScripts -* distance(double, double): -* Change distance to origin -*/ -int distance(lua_State* L) { - /* - int nArguments = lua_gettop(L); - if (nArguments != 2) - return luaL_error(L, "Expected %i arguments, got %i", 2, nArguments); - - double d1 = luaL_checknumber(L, -2); - double d2 = luaL_checknumber(L, -1); - PowerScaledScalar dist(static_cast(d1), static_cast(d2)); - OsEng.interactionHandler().distanceDelta(dist); - */ - return 0; -} - -/** - * \ingroup LuaScripts - * setInteractionSensitivity(double): - * Changes the global interaction sensitivity to the passed value - */ -int setInteractionSensitivity(lua_State* L) { - int nArguments = lua_gettop(L); - if (nArguments != 1) - return luaL_error(L, "Expected %i arguments, got %i", 1, nArguments); - - float sensitivity = static_cast(luaL_checknumber(L, -1)); - //OsEng.interactionHandler().setInteractionSensitivity(sensitivity); - return 0; -} - -/** - * \ingroup LuaScripts - * interactionSensitivity(): - * Returns the current, global interaction sensitivity - */ -int interactionSensitivity(lua_State* L) { - //float sensitivity = OsEng.interactionHandler().interactionSensitivity(); - //lua_pushnumber(L, sensitivity); - return 1; -} - -/** - * \ingroup LuaScripts - * setInvertRoll(bool): - * Determines if the roll movement is inverted - */ -int setInvertRoll(lua_State* L) { - int nArguments = lua_gettop(L); - if (nArguments != 1) - return luaL_error(L, "Expected %i arguments, got %i", 1, nArguments); - - bool invert = lua_toboolean(L, -1) == 1; - //OsEng.interactionHandler().setInvertRoll(invert); - return 0; -} - -/** - * \ingroup LuaScripts - * invertRoll(): - * Returns the current setting for inversion of roll movement - */ -int invertRoll(lua_State* L) { - //bool invert = OsEng.interactionHandler().invertRoll(); - //lua_pushboolean(L, invert); - return 1; -} - -/** - * \ingroup LuaScripts - * setInvertRotation(bool): - * Determines if the rotation movement is inverted - */ -int setInvertRotation(lua_State* L) { - int nArguments = lua_gettop(L); - if (nArguments != 1) - return luaL_error(L, "Expected %i arguments, got %i", 1, nArguments); - - bool invert = lua_toboolean(L, -1) == 1; - //OsEng.interactionHandler().setInvertRotation(invert); - return 0; -} - -/** - * \ingroup LuaScripts - * invertRotation(): - * Returns the current setting for inversion of rotation movement - */ -int invertRotation(lua_State* L) { - //bool invert = OsEng.interactionHandler().invertRotation(); - //lua_pushboolean(L, invert); - return 1; -} -#endif USE_OLD_INTERACTIONHANDLER } // namespace luascriptfunctions } // namespace openspace diff --git a/src/interaction/interactionmode.cpp b/src/interaction/interactionmode.cpp index f6ea8b17b9..70274c1876 100644 --- a/src/interaction/interactionmode.cpp +++ b/src/interaction/interactionmode.cpp @@ -37,7 +37,8 @@ #ifdef OPENSPACE_MODULE_GLOBEBROWSING_ENABLED #include -#include +#include +#include #endif @@ -57,22 +58,39 @@ namespace interaction { } - void InputState::addKeyframe(const network::datamessagestructures::PositionKeyframe &kf) { - _keyframeMutex.lock(); + const std::vector& InputState::keyframes() const { + return _keyframes; + } + + void InputState::addKeyframe(const datamessagestructures::CameraKeyframe &kf) { + clearOldKeyframes(); + + auto compareTimestamps = [](const datamessagestructures::CameraKeyframe a, + datamessagestructures::CameraKeyframe b) { + return a._timestamp < b._timestamp; + }; + + // Remove keyframes after the inserted keyframe. + _keyframes.erase(std::upper_bound(_keyframes.begin(), _keyframes.end(), kf, compareTimestamps), _keyframes.end()); - //save a maximum of 10 samples (1 seconds of buffer) - if (_keyframes.size() >= 10) { - _keyframes.erase(_keyframes.begin()); - } _keyframes.push_back(kf); + } - _keyframeMutex.unlock(); + void InputState::clearOldKeyframes() { + double now = OsEng.runTime(); + auto isLater = [now](const datamessagestructures::CameraKeyframe kf) { + return kf._timestamp > now; + }; + + // Remote keyframes with earlier timestamps than the current time. + auto nextKeyframe = std::find_if(_keyframes.begin(), _keyframes.end(), isLater); + if (nextKeyframe != _keyframes.begin()) { + _keyframes.erase(_keyframes.begin(), nextKeyframe - 1); + } } void InputState::clearKeyframes() { - _keyframeMutex.lock(); _keyframes.clear(); - _keyframeMutex.unlock(); } void InputState::keyboardCallback(Key key, KeyModifier modifier, KeyAction action) { @@ -129,6 +147,15 @@ namespace interaction { } return false; } + + bool InputState::isKeyPressed(Key key) const { + for (auto it = _keysDown.begin(); it != _keysDown.end(); it++) { + if ((*it).first == key) { + return true; + } + } + return false; + } bool InputState::isMouseButtonPressed(MouseButton mouseButton) const { for (auto it = _mouseButtonsDown.begin(); it != _mouseButtonsDown.end(); it++) { @@ -144,7 +171,10 @@ namespace interaction { -InteractionMode::InteractionMode() { +InteractionMode::InteractionMode() + : _rotateToFocusNodeInterpolator(Interpolator([](double t){ + return pow(t, 2); + })) { } @@ -165,6 +195,11 @@ SceneGraphNode* InteractionMode::focusNode() { return _focusNode; } +Interpolator& InteractionMode::rotateToFocusNodeInterpolator() { + return _rotateToFocusNodeInterpolator; +}; + + // KeyframeInteractionMode KeyframeInteractionMode::KeyframeInteractionMode(){ @@ -175,11 +210,38 @@ KeyframeInteractionMode::~KeyframeInteractionMode() { } void KeyframeInteractionMode::updateMouseStatesFromInput(const InputState& inputState, double deltaTime) { - + _keyframes = inputState.keyframes(); } -void KeyframeInteractionMode::updateCameraStateFromMouseStates(Camera& camera) { +void KeyframeInteractionMode::updateCameraStateFromMouseStates(Camera& camera, double deltaTime) { + if (_keyframes.size() == 0) { + return; + } + double now = OsEng.runTime(); + auto isLater = [now](const datamessagestructures::CameraKeyframe kf) { + return kf._timestamp > now; + }; + + auto nextKeyframe = std::find_if(_keyframes.begin(), _keyframes.end(), isLater); + if (nextKeyframe == _keyframes.end()) { + return; + } + + if (nextKeyframe == _keyframes.begin()) { + camera.setPositionVec3(_keyframes[0]._position); + camera.setRotation(_keyframes[0]._rotation); + return; + } + auto prevKeyframe = nextKeyframe - 1; + + double prevTime = prevKeyframe->_timestamp; + double nextTime = nextKeyframe->_timestamp; + + double t = (now - prevTime) / (nextTime - prevTime); + + camera.setPositionVec3(prevKeyframe->_position * (1 - t) + nextKeyframe->_position * t); + camera.setRotation(glm::slerp(prevKeyframe->_rotation, nextKeyframe->_rotation, t)); } // OrbitalInteractionMode @@ -199,15 +261,15 @@ void OrbitalInteractionMode::MouseStates::updateMouseStatesFromInput(const Input bool button1Pressed = inputState.isMouseButtonPressed(MouseButton::Button1); bool button2Pressed = inputState.isMouseButtonPressed(MouseButton::Button2); bool button3Pressed = inputState.isMouseButtonPressed(MouseButton::Button3); - bool keyCtrlPressed = inputState.isKeyPressed( - std::pair(Key::LeftControl, KeyModifier::Control)); - + bool keyCtrlPressed = inputState.isKeyPressed(Key::LeftControl); + bool keyShiftPressed = inputState.isKeyPressed(Key::LeftShift); + // Update the mouse states - if (button1Pressed) { + if (button1Pressed && !keyShiftPressed) { if (keyCtrlPressed) { glm::dvec2 mousePositionDelta = _localRotationMouseState.previousPosition - mousePosition; - _localRotationMouseState.velocity.set(mousePositionDelta * deltaTime * _sensitivity, deltaTime); + _localRotationMouseState.velocity.set(mousePositionDelta * _sensitivity, deltaTime); _globalRotationMouseState.previousPosition = mousePosition; _globalRotationMouseState.velocity.decelerate(deltaTime); @@ -215,7 +277,7 @@ void OrbitalInteractionMode::MouseStates::updateMouseStatesFromInput(const Input else { glm::dvec2 mousePositionDelta = _globalRotationMouseState.previousPosition - mousePosition; - _globalRotationMouseState.velocity.set(mousePositionDelta * deltaTime * _sensitivity, deltaTime); + _globalRotationMouseState.velocity.set(mousePositionDelta * _sensitivity, deltaTime); _localRotationMouseState.previousPosition = mousePosition; _localRotationMouseState.velocity.decelerate(deltaTime); @@ -231,17 +293,17 @@ void OrbitalInteractionMode::MouseStates::updateMouseStatesFromInput(const Input if (button2Pressed) { glm::dvec2 mousePositionDelta = _truckMovementMouseState.previousPosition - mousePosition; - _truckMovementMouseState.velocity.set(mousePositionDelta * deltaTime * _sensitivity, deltaTime); + _truckMovementMouseState.velocity.set(mousePositionDelta * _sensitivity, deltaTime); } else { // !button2Pressed _truckMovementMouseState.previousPosition = mousePosition; _truckMovementMouseState.velocity.decelerate(deltaTime); } - if (button3Pressed) { + if (button3Pressed || (keyShiftPressed && button1Pressed)) { if (keyCtrlPressed) { glm::dvec2 mousePositionDelta = _localRollMouseState.previousPosition - mousePosition; - _localRollMouseState.velocity.set(mousePositionDelta * deltaTime * _sensitivity, deltaTime); + _localRollMouseState.velocity.set(mousePositionDelta * _sensitivity, deltaTime); _globalRollMouseState.previousPosition = mousePosition; _globalRollMouseState.velocity.decelerate(deltaTime); @@ -249,7 +311,7 @@ void OrbitalInteractionMode::MouseStates::updateMouseStatesFromInput(const Input else { glm::dvec2 mousePositionDelta = _globalRollMouseState.previousPosition - mousePosition; - _globalRollMouseState.velocity.set(mousePositionDelta * deltaTime * _sensitivity, deltaTime); + _globalRollMouseState.velocity.set(mousePositionDelta * _sensitivity, deltaTime); _localRollMouseState.previousPosition = mousePosition; _localRollMouseState.velocity.decelerate(deltaTime); @@ -310,17 +372,18 @@ glm::dvec2 OrbitalInteractionMode::MouseStates::synchedGlobalRollMouseVelocity() return _globalRollMouseState.velocity.get(); } -OrbitalInteractionMode::OrbitalInteractionMode(std::shared_ptr mouseStates) +OrbitalInteractionMode::OrbitalInteractionMode( + std::shared_ptr mouseStates) : InteractionMode() - , _mouseStates(mouseStates){ - + , _mouseStates(mouseStates) { + } OrbitalInteractionMode::~OrbitalInteractionMode() { } -void OrbitalInteractionMode::updateCameraStateFromMouseStates(Camera& camera) { +void OrbitalInteractionMode::updateCameraStateFromMouseStates(Camera& camera, double deltaTime) { // Update synched data using namespace glm; @@ -358,12 +421,23 @@ void OrbitalInteractionMode::updateCameraStateFromMouseStates(Camera& camera) { glm::angleAxis(_mouseStates->synchedLocalRollMouseVelocity().x, dvec3(0, 0, 1)); localCameraRotation = localCameraRotation * cameraRollRotation; } + if (!_rotateToFocusNodeInterpolator.isInterpolating()) { // Do local rotation dvec3 eulerAngles(_mouseStates->synchedLocalRotationMouseVelocity().y, _mouseStates->synchedLocalRotationMouseVelocity().x, 0); dquat rotationDiff = dquat(eulerAngles); localCameraRotation = localCameraRotation * rotationDiff; } + else + { // Interpolate local rotation to focus node + double t = _rotateToFocusNodeInterpolator.value(); + localCameraRotation = slerp(localCameraRotation, dquat(dvec3(0.0)), t); + _rotateToFocusNodeInterpolator.step(deltaTime * 0.1); // Should probably depend on dt + // This is a fast but ugly solution to slow regaining of control... + if (t > 0.18) { + _rotateToFocusNodeInterpolator.end(); + } + } { // Do global rotation dvec2 smoothMouseVelocity = _mouseStates->synchedGlobalRotationMouseVelocity(); dvec3 eulerAngles(-smoothMouseVelocity.y, -smoothMouseVelocity.x, 0); @@ -430,7 +504,7 @@ void GlobeBrowsingInteractionMode::setFocusNode(SceneGraphNode* focusNode) { #ifdef OPENSPACE_MODULE_GLOBEBROWSING_ENABLED Renderable* baseRenderable = _focusNode->renderable(); - if (RenderableGlobe* globe = dynamic_cast(baseRenderable)) { + if (globebrowsing::RenderableGlobe* globe = dynamic_cast(baseRenderable)) { _globe = globe; } else { @@ -440,7 +514,7 @@ void GlobeBrowsingInteractionMode::setFocusNode(SceneGraphNode* focusNode) { #endif // OPENSPACE_MODULE_GLOBEBROWSING_ENABLED } -void GlobeBrowsingInteractionMode::updateCameraStateFromMouseStates(Camera& camera) { +void GlobeBrowsingInteractionMode::updateCameraStateFromMouseStates(Camera& camera, double deltaTime) { #ifdef OPENSPACE_MODULE_GLOBEBROWSING_ENABLED using namespace glm; @@ -448,7 +522,7 @@ void GlobeBrowsingInteractionMode::updateCameraStateFromMouseStates(Camera& came // Declare variables to use in interaction calculations // Shrink interaction ellipsoid to enable interaction below height = 0 double ellipsoidShrinkTerm = _globe->interactionDepthBelowEllipsoid(); - double minHeightAboveGround = _globe->cameraMinHeight(); + double minHeightAboveGround = _globe->generalProperties().cameraMinHeight; // Read the current state of the camera and focusnode dvec3 camPos = camera.positionVec3(); @@ -465,8 +539,8 @@ void GlobeBrowsingInteractionMode::updateCameraStateFromMouseStates(Camera& came // Sampling of height is done in the reference frame of the globe. // Hence, the camera position needs to be transformed with the inverse model matrix - glm::dmat4 inverseModelTransform = _globe->chunkedLodGlobe()->inverseModelTransform(); - glm::dmat4 modelTransform = _globe->chunkedLodGlobe()->modelTransform(); + glm::dmat4 inverseModelTransform = _globe->inverseModelTransform(); + glm::dmat4 modelTransform = _globe->modelTransform(); glm::dvec3 cameraPositionModelSpace = glm::dvec3(inverseModelTransform * glm::dvec4(camPos, 1)); @@ -481,10 +555,15 @@ void GlobeBrowsingInteractionMode::updateCameraStateFromMouseStates(Camera& came directionFromSurfaceToCameraModelSpace * ellipsoidShrinkTerm); dvec3 ellipsoidSurfaceToCamera = camPos - (centerPos + centerToEllipsoidSurface); + double heightToSurface = + _globe->getHeight(cameraPositionModelSpace) + ellipsoidShrinkTerm; + double distFromCenterToSurface = length(centerToEllipsoidSurface); double distFromEllipsoidSurfaceToCamera = length(ellipsoidSurfaceToCamera); double distFromCenterToCamera = length(posDiff); + double distFromSurfaceToCamera = + distFromEllipsoidSurfaceToCamera - heightToSurface; // Create the internal representation of the local and global camera rotations dmat4 lookAtMat = lookAt( @@ -505,17 +584,28 @@ void GlobeBrowsingInteractionMode::updateCameraStateFromMouseStates(Camera& came glm::angleAxis(_mouseStates->synchedLocalRollMouseVelocity().x, dvec3(0, 0, 1)); localCameraRotation = localCameraRotation * cameraRollRotation; } + if(!_rotateToFocusNodeInterpolator.isInterpolating()) { // Do local rotation glm::dvec3 eulerAngles(_mouseStates->synchedLocalRotationMouseVelocity().y, _mouseStates->synchedLocalRotationMouseVelocity().x, 0); glm::dquat rotationDiff = glm::dquat(eulerAngles); localCameraRotation = localCameraRotation * rotationDiff; } + else + { // Interpolate local rotation to focus node + double t = _rotateToFocusNodeInterpolator.value(); + localCameraRotation = slerp(localCameraRotation, dquat(dvec3(0.0)), t); + _rotateToFocusNodeInterpolator.step(0.002); // Should probably depend on dt + // This is a fast but ugly solution to slow regaining of control... + if (t > 0.2) { + _rotateToFocusNodeInterpolator.end(); + } + } { // Do global rotation (horizontal movement) glm::dvec3 eulerAngles = glm::dvec3( -_mouseStates->synchedGlobalRotationMouseVelocity().y, -_mouseStates->synchedGlobalRotationMouseVelocity().x, - 0) * glm::clamp(distFromEllipsoidSurfaceToCamera / distFromCenterToSurface, 0.0, 1.0); + 0) * glm::clamp(distFromSurfaceToCamera / distFromCenterToSurface, 0.0, 1.0); glm::dquat rotationDiffCamSpace = glm::dquat(eulerAngles); glm::dquat rotationDiffWorldSpace = @@ -528,14 +618,17 @@ void GlobeBrowsingInteractionMode::updateCameraStateFromMouseStates(Camera& came * rotationDiffWorldSpace - (distFromCenterToCamera * directionFromSurfaceToCamera); - glm::dvec3 rotationDiffVec3AroundCenter = + camPos += rotationDiffVec3; + + posDiff = camPos - centerPos; + glm::dvec3 rotationDiffVec3AroundCenter = posDiff - * focusNodeRotationDiff + * focusNodeRotationDiff - (posDiff); - - camPos += rotationDiffVec3 + rotationDiffVec3AroundCenter; - dvec3 posDiff = camPos - centerPos; - + camPos += rotationDiffVec3AroundCenter; + + + cameraPositionModelSpace = @@ -561,8 +654,7 @@ void GlobeBrowsingInteractionMode::updateCameraStateFromMouseStates(Camera& came glm::normalize(glm::quat_cast(glm::inverse(lookAtMat))); } { // Move position towards or away from focus node - distFromEllipsoidSurfaceToCamera = glm::length(ellipsoidSurfaceToCamera); - camPos += -directionFromSurfaceToCamera * distFromEllipsoidSurfaceToCamera * + camPos += -directionFromSurfaceToCamera * distFromSurfaceToCamera * _mouseStates->synchedTruckMovementMouseVelocity().y; } { // Roll around ellipsoid normal @@ -575,7 +667,7 @@ void GlobeBrowsingInteractionMode::updateCameraStateFromMouseStates(Camera& came // Sampling of height is done in the reference frame of the globe. // Hence, the camera position needs to be transformed with the inverse model matrix - glm::dmat4 inverseModelTransform = _globe->chunkedLodGlobe()->inverseModelTransform(); + glm::dmat4 inverseModelTransform = _globe->inverseModelTransform(); glm::dvec3 cameraPositionModelSpace = glm::dvec3(inverseModelTransform * glm::dvec4(camPos, 1)); @@ -594,5 +686,92 @@ void GlobeBrowsingInteractionMode::updateCameraStateFromMouseStates(Camera& came #endif // OPENSPACE_MODULE_GLOBEBROWSING_ENABLED } +#ifdef OPENSPACE_MODULE_GLOBEBROWSING_ENABLED +void GlobeBrowsingInteractionMode::goToChunk(Camera& camera, + globebrowsing::TileIndex ti, glm::vec2 uv, bool resetCameraDirection) { + using namespace globebrowsing; + + // Camera position in model space + glm::dvec3 camPos = camera.positionVec3(); + glm::dmat4 inverseModelTransform = _globe->inverseModelTransform(); + glm::dvec3 cameraPositionModelSpace = + glm::dvec3(inverseModelTransform * glm::dvec4(camPos, 1)); + + GeodeticPatch patch(ti); + Geodetic2 corner = patch.getCorner(SOUTH_WEST); + Geodetic2 positionOnPatch = patch.getSize(); + positionOnPatch.lat *= uv.y; + positionOnPatch.lon *= uv.x; + Geodetic2 pointPosition = corner + positionOnPatch; + + glm::dvec3 positionOnEllipsoid = + _globe->ellipsoid().geodeticSurfaceProjection(cameraPositionModelSpace); + double altitude = glm::length(cameraPositionModelSpace - positionOnEllipsoid); + + goToGeodetic3(camera, {pointPosition, altitude}); + + if (resetCameraDirection) { + this->resetCameraDirection(camera, pointPosition); + } +} + +void GlobeBrowsingInteractionMode::goToGeodetic2(Camera& camera, + globebrowsing::Geodetic2 geo2, bool resetCameraDirection) { + using namespace globebrowsing; + + // Camera position in model space + glm::dvec3 camPos = camera.positionVec3(); + glm::dmat4 inverseModelTransform = _globe->inverseModelTransform(); + glm::dvec3 cameraPositionModelSpace = + glm::dvec3(inverseModelTransform * glm::dvec4(camPos, 1)); + + glm::dvec3 positionOnEllipsoid = + _globe->ellipsoid().geodeticSurfaceProjection(cameraPositionModelSpace); + double altitude = glm::length(cameraPositionModelSpace - positionOnEllipsoid); + + goToGeodetic3(camera, {geo2, altitude}); + + if (resetCameraDirection) { + this->resetCameraDirection(camera, geo2); + } +} + +void GlobeBrowsingInteractionMode::goToGeodetic3(Camera& camera, globebrowsing::Geodetic3 geo3) { + glm::dvec3 positionModelSpace = _globe->ellipsoid().cartesianPosition(geo3); + glm::dmat4 modelTransform = _globe->modelTransform(); + glm::dvec3 positionWorldSpace = modelTransform * glm::dvec4(positionModelSpace, 1.0); + camera.setPositionVec3(positionWorldSpace); +} + + void GlobeBrowsingInteractionMode::resetCameraDirection(Camera& camera, globebrowsing::Geodetic2 geo2) { + using namespace globebrowsing; + + // Camera is described in world space + glm::dmat4 modelTransform = _globe->modelTransform(); + + // Lookup vector + glm::dvec3 positionModelSpace = _globe->ellipsoid().cartesianSurfacePosition(geo2); + glm::dvec3 slightlyNorth = _globe->ellipsoid().cartesianSurfacePosition( + Geodetic2(geo2.lat + 0.001, geo2.lon)); + glm::dvec3 lookUpModelSpace = glm::normalize(slightlyNorth - positionModelSpace); + glm::dvec3 lookUpWorldSpace = glm::dmat3(modelTransform) * lookUpModelSpace; + + // Lookat vector + glm::dvec3 lookAtWorldSpace = modelTransform * glm::dvec4(positionModelSpace, 1.0); + + // Eye position + glm::dvec3 eye = camera.positionVec3(); + + // Matrix + glm::dmat4 lookAtMatrix = glm::lookAt( + eye, lookAtWorldSpace, lookUpWorldSpace); + + // Set rotation + glm::dquat rotation = glm::quat_cast(inverse(lookAtMatrix)); + camera.setRotation(rotation); + } + +#endif // OPENSPACE_MODULE_GLOBEBROWSING_ENABLED + } // namespace interaction } // namespace openspace diff --git a/src/interaction/luaconsole.cpp b/src/interaction/luaconsole.cpp index 1073dfd43e..2a5b8847b3 100644 --- a/src/interaction/luaconsole.cpp +++ b/src/interaction/luaconsole.cpp @@ -24,6 +24,7 @@ #include +#include #include #include @@ -58,6 +59,7 @@ LuaConsole::LuaConsole() , _filename("") , _autoCompleteInfo({NoAutoComplete, false, ""}) , _isVisible(false) + , _remoteScripting(true) { // _commands.push_back(""); // _activeCommand = _commands.size() - 1; @@ -89,6 +91,13 @@ void LuaConsole::initialize() { } _commands.push_back(""); _activeCommand = _commands.size() - 1; + + OsEng.parallelConnection().connectionEvent()->subscribe("luaConsole", + "statusChanged", [this]() { + ParallelConnection::Status status = OsEng.parallelConnection().status(); + parallelConnectionChanged(status); + }); + } void LuaConsole::deinitialize() { @@ -102,6 +111,8 @@ void LuaConsole::deinitialize() { file.write(s.c_str(), length); } } + + OsEng.parallelConnection().connectionEvent()->unsubscribe("luaConsole"); } void LuaConsole::keyboardCallback(Key key, KeyModifier modifier, KeyAction action) { @@ -169,7 +180,8 @@ void LuaConsole::keyboardCallback(Key key, KeyModifier modifier, KeyAction actio else { std::string cmd = _commands.at(_activeCommand); if (cmd != "") { - OsEng.scriptEngine().queueScript(cmd); + OsEng.scriptEngine().queueScript(cmd, + _remoteScripting ? scripting::ScriptEngine::RemoteScripting::Yes : scripting::ScriptEngine::RemoteScripting::No); // Only add the current command to the history if it hasn't been // executed before. We don't want two of the same commands in a row @@ -303,19 +315,36 @@ void LuaConsole::charCallback(unsigned int codepoint, KeyModifier modifier) { void LuaConsole::render() { const float font_size = 10.0f; - int ySize = OsEng.windowWrapper().viewportPixelCoordinates().w; + int ySize = OsEng.renderEngine().fontResolution().y; + //int ySize = OsEng.windowWrapper().currentWindowSize().y; + //int ySize = OsEng.windowWrapper().viewportPixelCoordinates().w; float startY = static_cast(ySize) - 2.0f * font_size; startY = startY - font_size * 15.0f * 2.0f; const glm::vec4 red(1, 0, 0, 1); + const glm::vec4 lightBlue(0.4, 0.4, 1, 1); const glm::vec4 green(0, 1, 0, 1); const glm::vec4 white(1, 1, 1, 1); std::shared_ptr font = OsEng.fontManager().font("Mono", font_size); using ghoul::fontrendering::RenderFont; - RenderFont(*font, glm::vec2(15.f, startY), red, "$"); + if (_remoteScripting) { + int nClients = OsEng.parallelConnection().nConnections() - 1; + if (nClients == 1) { + RenderFont(*font, glm::vec2(15.f, startY + 20.0f), red, "Broadcasting script to 1 client"); + } else { + RenderFont(*font, glm::vec2(15.f, startY + 20.0f), red, ("Broadcasting script to " + std::to_string(nClients) + " clients").c_str()); + } + RenderFont(*font, glm::vec2(15.f, startY), red, "$"); + } + else { + if (OsEng.parallelConnection().isHost()) { + RenderFont(*font, glm::vec2(15.f, startY + 20.0f), lightBlue, "Local script execution"); + } + RenderFont(*font, glm::vec2(15.f, startY), lightBlue, "$"); + } RenderFont(*font, glm::vec2(15.f + font_size, startY), white, "%s", _commands.at(_activeCommand).c_str()); size_t n = std::count(_commands.at(_activeCommand).begin(), _commands.at(_activeCommand).begin() + _inputPosition, '\n'); @@ -390,10 +419,24 @@ void LuaConsole::setVisible(bool visible) { _isVisible = visible; } -void LuaConsole::toggleVisibility() { - _isVisible = !_isVisible; +void LuaConsole::toggleMode() { + if (_isVisible) { + if (_remoteScripting) { + _remoteScripting = false; + } else { + _isVisible = false; + } + } else { + _remoteScripting = OsEng.parallelConnection().isHost(); + _isVisible = true; + } } +void LuaConsole::parallelConnectionChanged(const ParallelConnection::Status& status) { + _remoteScripting = status == ParallelConnection::Status::Host; +} + + scripting::LuaLibrary LuaConsole::luaLibrary() { return { "console", diff --git a/src/interaction/luaconsole_lua.inl b/src/interaction/luaconsole_lua.inl index 99497bfaeb..97d6ec0b51 100644 --- a/src/interaction/luaconsole_lua.inl +++ b/src/interaction/luaconsole_lua.inl @@ -64,7 +64,7 @@ int toggle(lua_State* L) { if (nArguments != 0) return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments); - OsEng.console().toggleVisibility(); + OsEng.console().toggleMode(); return 0; } diff --git a/src/interaction/mousecontroller.cpp b/src/interaction/mousecontroller.cpp deleted file mode 100644 index d41535fcb4..0000000000 --- a/src/interaction/mousecontroller.cpp +++ /dev/null @@ -1,257 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - - - -//#define USE_OLD_INTERACTIONHANDLER -#ifdef USE_OLD_INTERACTIONHANDLER - -#include - -#include -#include - -#include - -namespace openspace { -namespace interaction { - -MouseController::MouseController() - : _lastTrackballPos(0.f) - , _isMouseBeingPressedAndHeld(false) -{} - -glm::vec3 MouseController::mapToTrackball(glm::vec2 mousePos) { - const float RADIUS = 0.5; // Sphere radius - glm::vec3 out = glm::vec3(mousePos.x - 0.5, -1.0*(mousePos.y - 0.5), 0); - - // Mapping according to Holroyds trackball - // Piece-wise sphere + hyperbolic sheet - if (out.x*out.x + out.y*out.y <= RADIUS*RADIUS / 2.0) { - //Spherical Region - out.z = RADIUS*RADIUS - (out.x*out.x + out.y*out.y); - out.z = out.z > 0.0f ? sqrtf(out.z) : 0.0f; - } - else { //Hyperbolic Region - for smooth z values - out.z = (RADIUS*RADIUS) / (2.0f*sqrt(out.x*out.x + out.y*out.y)); - } - - return glm::normalize(out); -} - -glm::vec3 MouseController::mapToCamera(glm::vec3 trackballPos) { - //Get x,y,z axis vectors of current camera view - glm::vec3 currentViewYaxis = glm::normalize(_handler->camera()->lookUpVectorCameraSpace()); - psc viewDir = _handler->camera()->position() - _handler->focusNode()->worldPosition(); - glm::vec3 currentViewZaxis = glm::normalize(viewDir.vec3()); - glm::vec3 currentViewXaxis = glm::normalize(glm::cross(currentViewYaxis, currentViewZaxis)); - - //mapping to camera co-ordinate - currentViewXaxis *= trackballPos.x; - currentViewYaxis *= trackballPos.y; - currentViewZaxis *= trackballPos.z; - return (currentViewXaxis + currentViewYaxis + currentViewZaxis); -} - -void MouseController::trackballRotate(int x, int y) { - // Normalize mouse coordinates to [0,1] - glm::vec2 res = OsEng.windowWrapper().currentWindowSize(); - glm::vec2 mousePos = glm::vec2((float)x / res.x, (float)y / res.y); - - mousePos = glm::clamp(mousePos, -0.5f, 1.5f); // Ugly fix #1: Camera position becomes NaN on mouse values outside [-0.5, 1.5] - //mousePos[1] = 0.5; // Ugly fix #2: Tempoarily only allow rotation around y - - glm::vec3 curTrackballPos = mapToTrackball(mousePos); - // LDEBUG(mousePos.x << ", " << mousePos.y << " = " << curTrackballPos.x << ", " << curTrackballPos.y << ", " << curTrackballPos.z); - - // Disable movement on the first click for extra smoothness - if (!_isMouseBeingPressedAndHeld) { - _lastTrackballPos = curTrackballPos; - _isMouseBeingPressedAndHeld = true; - } - - if (curTrackballPos != _lastTrackballPos) { - // calculate rotation angle (in radians) - float rotationAngle = glm::angle(curTrackballPos, _lastTrackballPos); - //rotationAngle *= static_cast(_handler->deltaTime()) * 100.0f; - - // Map trackballpos to camera - // glm::vec3 trackballMappedToCamera = mapToCamera(_lastTrackballPos - curTrackballPos); - // psc currentCamPos = camera_->getPosition(); - // glm::vec3 nextCamPos = currentCamPos.getVec3f() + trackballMappedToCamera; - // glm::vec3 rotationAxis = glm::cross(currentCamPos.getVec3f(), nextCamPos); - - glm::vec3 rotationAxis = glm::cross(_lastTrackballPos, curTrackballPos); - rotationAxis = glm::normalize(rotationAxis); - glm::quat quaternion = glm::angleAxis(rotationAngle, rotationAxis); - - // Apply quaternion to camera - //_handler->orbitDelta(quaternion); - - _lastTrackballPos = curTrackballPos; - } -} - - -TrackballMouseController::TrackballMouseController() - : MouseController() - , _leftMouseButtonDown(false) -{} - -void TrackballMouseController::button(MouseButton button, MouseAction action) { - if (button == MouseButton::Left && action == MouseAction::Press) - _leftMouseButtonDown = true; - else if (button == MouseButton::Left && action == MouseAction::Release) { - _leftMouseButtonDown = false; - _isMouseBeingPressedAndHeld = false; - } -} - -void TrackballMouseController::move(float x, float y) { - if (_leftMouseButtonDown) - trackballRotate(static_cast(x), static_cast(y)); -} - -void TrackballMouseController::scrollWheel(int pos) { - /* - const float speed = 4.75f; - const float dt = static_cast(_handler->deltaTime()); - if (pos < 0) { - PowerScaledScalar dist(speed * dt, 0.0f); - _handler->distanceDelta(dist); - } - else if (pos > 0) { - PowerScaledScalar dist(-speed * dt, 0.0f); - _handler->distanceDelta(dist); - } - */ -} - -void TrackballMouseController::update(const double& dt){ - -} - - -OrbitalMouseController::OrbitalMouseController() - : MouseController() - , _leftMouseButtonDown(false) - , _rightMouseButtonDown(false) - , _middleMouseButtonDown(false) - , _currentCursorPos(0) - , _rotationSpeed(10.f) - , _navigationSpeed(3.f) -{ - for (int n = 0; n < 3; ++n){ - _previousCursorPos[n] = glm::vec2(0); - } -} - -void OrbitalMouseController::button(MouseButton button, MouseAction action) { - if (button == MouseButton::Left){ - if (action == MouseAction::Press){ - _leftMouseButtonDown = true; - _previousCursorPos[MouseButtons::ButtonLeft] = OsEng.windowWrapper().mousePosition(); - } - else if (action == MouseAction::Release) { - _leftMouseButtonDown = false; - _currentCursorDiff[MouseButtons::ButtonLeft] = glm::vec2(0); - } - } - else if (button == MouseButton::Right){ - if (action == MouseAction::Press){ - _rightMouseButtonDown = true; - _previousCursorPos[MouseButtons::ButtonRight] = OsEng.windowWrapper().mousePosition(); - } - else if (action == MouseAction::Release) { - _rightMouseButtonDown = false; - _currentCursorDiff[MouseButtons::ButtonRight] = glm::vec2(0); - } - } - else if (button == MouseButton::Middle){ - if (action == MouseAction::Press){ - _middleMouseButtonDown = true; - _previousCursorPos[MouseButtons::ButtonMiddle] = OsEng.windowWrapper().mousePosition(); - } - else if (action == MouseAction::Release) { - _middleMouseButtonDown = false; - _currentCursorDiff[MouseButtons::ButtonMiddle] = glm::vec2(0); - } - } - -} - -void OrbitalMouseController::move(float x, float y) { - _currentCursorPos = OsEng.windowWrapper().mousePosition(); - - if (_leftMouseButtonDown) { - glm::vec2 diff = _currentCursorPos - _previousCursorPos[MouseButtons::ButtonLeft]; - glm::vec2 res = OsEng.windowWrapper().currentWindowSize(); - _currentCursorDiff[MouseButtons::ButtonLeft] = diff / res; - } - if (_rightMouseButtonDown) { - glm::vec2 diff = _currentCursorPos - _previousCursorPos[MouseButtons::ButtonRight]; - glm::vec2 res = OsEng.windowWrapper().currentWindowSize(); - _currentCursorDiff[MouseButtons::ButtonRight] = diff / res; - } - if (_middleMouseButtonDown) { - glm::vec2 diff = _currentCursorPos - _previousCursorPos[MouseButtons::ButtonMiddle]; - glm::vec2 res = OsEng.windowWrapper().currentWindowSize(); - _currentCursorDiff[MouseButtons::ButtonMiddle] = diff / res; - } -} - -void OrbitalMouseController::scrollWheel(int pos) { - -} - -void OrbitalMouseController::update(const double& dt){ - /* - const float interactionSpeed = OsEng.interactionHandler().interactionSensitivity(); - const bool rotationInvert = OsEng.interactionHandler().invertRotation(); - const bool rollInvert = OsEng.interactionHandler().invertRoll(); - - //if (_leftMouseButtonDown || _rightMouseButtonDown || _middleMouseButtonDown){ - _handler->orbit( - static_cast(_leftMouseButtonDown) * static_cast(dt) * _currentCursorDiff[MouseButtons::ButtonLeft].x * interactionSpeed * (rotationInvert ? -1.f : 1.f), - static_cast(_leftMouseButtonDown) * static_cast(dt) * _currentCursorDiff[MouseButtons::ButtonLeft].y * interactionSpeed * (rotationInvert ? -1.f : 1.f), - static_cast(_middleMouseButtonDown) * static_cast(dt) * _currentCursorDiff[MouseButtons::ButtonMiddle].x * interactionSpeed * (rollInvert ? -1.f : 1.f), - static_cast(_rightMouseButtonDown) * static_cast(dt) * _currentCursorDiff[MouseButtons::ButtonRight].y * _navigationSpeed); - //} - */ - -// if (_leftMouseButtonDown){ -// _handler->orbit(static_cast(dt)* _currentCursorDiff[MouseButtons::ButtonLeft].x * _rotationSpeed, static_cast(dt)* _currentCursorDiff[MouseButtons::ButtonLeft].y * _rotationSpeed, 0.f); -// } -// if (_middleMouseButtonDown){ -// _handler->orbit(0.f, 0.f, static_cast(dt)* _currentCursorDiff[MouseButtons::ButtonMiddle].x * _rotationSpeed); -// } -// if (_rightMouseButtonDown){ -// _handler->distance(static_cast(dt)* _currentCursorDiff[MouseButtons::ButtonRight].y * _navigationSpeed); -// } -} - -} // namespace interaction -} // namespace openspace - -#endif // USE_OLD_INTERACTIONHANDLER diff --git a/src/mission/mission.cpp b/src/mission/mission.cpp index 8daed0de72..b8bdb20db8 100644 --- a/src/mission/mission.cpp +++ b/src/mission/mission.cpp @@ -24,18 +24,12 @@ #include -#include -#include -#include -#include -#include -#include - #include -namespace { - const std::string _loggerCat = "MissionPhaseSequencer"; +#include +#include +namespace { const std::string KeyName = "Name"; const std::string KeyDescription = "Description"; const std::string KeyPhases = "Phases"; @@ -44,7 +38,6 @@ namespace { namespace openspace { - Documentation MissionPhase::Documentation() { using namespace documentation; @@ -85,15 +78,8 @@ Documentation MissionPhase::Documentation() { } MissionPhase::MissionPhase(const ghoul::Dictionary& dict) { - const auto byPhaseStartTime = [](const MissionPhase& a, const MissionPhase& b)->bool{ - return a.timeRange().start < b.timeRange().start; - }; - _name = dict.value(KeyName); - if (!dict.getValue(KeyDescription, _description)) { - // If no description specified, just init to empty string - _description = ""; - } + dict.getValue(KeyDescription, _description); ghoul::Dictionary childDicts; if (dict.getValue(KeyPhases, childDicts)) { @@ -101,11 +87,17 @@ MissionPhase::MissionPhase(const ghoul::Dictionary& dict) { _subphases.reserve(childDicts.size()); for (size_t i = 0; i < childDicts.size(); ++i) { std::string key = std::to_string(i + 1); - _subphases[i] = MissionPhase(childDicts.value(key)); + _subphases.emplace_back(childDicts.value(key)); } // Ensure subphases are sorted - std::stable_sort(_subphases.begin(), _subphases.end(), byPhaseStartTime); + std::stable_sort( + _subphases.begin(), + _subphases.end(), + [](const MissionPhase& a, const MissionPhase& b) { + return a.timeRange().start < b.timeRange().start; + } + ); // Calculate the total time range of all subphases TimeRange timeRangeSubPhases; @@ -116,8 +108,13 @@ MissionPhase::MissionPhase(const ghoul::Dictionary& dict) { ghoul::Dictionary timeRangeDict; if (dict.getValue(KeyTimeRange, timeRangeDict)) { TimeRange overallTimeRange(timeRangeDict); - ghoul_assert(overallTimeRange.includes(timeRangeSubPhases), - "User specified time range must at least include its subphases'"); + if (!overallTimeRange.includes(timeRangeSubPhases)) { + throw ghoul::RuntimeError( + "User specified time range must at least include its subphases'", + "Mission (" + _name + ")" + ); + } + _timeRange.include(overallTimeRange); } else { @@ -132,7 +129,10 @@ MissionPhase::MissionPhase(const ghoul::Dictionary& dict) { _timeRange = TimeRange(timeRangeDict); // throws exception if unable to parse } else { - throw std::runtime_error("Must specify key: " + KeyTimeRange); + throw ghoul::RuntimeError( + "If there are no subphases specified, the time range has to be specified", + "Mission (" + _name + ")" + ); } } } @@ -149,48 +149,35 @@ const std::string & MissionPhase::description() const { return _description; } -/** -* Returns all subphases sorted by start time -*/ - const std::vector& MissionPhase::phases() const { return _subphases; } -/** -* Returns the i:th subphase, sorted by start time -*/ - -const MissionPhase& MissionPhase::phase(size_t i) const { - return _subphases[i]; -} - -std::vector MissionPhase::phaseTrace(double time, int maxDepth) const { - std::vector trace; +MissionPhase::Trace MissionPhase::phaseTrace(double time, int maxDepth) const { + Trace trace; if (_timeRange.includes(time)) { - trace.push_back(this); + trace.push_back(std::cref(*this)); phaseTrace(time, trace, maxDepth); } return std::move(trace); } -bool MissionPhase::phaseTrace(double time, std::vector& trace, int maxDepth) const { +void MissionPhase::phaseTrace(double time, Trace& trace, int maxDepth) const { if (maxDepth == 0) { - return false; + return; } - for (int i = 0; i < _subphases.size(); ++i) { - if (_subphases[i]._timeRange.includes(time)) { - trace.push_back(&_subphases[i]); - _subphases[i].phaseTrace(time, trace, maxDepth - 1); - return true; // only add the first one + for (const MissionPhase& phase : _subphases) { + if (phase.timeRange().includes(time)) { + trace.push_back(phase); + phase.phaseTrace(time, trace, maxDepth - 1); + return; } - // Since time ranges are sorted we can do early termination - else if (_subphases[i]._timeRange.start > time) { - return false; + else if (phase.timeRange().start > time) { + // Since time ranges are sorted we can do early termination + return; } } - return true; } Mission missionFromFile(std::string filename) { diff --git a/src/mission/missionmanager.cpp b/src/mission/missionmanager.cpp index 71ed449e53..56cb58be64 100644 --- a/src/mission/missionmanager.cpp +++ b/src/mission/missionmanager.cpp @@ -38,19 +38,13 @@ MissionManager::MissionManagerException::MissionManagerException(std::string err : ghoul::RuntimeError(std::move(error), "MissionManager") {} -MissionManager MissionManager::_instance; -MissionManager& MissionManager::ref() { - return _instance; -} - -void MissionManager::initialize() { - OsEng.scriptEngine().addLibrary(MissionManager::luaLibrary()); -} - -void MissionManager::deinitialize() {} +MissionManager::MissionManager() + : _currentMission(_missionMap.end()) +{} void MissionManager::setCurrentMission(const std::string& missionName) { + ghoul_assert(!missionName.empty(), "missionName must not be empty"); auto it = _missionMap.find(missionName); if (it == _missionMap.end()) { throw MissionManagerException("Mission has not been loaded"); @@ -70,15 +64,18 @@ void MissionManager::loadMission(const std::string& filename) { ghoul_assert(FileSys.fileExists(filename), "filename must exist"); // Changing the values might invalidate the _currentMission iterator - const std::string& currentMission = _currentMission->first; + std::string currentMission = _currentMission != _missionMap.end() ? _currentMission->first : ""; Mission mission = missionFromFile(filename); - _missionMap.insert({ mission.name(), std::move(mission) }); + std::string missionName = mission.name(); + _missionMap.insert({ missionName, std::move(mission) }); if (_missionMap.size() == 1) { - setCurrentMission(mission.name()); + setCurrentMission(missionName); } - setCurrentMission(currentMission); + if (!currentMission.empty()) { + setCurrentMission(currentMission); + } } bool MissionManager::hasMission(const std::string& missionName) { @@ -114,8 +111,5 @@ scripting::LuaLibrary MissionManager::luaLibrary() { // Singleton -MissionManager::MissionManager() - : _currentMission(_missionMap.end()) -{} } // namespace openspace diff --git a/src/mission/missionmanager_lua.inl b/src/mission/missionmanager_lua.inl index a56d3b7f6a..75840b3f27 100644 --- a/src/mission/missionmanager_lua.inl +++ b/src/mission/missionmanager_lua.inl @@ -35,7 +35,7 @@ namespace luascriptfunctions { if (missionFileName.empty()) { return luaL_error(L, "filepath string is empty"); } - MissionManager::ref().loadMission(missionFileName); + MissionManager::ref().loadMission(absPath(missionFileName)); } int setCurrentMission(lua_State* L) { diff --git a/src/network/networkengine.cpp b/src/network/networkengine.cpp index 6b8b58b54f..a3a9c3e375 100644 --- a/src/network/networkengine.cpp +++ b/src/network/networkengine.cpp @@ -27,6 +27,8 @@ #include #include +#include + #include #include #include @@ -67,7 +69,7 @@ bool NetworkEngine::handleMessage(const std::string& message) { { std::string script = message.substr(1); //LINFO("Received Lua Script: '" << script << "'"); - OsEng.scriptEngine().queueScript(script); + OsEng.scriptEngine().queueScript(script, scripting::ScriptEngine::RemoteScripting::No); return true; } case MessageTypeExternalControlConnected: diff --git a/src/network/parallelconnection.cpp b/src/network/parallelconnection.cpp index f8579a0f5e..9eb0a8d60c 100644 --- a/src/network/parallelconnection.cpp +++ b/src/network/parallelconnection.cpp @@ -52,10 +52,21 @@ #endif #endif +#ifdef WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#include +#include +#endif + //openspace includes #include #include +#include #include +#include #include #include #include @@ -64,13 +75,16 @@ #include "parallelconnection_lua.inl" namespace { + const uint32_t ProtocolVersion = 2; + const size_t MaxLatencyDiffs = 64; + const double BroadcastIntervalMilliseconds = 100; const std::string _loggerCat = "ParallelConnection"; + const int nFrametimesBuffer = 4; + const int nBroadcastIntervalsBuffer = 2; } namespace openspace { -namespace network { - ParallelConnection::ParallelConnection() : _passCode(0) , _port("20501") @@ -83,15 +97,16 @@ ParallelConnection::ParallelConnection() , _listenThread(nullptr) , _handlerThread(nullptr) , _isRunning(true) - , _isHost(false) + , _nConnections(0) + , _status(Status::Disconnected) + , _hostName("") , _isConnected(false) , _tryConnect(false) - , _performDisconnect(false) - , _latestTimeKeyframeValid(false) + , _disconnect(false) , _initializationTimejumpRequired(false) { - //create handler thread - _handlerThread = new (std::nothrow) std::thread(&ParallelConnection::threadManagement, this); + _connectionEvent = std::make_shared>(); + _handlerThread = std::make_unique(&ParallelConnection::threadManagement, this); } ParallelConnection::~ParallelConnection(){ @@ -104,9 +119,6 @@ ParallelConnection::~ParallelConnection(){ //join handler _handlerThread->join(); - - //and delete handler - delete _handlerThread; } void ParallelConnection::threadManagement(){ @@ -114,13 +126,13 @@ void ParallelConnection::threadManagement(){ // How about moving this out of the thread and into the destructor? ---abock //while we're still running - while(_isRunning.load()){ + while(_isRunning){ { //lock disconnect mutex mutex //not really needed since no data is modified but conditions need a mutex - std::unique_lock unqlock(_disconnectMutex); + std::unique_lock disconnectLock(_disconnectMutex); //wait for a signal to disconnect - _disconnectCondition.wait(unqlock); + _disconnectCondition.wait(disconnectLock, [this]() { return _disconnect.load(); }); //perform actual disconnect disconnect(); @@ -131,7 +143,9 @@ void ParallelConnection::threadManagement(){ void ParallelConnection::signalDisconnect(){ //signal handler thread to disconnect - _disconnectCondition.notify_all(); + _disconnect = true; + _sendCondition.notify_all(); // Allow send function to terminate. + _disconnectCondition.notify_all(); // Unblock thread management thread. } void ParallelConnection::closeSocket(){ @@ -174,41 +188,34 @@ void ParallelConnection::disconnect(){ _isConnected.store(false); //tell broadcast thread to stop broadcasting (we're no longer host) - _isHost.store(false); - - //signal send thread to stop waiting and finish current run - _sendCondition.notify_all(); - + setStatus(Status::Disconnected); + //join connection thread and delete it if(_connectionThread != nullptr){ _connectionThread->join(); - delete _connectionThread; _connectionThread = nullptr; } //join send thread and delete it if (_sendThread != nullptr){ _sendThread->join(); - delete _sendThread; _sendThread = nullptr; } //join listen thread and delete it if( _listenThread != nullptr){ _listenThread->join(); - delete _listenThread; _listenThread = nullptr; } //join broadcast thread and delete it if(_broadcastThread != nullptr){ _broadcastThread->join(); - delete _broadcastThread; _broadcastThread = nullptr; } // disconnect and cleanup completed - _performDisconnect.store(false); + _disconnect = false; } } @@ -225,11 +232,9 @@ void ParallelConnection::clientConnect(){ } struct addrinfo *addresult = NULL, *ptr = NULL, hints; - #ifdef __WIN32__ //WinSock - ZeroMemory(&hints, sizeof(hints)); - #else - memset(&hints, 0, sizeof(hints)); - #endif + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; @@ -250,7 +255,7 @@ void ParallelConnection::clientConnect(){ _tryConnect.store(true); //start connection thread - _connectionThread = new (std::nothrow) std::thread(&ParallelConnection::establishConnection, this, addresult); + _connectionThread = std::make_unique(&ParallelConnection::establishConnection, this, addresult); } @@ -266,14 +271,15 @@ void ParallelConnection::establishConnection(addrinfo *info){ signalDisconnect(); } - int flag = 1; + int trueFlag = 1; + int falseFlag = 0; int result; //set no delay result = setsockopt(_clientSocket, /* socket affected */ IPPROTO_TCP, /* set option at TCP level */ TCP_NODELAY, /* name of option */ - (char *)&flag, /* the cast is historical cruft */ + (char *)&trueFlag, /* the cast is historical cruft */ sizeof(int)); /* length of option value */ //set send timeout @@ -293,11 +299,11 @@ void ParallelConnection::establishConnection(addrinfo *info){ (char *)&timeout, sizeof(timeout)); - result = setsockopt(_clientSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&flag, sizeof(int)); + result = setsockopt(_clientSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&falseFlag, sizeof(int)); if (result == SOCKET_ERROR) LERROR("Failed to set socket option 'reuse address'. Error code: " << _ERRNO); - result = setsockopt(_clientSocket, SOL_SOCKET, SO_KEEPALIVE, (char*)&flag, sizeof(int)); + result = setsockopt(_clientSocket, SOL_SOCKET, SO_KEEPALIVE, (char*)&trueFlag, sizeof(int)); if (result == SOCKET_ERROR) LERROR("Failed to set socket option 'keep alive'. Error code: " << _ERRNO); @@ -320,19 +326,25 @@ void ParallelConnection::establishConnection(addrinfo *info){ _isConnected.store(true); //start sending messages - _sendThread = new (std::nothrow) std::thread(&ParallelConnection::sendFunc, this); + _sendThread = std::make_unique(&ParallelConnection::sendFunc, this); //start listening for communication - _listenThread = new (std::nothrow) std::thread(&ParallelConnection::listenCommunication, this); + _listenThread = std::make_unique(&ParallelConnection::listenCommunication, this); //we no longer need to try to establish connection _tryConnect.store(false); + _sendBufferMutex.lock(); + _sendBuffer.clear(); + _sendBufferMutex.unlock(); + //send authentication sendAuthentication(); + } else { + LINFO("Connection attempt failed."); } -#ifdef __WIN32__ +#ifdef WIN32 //on windows: try to connect once per second std::this_thread::sleep_for(std::chrono::seconds(1)); #else @@ -353,52 +365,46 @@ void ParallelConnection::establishConnection(addrinfo *info){ freeaddrinfo(info); } -void ParallelConnection::sendAuthentication(){ +void ParallelConnection::sendAuthentication() { //length of this nodes name - uint16_t namelen = static_cast(_name.length()); + uint32_t nameLength = static_cast(_name.length()); - //total size of the buffer, header + size of passcodde + namelength + size of namelength - int size = headerSize() + sizeof(uint32_t) + sizeof(namelen) + static_cast(namelen); + //total size of the buffer: (passcode + namelength + name) + size_t size = 2 * sizeof(uint32_t) + nameLength; //create and reserve buffer std::vector buffer; buffer.reserve(size); - //write header to buffer - writeHeader(buffer, MessageTypes::Authentication); - //write passcode to buffer buffer.insert(buffer.end(), reinterpret_cast(&_passCode), reinterpret_cast(&_passCode) + sizeof(uint32_t)); //write the length of the nodes name to buffer - buffer.insert(buffer.end(), reinterpret_cast(&namelen), reinterpret_cast(&namelen) + sizeof(uint16_t)); + buffer.insert(buffer.end(), reinterpret_cast(&nameLength), reinterpret_cast(&nameLength) + sizeof(uint32_t)); - //write this nodes name to buffer + //write this node's name to buffer buffer.insert(buffer.end(), _name.begin(), _name.end()); //send buffer - queueMessage(buffer); + queueOutMessage(Message(MessageType::Authentication, buffer)); } -void ParallelConnection::delegateDecoding(uint32_t type){ - switch (type){ - case MessageTypes::Authentication: - //not used + +void ParallelConnection::queueInMessage(const Message& message) { + std::unique_lock unqlock(_receiveBufferMutex); + _receiveBuffer.push_back(message); +} + +void ParallelConnection::handleMessage(const Message& message) { + switch (message.type){ + case MessageType::Data: + dataMessageReceived(message.content); break; - case MessageTypes::Initialization: - initializationMessageReceived(); + case MessageType::ConnectionStatus: + connectionStatusMessageReceived(message.content); break; - case MessageTypes::Data: - dataMessageReceived(); - break; - case MessageTypes::Script: - //not used - break; - case MessageTypes::HostInfo: - hostInfoMessageReceived(); - break; - case MessageTypes::InitializationRequest: - initializationRequestMessageReceived(); + case MessageType::NConnections: + nConnectionsMessageReceived(message.content); break; default: //unknown message type @@ -406,6 +412,7 @@ void ParallelConnection::delegateDecoding(uint32_t type){ } } +/* void ParallelConnection::initializationMessageReceived(){ int result; @@ -476,116 +483,77 @@ void ParallelConnection::initializationMessageReceived(){ writeHeader(buffer, MessageTypes::InitializationCompleted); //let the server know - queueMessage(buffer); + std::cout << "initialization message recieved queue" << std::endl; + queueMessage(InitializationCompleted, buffer); //we also need to force a time jump just to ensure that the server and client are synced _initializationTimejumpRequired.store(true); } +*/ -void ParallelConnection::dataMessageReceived(){ - int result; - uint16_t msglen; - uint16_t type; +double ParallelConnection::calculateBufferedKeyframeTime(double originalTime) { + std::lock_guard latencyLock(_latencyMutex); - //create a buffer to hold the size of streamdata message - std::vector buffer; - buffer.resize(sizeof(type)); - - //read type of data message - result = receiveData(_clientSocket, buffer, sizeof(type), 0); - - if (result <= 0){ - //error - LERROR("Failed to read type of data message received."); - return; + double timeDiff = OsEng.runTime() - originalTime; + if (_latencyDiffs.size() == 0) { + _initialTimeDiff = timeDiff; } - + double latencyDiff = timeDiff - _initialTimeDiff; + if (_latencyDiffs.size() >= MaxLatencyDiffs) { + _latencyDiffs.pop_front(); + } + _latencyDiffs.push_back(latencyDiff); + + double accumulatedLatencyDiffSquared = 0; + double accumulatedLatencyDiff = 0; + for (double diff : _latencyDiffs) { + accumulatedLatencyDiff += diff; + accumulatedLatencyDiffSquared += diff*diff; + } + double expectedLatencyDiffSquared = accumulatedLatencyDiffSquared / _latencyDiffs.size(); + double expectedLatencyDiff = accumulatedLatencyDiff / _latencyDiffs.size(); + + // V(X) = E(x^2) - E(x)^2 + double latencyVariance = expectedLatencyDiffSquared - expectedLatencyDiff*expectedLatencyDiff; + double latencyStandardDeviation = std::sqrt(latencyVariance); + + double frametime = OsEng.windowWrapper().averageDeltaTime(); + + double latencyCompensation = std::max(expectedLatencyDiff + 2 * latencyStandardDeviation, latencyDiff); + + return originalTime + timeDiff + nBroadcastIntervalsBuffer * BroadcastIntervalMilliseconds / 1000 + latencyCompensation + nFrametimesBuffer * frametime; + +} + +void ParallelConnection::dataMessageReceived(const std::vector& messageContent) { + //the type of data message received - type =(*(reinterpret_cast(buffer.data()))); - - //read size of streamdata message - result = receiveData(_clientSocket, buffer, sizeof(msglen), 0); - - if (result <= 0){ - //error - LERROR("Failed to read size of data message received."); - return; - } - - //the size in bytes of the streamdata message - msglen = (*(reinterpret_cast(buffer.data()))); + uint32_t type = *(reinterpret_cast(messageContent.data())); + std::vector buffer(messageContent.begin() + sizeof(uint32_t), messageContent.end()); + + switch(static_cast(type)) { + case datamessagestructures::Type::CameraData: { - //resize the buffer to be able to read the streamdata - buffer.clear(); - buffer.resize(msglen); + datamessagestructures::CameraKeyframe kf(buffer); + kf._timestamp = calculateBufferedKeyframeTime(kf._timestamp); - //read the data into buffer - result = receiveData(_clientSocket, buffer, msglen, 0); - - if (result <= 0){ - //error - LERROR("Failed to read data message."); - return; - } - - //which type of data message was received? - switch(type){ - case network::datamessagestructures::PositionData:{ - //position data message - //create and read a position keyframe from the data buffer - network::datamessagestructures::PositionKeyframe kf; - kf.deserialize(buffer); - - //add the keyframe to the interaction handler OsEng.interactionHandler().addKeyframe(kf); break; } - case network::datamessagestructures::TimeData:{ - //time data message - //create and read a time keyframe from the data buffer - network::datamessagestructures::TimeKeyframe tf; - tf.deserialize(buffer); - - //lock mutex and assign latest time keyframe parameters - _timeKeyframeMutex.lock(); - - _latestTimeKeyframe._dt = tf._dt; - _latestTimeKeyframe._time = tf._time; - _latestTimeKeyframe._paused = tf._paused; - - //ensure that we never miss a timejump - //if last keyframe required a jump and that keyframe has not been used yet - if(_latestTimeKeyframe._requiresTimeJump && _latestTimeKeyframeValid){ - //do nothing to the boolean. Old value must be executed - }else{ - //either the latest keyframe didnt require a jump, or we have already spent that keyframe. - //in either case we can go ahead and write the bool value of newest frame - _latestTimeKeyframe._requiresTimeJump = tf._requiresTimeJump; - } - - //if we're just initialized we need to perform a time jump as soon as a valid keyframe has been received - if(_initializationTimejumpRequired.load() && _latestTimeKeyframeValid){ - _latestTimeKeyframe._requiresTimeJump = true; - _initializationTimejumpRequired.store(false); - } - - //unlock mutex - _timeKeyframeMutex.unlock(); - - //the keyframe is now valid for use - _latestTimeKeyframeValid.store(true); - + case datamessagestructures::Type::TimeData: { + + datamessagestructures::TimeKeyframe kf(buffer); + kf._timestamp = calculateBufferedKeyframeTime(kf._timestamp); + + OsEng.timeManager().addKeyframe(kf); break; } - case network::datamessagestructures::ScriptData:{ - //script data message - //create and read a script message from data buffer - network::datamessagestructures::ScriptMessage sm; + case datamessagestructures::Type::ScriptData: { + datamessagestructures::ScriptMessage sm; sm.deserialize(buffer); - - //Que script to be executed by script engine - OsEng.scriptEngine().queueScript(sm._script); + OsEng.scriptEngine().queueScript(sm._script, scripting::ScriptEngine::RemoteScripting::No); + break; } default:{ @@ -595,113 +563,152 @@ void ParallelConnection::dataMessageReceived(){ } } -void ParallelConnection::queueMessage(std::vector message){ - { - std::unique_lock unqlock(_sendBufferMutex); - _sendBuffer.push_back(message); - _sendCondition.notify_all(); - } +void ParallelConnection::queueOutDataMessage(const DataMessage& dataMessage) { + uint32_t dataMessageTypeOut = static_cast(dataMessage.type); + + std::vector messageContent; + messageContent.insert(messageContent.end(), + reinterpret_cast(&dataMessageTypeOut), + reinterpret_cast(&dataMessageTypeOut) + sizeof(uint32_t)); + + messageContent.insert(messageContent.end(), + dataMessage.content.begin(), + dataMessage.content.end()); + + queueOutMessage(Message(MessageType::Data, messageContent)); +} + +void ParallelConnection::queueOutMessage(const Message& message) { + std::unique_lock unqlock(_sendBufferMutex); + _sendBuffer.push_back(message); + _sendCondition.notify_all(); } void ParallelConnection::sendFunc(){ int result; //while we're connected - while(_isConnected.load()){ - { - //wait for signal then lock mutex and send first queued message - std::unique_lock unqlock(_sendBufferMutex); - _sendCondition.wait_for(unqlock, std::chrono::milliseconds(500)); - - if(!_sendBuffer.empty()){ - while(!_sendBuffer.empty()){ - result = send(_clientSocket, _sendBuffer.front().data(), _sendBuffer.front().size(), 0); - _sendBuffer.erase(_sendBuffer.begin()); - - //make sure everything went well - if (result == SOCKET_ERROR){ - //failed to send message - LERROR("Failed to send message.\nError: " << _ERRNO << " detected in connection, disconnecting."); - - //signal that a disconnect should be performed - signalDisconnect(); - } - } - } + while(_isConnected && !_disconnect) { + //wait for signal then lock mutex and send first queued message + std::unique_lock unqlock(_sendBufferMutex); + _sendCondition.wait(unqlock); + + if (_disconnect) { + break; + } + + while (!_sendBuffer.empty()) { + Message message = _sendBuffer.front(); + unqlock.unlock(); + std::vector header; + + //insert header into buffer + header.push_back('O'); + header.push_back('S'); + + uint32_t messageTypeOut = static_cast(message.type); + uint32_t messageSizeOut = static_cast(message.content.size()); + + + header.insert(header.end(), + reinterpret_cast(&ProtocolVersion), + reinterpret_cast(&ProtocolVersion) + sizeof(uint32_t)); + + header.insert(header.end(), + reinterpret_cast(&messageTypeOut), + reinterpret_cast(&messageTypeOut) + sizeof(uint32_t)); + + header.insert(header.end(), + reinterpret_cast(&messageSizeOut), + reinterpret_cast(&messageSizeOut) + sizeof(uint32_t)); + + result = send(_clientSocket, header.data(), header.size(), 0); + result = send(_clientSocket, message.content.data(), message.content.size(), 0); + + if (result == SOCKET_ERROR) { + LERROR("Failed to send message.\nError: " << _ERRNO << " detected in connection, disconnecting."); + signalDisconnect(); + } + + unqlock.lock(); + _sendBuffer.erase(_sendBuffer.begin()); } - } + std::lock_guard sendLock(_sendBufferMutex); + _sendBuffer.clear(); + } -void ParallelConnection::hostInfoMessageReceived(){ - //create buffer - std::vector hostflag; - //resize to hold a flag saying if we're host or not - hostflag.resize(1); - - //read data into buffer - int result = receiveData(_clientSocket, hostflag, 1, 0); +void ParallelConnection::connectionStatusMessageReceived(const std::vector& message) { + if (message.size() < 2 * sizeof(uint32_t)) { + LERROR("Malformed connection status message."); + return; + } + size_t pointer = 0; + uint32_t statusIn = *(reinterpret_cast(&message[pointer])); + ParallelConnection::Status status = static_cast(statusIn); + pointer += sizeof(uint32_t); - //enough data was read - if (result > 0){ - - //we've been assigned as host - if (hostflag.at(0) == 1){ - - //we're already host, do nothing (dummy check) - if (_isHost.load()){ - return; - } - else{ - - //we're the host - _isHost.store(true); + size_t hostNameSize = *(reinterpret_cast(&message[pointer])); + pointer += sizeof(uint32_t); - //start broadcasting - _broadcastThread = new (std::nothrow) std::thread(&ParallelConnection::broadcast, this); - } - } - else{ //we've been assigned as client - - //we were broadcasting but should stop now - if (_isHost.load()){ + if (hostNameSize > message.size() - pointer) { + LERROR("Malformed connection status message."); + return; + } - //stop broadcast loop - _isHost.store(false); - - //and delete broadcasting thread - if (_broadcastThread != nullptr){ - _broadcastThread->join(); - delete _broadcastThread; - _broadcastThread = nullptr; - } - } - else{ - //we were not broadcasting so nothing to do - } - - //clear buffered any keyframes - OsEng.interactionHandler().clearKeyframes(); - - //request init package from the host - int size = headerSize(); - std::vector buffer; - buffer.reserve(size); - - //write header - writeHeader(buffer, MessageTypes::InitializationRequest); + std::string hostName = ""; + if (hostNameSize > 0) { + hostName = std::string(&message[pointer], hostNameSize); + } + pointer += hostNameSize; + + if (status > Status::Host) { + LERROR("Invalid status."); + return; + } - //send message - queueMessage(buffer); + _latencyMutex.lock(); + _latencyDiffs.clear(); + _latencyMutex.unlock(); + setHostName(hostName); + + if (status == _status) { + //status remains unchanged. + return; + } + + setStatus(status); + + if (status == Status::Host) { // assigned as host + _broadcastThread = std::make_unique(&ParallelConnection::broadcast, this); + } else { // assigned as client + + // delete broadcasting thread + // (the thread is allowed to terminate once the status is set to non-host.) + if (_broadcastThread != nullptr) { + _broadcastThread->join(); + _broadcastThread = nullptr; } } - else{ - LERROR("Error " << _ERRNO << " detected in connection, disconnecting."); - signalDisconnect(); - } + OsEng.interactionHandler().clearKeyframes(); + OsEng.timeManager().clearKeyframes(); + } -void ParallelConnection::initializationRequestMessageReceived(){ - +void ParallelConnection::nConnectionsMessageReceived(const std::vector& message) { + if (message.size() < sizeof(uint32_t)) { + LERROR("Malformed host info message."); + return; + } + uint32_t nConnections = *(reinterpret_cast(&message[0])); + setNConnections(nConnections); +} + + + + +//void ParallelConnection::initializationRequestMessageReceived(const std::vector& message){ + /* //get current state as scripts std::vector scripts; std::map::iterator state_it; @@ -731,7 +738,7 @@ void ParallelConnection::initializationRequestMessageReceived(){ //serialize and encode all scripts into scriptbuffer std::vector::iterator script_it; - network::datamessagestructures::ScriptMessage sm; + datamessagestructures::ScriptMessage sm; for(script_it = scripts.begin(); script_it != scripts.end(); ++script_it){ @@ -767,56 +774,70 @@ void ParallelConnection::initializationRequestMessageReceived(){ buffer.insert(buffer.end(), scriptbuffer.begin(), scriptbuffer.end()); //queue message - queueMessage(buffer); -} + std::cout << "initializationRequest queue" << std::endl; + queueMessage(MessageType::Initialization, buffer); + */ +//} -void ParallelConnection::listenCommunication(){ +void ParallelConnection::listenCommunication() { + constexpr size_t headerSize = 2 * sizeof(char) + 3 * sizeof(uint32_t); + //create basic buffer for receiving first part of messages - std::vector buffer; - //size of the header - buffer.resize(headerSize()); - - int result; + std::vector headerBuffer(headerSize); + std::vector messageBuffer; + + int nBytesRead = 0; //while we're still connected - while (_isConnected.load()){ - //receive the first parts of a message - result = receiveData(_clientSocket, buffer, headerSize(), 0); + while (_isConnected.load()) { + //receive the header data + nBytesRead = receiveData(_clientSocket, headerBuffer, headerSize, 0); //if enough data was received - if (result > 0){ - - //make sure that header matches this version of OpenSpace - if (buffer[0] == 'O' && //Open - buffer[1] == 'S' && //Space - buffer[2] == OPENSPACE_VERSION_MAJOR && // major version - buffer[3] == OPENSPACE_VERSION_MINOR // minor version - ) - { - //parse type - uint32_t type = (*(reinterpret_cast(&buffer[4]))); - - //and delegate decoding depending on type - delegateDecoding(type); - } - else{ - LERROR("Error: Client OpenSpace version " << OPENSPACE_VERSION_MAJOR << ", " << OPENSPACE_VERSION_MINOR << " does not match server version " << buffer[2] <<", " << buffer[3] << std::endl << "Message not decoded."); + if (nBytesRead <= 0) { + if (!_disconnect) { + LERROR("Error " << _ERRNO << " detected in connection when reading header, disconnecting!"); + signalDisconnect(); } + break; } - else{ - if (result == 0){ - //connection rejected - LERROR("Parallel connection rejected, disconnecting..."); - } - else{ - LERROR("Error " << _ERRNO << " detected in connection, disconnecting!"); - } - //signal that a disconnect should be performed + //make sure that header matches this version of OpenSpace + if (!(headerBuffer[0] == 'O' && headerBuffer[1] && 'S')) { + LERROR("Expected to read message header 'OS' from socket."); signalDisconnect(); break; } + + uint32_t *ptr = reinterpret_cast(&headerBuffer[2]); + + uint32_t protocolVersionIn = *(ptr++); + uint32_t messageTypeIn = *(ptr++); + uint32_t messageSizeIn = *(ptr++); + + if (protocolVersionIn != ProtocolVersion) { + LERROR("Protocol versions do not match. Server version: " << protocolVersionIn << ", Client version: " << ProtocolVersion); + signalDisconnect(); + break; + } + + size_t messageSize = messageSizeIn; + + // receive the payload + messageBuffer.resize(messageSize); + nBytesRead = receiveData(_clientSocket, messageBuffer, messageSize, 0); + + if (nBytesRead <= 0) { + if (!_disconnect) { + LERROR("Error " << _ERRNO << " detected in connection when reading message, disconnecting!"); + signalDisconnect(); + } + break; + } + + //and delegate decoding depending on type + queueInMessage(Message(static_cast(messageTypeIn), messageBuffer)); } } @@ -853,24 +874,17 @@ void ParallelConnection::setName(const std::string& name){ _name = name; } -bool ParallelConnection::isHost(){ - return _isHost.load(); -} - + void ParallelConnection::requestHostship(const std::string &password){ std::vector buffer; - buffer.reserve(headerSize()); - uint32_t passcode = hash(password); - - //write header - writeHeader(buffer, MessageTypes::HostshipRequest); - - //write passcode buffer.insert(buffer.end(), reinterpret_cast(&passcode), reinterpret_cast(&passcode) + sizeof(uint32_t)); - - //send message - queueMessage(buffer); + queueOutMessage(Message(MessageType::HostshipRequest, buffer)); +} + +void ParallelConnection::resignHostship() { + std::vector buffer; + queueOutMessage(Message(MessageType::HostshipResignation, buffer)); } void ParallelConnection::setPassword(const std::string& pwd){ @@ -878,7 +892,7 @@ void ParallelConnection::setPassword(const std::string& pwd){ } bool ParallelConnection::initNetworkAPI(){ - #if defined(__WIN32__) + #if defined(WIN32) WSADATA wsaData; WORD version; int error; @@ -903,203 +917,148 @@ bool ParallelConnection::initNetworkAPI(){ return true; } +void ParallelConnection::sendScript(const std::string& script) { + if (!isHost()) return; + + datamessagestructures::ScriptMessage sm; + sm._script = script; + + std::vector buffer; + sm.serialize(buffer); + + queueOutDataMessage(DataMessage(datamessagestructures::Type::ScriptData, buffer)); +} + void ParallelConnection::preSynchronization(){ - - //if we're the host - if(_isHost){ - //get current time parameters and create a keyframe - network::datamessagestructures::TimeKeyframe tf; - tf._dt = Time::ref().deltaTime(); - tf._paused = Time::ref().paused(); - tf._requiresTimeJump = Time::ref().timeJumped(); - tf._time = Time::ref().j2000Seconds(); - - //create a buffer and serialize message - std::vector tbuffer; - tf.serialize(tbuffer); - - //get the size of the keyframebuffer - uint16_t msglen = static_cast(tbuffer.size()); - - //the type of data message - uint16_t type = static_cast(network::datamessagestructures::TimeData); - - //create the full buffer - std::vector buffer; - buffer.reserve(headerSize() + sizeof(type) + sizeof(msglen) + msglen); - - //write header - writeHeader(buffer, MessageTypes::Data); - - //type of message - buffer.insert(buffer.end(), reinterpret_cast(&type), reinterpret_cast(&type) + sizeof(type)); - - //size of message - buffer.insert(buffer.end(), reinterpret_cast(&msglen), reinterpret_cast(&msglen) + sizeof(msglen)); - - //actual message - buffer.insert(buffer.end(), tbuffer.begin(), tbuffer.end()); - - //send message - queueMessage(buffer); + + std::unique_lock unqlock(_receiveBufferMutex); + while (!_receiveBuffer.empty()) { + Message& message = _receiveBuffer.front(); + handleMessage(message); + _receiveBuffer.pop_front(); } - else{ - //if we're not the host and we have a valid keyframe (one that hasnt been used before) - if(_latestTimeKeyframeValid.load()){ - - //lock mutex and retrieve parameters from latest keyframe - _timeKeyframeMutex.lock(); - - double dt = _latestTimeKeyframe._dt; - double time = _latestTimeKeyframe._time; - bool jump = _latestTimeKeyframe._requiresTimeJump; - bool paused = _latestTimeKeyframe._paused; - - _timeKeyframeMutex.unlock(); - - //this keyframe is now spent - _latestTimeKeyframeValid.store(false); - - //assign latest params - Time::ref().setDeltaTime(dt); - Time::ref().setTime(time, jump); - Time::ref().setPause(paused); - + + if (status() == Status::Host) { + if (Time::ref().timeJumped()) { + _timeJumped = true; } } } - -void ParallelConnection::scriptMessage(const std::string propIdentifier, const std::string propValue){ - - //save script as current state - { - //mutex protect - std::lock_guard lock(_currentStateMutex); - _currentState[propIdentifier] = propValue; - } - - //if we're connected and we're the host, also send the script - if(_isConnected.load() && _isHost.load()){ - //construct script - std::string script = scriptFromPropertyAndValue(propIdentifier, propValue); - - //create a script message - network::datamessagestructures::ScriptMessage sm; - sm._script = script; - sm._scriptlen = static_cast(script.length()); - - //create a buffer for the script - std::vector sbuffer; - - //fill the script buffer - sm.serialize(sbuffer); - - //get the size of the keyframebuffer - uint16_t msglen = static_cast(sbuffer.size()); - - //the type of message - uint16_t type = static_cast(network::datamessagestructures::ScriptData); - - //create the full buffer - std::vector buffer; - buffer.reserve(headerSize() + sizeof(type) + sizeof(msglen) + msglen); - - //write header - writeHeader(buffer, MessageTypes::Data); - - //type of message - buffer.insert(buffer.end(), reinterpret_cast(&type), reinterpret_cast(&type) + sizeof(type)); - - //size of message - buffer.insert(buffer.end(), reinterpret_cast(&msglen), reinterpret_cast(&msglen) + sizeof(msglen)); - - //actual message - buffer.insert(buffer.end(), sbuffer.begin(), sbuffer.end()); - - //send message - queueMessage(buffer); + +void ParallelConnection::setStatus(Status status) { + if (_status != status) { + _status = status; + _connectionEvent->publish("statusChanged"); } +} +ParallelConnection::Status ParallelConnection::status() { + return _status; } - -std::string ParallelConnection::scriptFromPropertyAndValue(const std::string property, const std::string value){ - //consruct script - std::string script = "openspace.setPropertyValue(\"" + property + "\"," + value + ");"; - return script; + +void ParallelConnection::setNConnections(size_t nConnections) { + if (_nConnections != nConnections) { + _nConnections = nConnections; + _connectionEvent->publish("nConnectionsChanged"); + } } - + +size_t ParallelConnection::nConnections() { + return _nConnections; +} + +bool ParallelConnection::isHost() { + return _status == Status::Host; +} + +void ParallelConnection::setHostName(const std::string& hostName) { + if (_hostName != hostName) { + _hostName = hostName; + _connectionEvent->publish("hostNameChanged"); + } +} + +const std::string& ParallelConnection::hostName() { + return _hostName; +} + +void ParallelConnection::sendCameraKeyframe() { + //create a keyframe with current position and orientation of camera + datamessagestructures::CameraKeyframe kf; + kf._position = OsEng.interactionHandler().camera()->positionVec3(); + kf._rotation = OsEng.interactionHandler().camera()->rotationQuaternion(); + + //timestamp as current runtime of OpenSpace instance + kf._timestamp = OsEng.runTime(); + + //create a buffer for the keyframe + std::vector buffer; + + //fill the keyframe buffer + kf.serialize(buffer); + + //send message + queueOutDataMessage(DataMessage(datamessagestructures::Type::CameraData, buffer)); +} + +void ParallelConnection::sendTimeKeyframe() { + //create a keyframe with current position and orientation of camera + datamessagestructures::TimeKeyframe kf; + + kf._dt = Time::ref().deltaTime(); + kf._paused = Time::ref().paused(); + kf._requiresTimeJump = _timeJumped; + kf._time = Time::ref().j2000Seconds(); + + //timestamp as current runtime of OpenSpace instance + kf._timestamp = OsEng.runTime(); + + //create a buffer for the keyframe + std::vector buffer; + + //fill the keyframe buffer + kf.serialize(buffer); + + //send message + queueOutDataMessage(DataMessage(datamessagestructures::Type::TimeData, buffer)); + _timeJumped = false; +} + + void ParallelConnection::broadcast(){ - + _timeJumped = true; //while we're still connected and we're the host - while (_isConnected.load() && _isHost.load()){ - - //create a keyframe with current position and orientation of camera - network::datamessagestructures::PositionKeyframe kf; - kf._position = OsEng.interactionHandler().camera()->position(); - kf._viewRotationQuat = glm::quat_cast(glm::mat4(OsEng.interactionHandler().camera()->viewRotationMatrix())); - - //timestamp as current runtime of OpenSpace instance - kf._timeStamp = OsEng.runTime(); - - //create a buffer for the keyframe - std::vector kfBuffer; - - //fill the keyframe buffer - kf.serialize(kfBuffer); - - //get the size of the keyframebuffer - uint16_t msglen = static_cast(kfBuffer.size()); - - //the type of message - uint16_t type = static_cast(network::datamessagestructures::PositionData); - - //create the full buffer - std::vector buffer; - buffer.reserve(headerSize() + sizeof(type) + sizeof(msglen) + msglen); - - //write header - writeHeader(buffer, MessageTypes::Data); - - //type of message - buffer.insert(buffer.end(), reinterpret_cast(&type), reinterpret_cast(&type) + sizeof(type)); - - //size of message - buffer.insert(buffer.end(), reinterpret_cast(&msglen), reinterpret_cast(&msglen) + sizeof(msglen)); - - //actual message - buffer.insert(buffer.end(), kfBuffer.begin(), kfBuffer.end()); - - //send message - queueMessage(buffer); + while (_isConnected && isHost()) { + sendCameraKeyframe(); + sendTimeKeyframe(); //100 ms sleep - send keyframes 10 times per second - std::this_thread::sleep_for(std::chrono::milliseconds(100)); + std::this_thread::sleep_for(std::chrono::milliseconds(static_cast(BroadcastIntervalMilliseconds))); } } - -void ParallelConnection::writeHeader(std::vector &buffer, uint32_t messageType){ - //make sure the buffer is large enough to hold at least the header - if(buffer.size() < headerSize()){ - buffer.reserve(headerSize()); - } - - //get the current running version of openspace - uint8_t versionMajor = static_cast(OPENSPACE_VERSION_MAJOR); - uint8_t versionMinor = static_cast(OPENSPACE_VERSION_MINOR); - - //insert header into buffer - buffer.insert(buffer.end(), 'O'); - buffer.insert(buffer.end(), 'S'); - buffer.insert(buffer.end(), versionMajor); - buffer.insert(buffer.end(), versionMinor); - buffer.insert(buffer.end(), reinterpret_cast(&messageType), reinterpret_cast(&messageType) + sizeof(messageType)); -} - -int ParallelConnection::headerSize(){ - //minor and major version (as uint8_t -> 1 byte) + two bytes for the chars 'O' and 'S' + 4 bytes for type of message - return 2 * sizeof(uint8_t) + 2 + sizeof(uint32_t); -} +uint32_t ParallelConnection::hash(const std::string &val) { + uint32_t hashVal = 0, i; + size_t len = val.length(); + + for (hashVal = i = 0; i < len; ++i) { + hashVal += val.c_str()[i]; + hashVal += (hashVal << 10); + hashVal ^= (hashVal >> 6); + } + + hashVal += (hashVal << 3); + hashVal ^= (hashVal >> 11); + hashVal += (hashVal << 15); + + return hashVal; +}; + + +std::shared_ptr> ParallelConnection::connectionEvent() { + return _connectionEvent; +} + scripting::LuaLibrary ParallelConnection::luaLibrary() { return { "parallel", @@ -1146,10 +1105,14 @@ scripting::LuaLibrary ParallelConnection::luaLibrary() { "string", "Request to be the host for this session" }, + { + "resignHostship", + &luascriptfunctions::resignHostship, + "", + "Resign hostship" + }, } }; } - -} // namespace network - + } // namespace openspace diff --git a/src/network/parallelconnection_lua.inl b/src/network/parallelconnection_lua.inl index 59ef2b3730..13b3b4bcf8 100644 --- a/src/network/parallelconnection_lua.inl +++ b/src/network/parallelconnection_lua.inl @@ -184,6 +184,17 @@ int requestHostship(lua_State* L) { return 0; } +int resignHostship(lua_State* L) { + + int nArguments = lua_gettop(L); + if (nArguments != 0) + return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments); + if (OsEng.isMaster()) { + OsEng.parallelConnection().resignHostship(); + } + return 0; +} + } // namespace luascriptfunctions } // namespace openspace diff --git a/src/performance/performancemanager.cpp b/src/performance/performancemanager.cpp index 6c0630f5e3..fae9acafbc 100644 --- a/src/performance/performancemanager.cpp +++ b/src/performance/performancemanager.cpp @@ -264,12 +264,26 @@ void PerformanceManager::storeScenePerformanceMeasurements( entry.renderTime[PerformanceLayout::NumberValues - 1] = r.renderTime / 1000.f; std::rotate( - std::begin(entry.updateEphemeris), - std::next(std::begin(entry.updateEphemeris)), - std::end(entry.updateEphemeris) + std::begin(entry.updateTranslation), + std::next(std::begin(entry.updateTranslation)), + std::end(entry.updateTranslation) ); - entry.updateEphemeris[PerformanceLayout::NumberValues - 1] = r.updateTimeEphemeris / 1000.f; - + entry.updateTranslation[PerformanceLayout::NumberValues - 1] = r.updateTimeTranslation / 1000.f; + + std::rotate( + std::begin(entry.updateRotation), + std::next(std::begin(entry.updateRotation)), + std::end(entry.updateRotation) + ); + entry.updateRotation[PerformanceLayout::NumberValues - 1] = r.updateTimeRotation / 1000.f; + + std::rotate( + std::begin(entry.updateScaling), + std::next(std::begin(entry.updateScaling)), + std::end(entry.updateScaling) + ); + entry.updateScaling[PerformanceLayout::NumberValues - 1] = r.updateTimeScaling / 1000.f; + std::rotate( std::begin(entry.updateRenderable), std::next(std::begin(entry.updateRenderable)), diff --git a/src/properties/matrix/dmat2property.cpp b/src/properties/matrix/dmat2property.cpp new file mode 100644 index 0000000000..5803a22efa --- /dev/null +++ b/src/properties/matrix/dmat2property.cpp @@ -0,0 +1,140 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_getfield(state, -1, std::to_string(number).c_str()); \ + if (lua_isnumber(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i][j] \ + = static_cast<__TYPE__::value_type>(lua_tonumber(state, -1)); \ + lua_pop(state, 1); \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_pushnumber(state, static_cast(value[i][j])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != \ + (ghoul::glm_rows<__TYPE__>::value * ghoul::glm_cols<__TYPE__>::value)) \ + { \ + success = false; \ + return result; \ + } \ + int number = 0; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + std::stringstream s(tokens[number]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else { \ + result[i][j] = v; \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = ""; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + outValue += std::to_string(inValue[i][j]) + ","; \ + } \ + outValue.pop_back(); \ + } \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(DMat2Property, glm::dmat2x2, glm::dmat2x2(0), + glm::dmat2x2( + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest() + ), + glm::dmat2x2( + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max() + ), + glm::dmat2x2( + 0.01, 0.01, + 0.01, 0.01 + ), + DEFAULT_FROM_LUA_LAMBDA(glm::dmat2x2), + DEFAULT_TO_LUA_LAMBDA(glm::dmat2x2), + DEFAULT_FROM_STRING_LAMBDA(glm::dmat2x2), + DEFAULT_TO_STRING_LAMBDA(glm::dmat2x2), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/matrix/dmat2x3property.cpp b/src/properties/matrix/dmat2x3property.cpp new file mode 100644 index 0000000000..d19e4c2ab5 --- /dev/null +++ b/src/properties/matrix/dmat2x3property.cpp @@ -0,0 +1,144 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_getfield(state, -1, std::to_string(number).c_str()); \ + if (lua_isnumber(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i][j] \ + = static_cast<__TYPE__::value_type>(lua_tonumber(state, -1)); \ + lua_pop(state, 1); \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_pushnumber(state, static_cast(value[i][j])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != \ + (ghoul::glm_rows<__TYPE__>::value * ghoul::glm_cols<__TYPE__>::value)) \ + { \ + success = false; \ + return result; \ + } \ + int number = 0; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + std::stringstream s(tokens[number]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else { \ + result[i][j] = v; \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = ""; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + outValue += std::to_string(inValue[i][j]) + ","; \ + } \ + outValue.pop_back(); \ + } \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(DMat2x3Property, glm::dmat2x3, glm::dmat2x3(0), + glm::dmat2x3( + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest() + ), + glm::dmat2x3( + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max() + ), + glm::dmat2x3( + 0.01, 0.01, 0.01, + 0.01, 0.01, 0.01 + ), + DEFAULT_FROM_LUA_LAMBDA(glm::dmat2x3), + DEFAULT_TO_LUA_LAMBDA(glm::dmat2x3), + DEFAULT_FROM_STRING_LAMBDA(glm::dmat2x3), + DEFAULT_TO_STRING_LAMBDA(glm::dmat2x3), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/matrix/dmat2x4property.cpp b/src/properties/matrix/dmat2x4property.cpp new file mode 100644 index 0000000000..c98c3c6457 --- /dev/null +++ b/src/properties/matrix/dmat2x4property.cpp @@ -0,0 +1,148 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_getfield(state, -1, std::to_string(number).c_str()); \ + if (lua_isnumber(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i][j] \ + = static_cast<__TYPE__::value_type>(lua_tonumber(state, -1)); \ + lua_pop(state, 1); \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_pushnumber(state, static_cast(value[i][j])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != \ + (ghoul::glm_rows<__TYPE__>::value * ghoul::glm_cols<__TYPE__>::value)) \ + { \ + success = false; \ + return result; \ + } \ + int number = 0; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + std::stringstream s(tokens[number]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else { \ + result[i][j] = v; \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = ""; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + outValue += std::to_string(inValue[i][j]) + ","; \ + } \ + outValue.pop_back(); \ + } \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(DMat2x4Property, glm::dmat2x4, glm::dmat2x4(0), + glm::dmat2x4( + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest() + ), + glm::dmat2x4( + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max() + ), + glm::dmat2x4( + 0.01, 0.01, 0.01, 0.01, + 0.01, 0.01, 0.01, 0.01 + ), + DEFAULT_FROM_LUA_LAMBDA(glm::dmat2x4), + DEFAULT_TO_LUA_LAMBDA(glm::dmat2x4), + DEFAULT_FROM_STRING_LAMBDA(glm::dmat2x4), + DEFAULT_TO_STRING_LAMBDA(glm::dmat2x4), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/matrix/dmat3property.cpp b/src/properties/matrix/dmat3property.cpp new file mode 100644 index 0000000000..5b5bed6e59 --- /dev/null +++ b/src/properties/matrix/dmat3property.cpp @@ -0,0 +1,151 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_getfield(state, -1, std::to_string(number).c_str()); \ + if (lua_isnumber(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i][j] \ + = static_cast<__TYPE__::value_type>(lua_tonumber(state, -1)); \ + lua_pop(state, 1); \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_pushnumber(state, static_cast(value[i][j])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != \ + (ghoul::glm_rows<__TYPE__>::value * ghoul::glm_cols<__TYPE__>::value)) \ + { \ + success = false; \ + return result; \ + } \ + int number = 0; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + std::stringstream s(tokens[number]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else { \ + result[i][j] = v; \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = ""; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + outValue += std::to_string(inValue[i][j]) + ","; \ + } \ + outValue.pop_back(); \ + } \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(DMat3Property, glm::dmat3x3, glm::dmat3x3(0), + glm::dmat3x3( + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest() + ), + glm::dmat3x3( + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max() + ), + glm::dmat3x3( + 0.01, 0.01, 0.01, + 0.01, 0.01, 0.01, + 0.01, 0.01, 0.01 + ), + DEFAULT_FROM_LUA_LAMBDA(glm::dmat3x3), + DEFAULT_TO_LUA_LAMBDA(glm::dmat3x3), + DEFAULT_FROM_STRING_LAMBDA(glm::dmat3x3), + DEFAULT_TO_STRING_LAMBDA(glm::dmat3x3), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/matrix/dmat3x2property.cpp b/src/properties/matrix/dmat3x2property.cpp new file mode 100644 index 0000000000..1bd04eb146 --- /dev/null +++ b/src/properties/matrix/dmat3x2property.cpp @@ -0,0 +1,144 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_getfield(state, -1, std::to_string(number).c_str()); \ + if (lua_isnumber(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i][j] \ + = static_cast<__TYPE__::value_type>(lua_tonumber(state, -1)); \ + lua_pop(state, 1); \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_pushnumber(state, static_cast(value[i][j])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != \ + (ghoul::glm_rows<__TYPE__>::value * ghoul::glm_cols<__TYPE__>::value)) \ + { \ + success = false; \ + return result; \ + } \ + int number = 0; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + std::stringstream s(tokens[number]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else { \ + result[i][j] = v; \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = ""; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + outValue += std::to_string(inValue[i][j]) + ","; \ + } \ + outValue.pop_back(); \ + } \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(DMat3x2Property, glm::dmat3x2, glm::dmat3x2(0), + glm::dmat3x2( + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest() + ), + glm::dmat3x2( + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max() + ), + glm::dmat3x2( + 0.01, 0.01, 0.01, + 0.01, 0.01, 0.01 + ), + DEFAULT_FROM_LUA_LAMBDA(glm::dmat3x2), + DEFAULT_TO_LUA_LAMBDA(glm::dmat3x2), + DEFAULT_FROM_STRING_LAMBDA(glm::dmat3x2), + DEFAULT_TO_STRING_LAMBDA(glm::dmat3x2), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/matrix/dmat3x4property.cpp b/src/properties/matrix/dmat3x4property.cpp new file mode 100644 index 0000000000..99dfe5283a --- /dev/null +++ b/src/properties/matrix/dmat3x4property.cpp @@ -0,0 +1,157 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_getfield(state, -1, std::to_string(number).c_str()); \ + if (lua_isnumber(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i][j] \ + = static_cast<__TYPE__::value_type>(lua_tonumber(state, -1)); \ + lua_pop(state, 1); \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_pushnumber(state, static_cast(value[i][j])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != \ + (ghoul::glm_rows<__TYPE__>::value * ghoul::glm_cols<__TYPE__>::value)) \ + { \ + success = false; \ + return result; \ + } \ + int number = 0; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + std::stringstream s(tokens[number]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else { \ + result[i][j] = v; \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = ""; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + outValue += std::to_string(inValue[i][j]) + ","; \ + } \ + outValue.pop_back(); \ + } \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(DMat3x4Property, glm::dmat3x4, glm::dmat3x4(0), + glm::dmat3x4( + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest() + ), + glm::dmat3x4( + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max() + ), + glm::dmat3x4( + 0.01, 0.01, 0.01, 0.01, + 0.01, 0.01, 0.01, 0.01, + 0.01, 0.01, 0.01, 0.01 + ), + DEFAULT_FROM_LUA_LAMBDA(glm::dmat3x4), + DEFAULT_TO_LUA_LAMBDA(glm::dmat3x4), + DEFAULT_FROM_STRING_LAMBDA(glm::dmat3x4), + DEFAULT_TO_STRING_LAMBDA(glm::dmat3x4), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/matrix/dmat4property.cpp b/src/properties/matrix/dmat4property.cpp new file mode 100644 index 0000000000..2d9c24003c --- /dev/null +++ b/src/properties/matrix/dmat4property.cpp @@ -0,0 +1,166 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_getfield(state, -1, std::to_string(number).c_str()); \ + if (lua_isnumber(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i][j] \ + = static_cast<__TYPE__::value_type>(lua_tonumber(state, -1)); \ + lua_pop(state, 1); \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_pushnumber(state, static_cast(value[i][j])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != \ + (ghoul::glm_rows<__TYPE__>::value * ghoul::glm_cols<__TYPE__>::value)) \ + { \ + success = false; \ + return result; \ + } \ + int number = 0; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + std::stringstream s(tokens[number]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else { \ + result[i][j] = v; \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = ""; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + outValue += std::to_string(inValue[i][j]) + ","; \ + } \ + outValue.pop_back(); \ + } \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(DMat4Property, glm::dmat4x4, glm::dmat4x4(0), + glm::dmat4x4( + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest() + ), + glm::dmat4x4( + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max() + ), + glm::dmat4x4( + 0.01, 0.01, 0.01, 0.01, + 0.01, 0.01, 0.01, 0.01, + 0.01, 0.01, 0.01, 0.01, + 0.01, 0.01, 0.01, 0.01 + ), + DEFAULT_FROM_LUA_LAMBDA(glm::dmat4x4), + DEFAULT_TO_LUA_LAMBDA(glm::dmat4x4), + DEFAULT_FROM_STRING_LAMBDA(glm::dmat4x4), + DEFAULT_TO_STRING_LAMBDA(glm::dmat4x4), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/matrix/dmat4x2property.cpp b/src/properties/matrix/dmat4x2property.cpp new file mode 100644 index 0000000000..b4b132d47b --- /dev/null +++ b/src/properties/matrix/dmat4x2property.cpp @@ -0,0 +1,148 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_getfield(state, -1, std::to_string(number).c_str()); \ + if (lua_isnumber(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i][j] \ + = static_cast<__TYPE__::value_type>(lua_tonumber(state, -1)); \ + lua_pop(state, 1); \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_pushnumber(state, static_cast(value[i][j])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != \ + (ghoul::glm_rows<__TYPE__>::value * ghoul::glm_cols<__TYPE__>::value)) \ + { \ + success = false; \ + return result; \ + } \ + int number = 0; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + std::stringstream s(tokens[number]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else { \ + result[i][j] = v; \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = ""; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + outValue += std::to_string(inValue[i][j]) + ","; \ + } \ + outValue.pop_back(); \ + } \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(DMat4x2Property, glm::dmat4x2, glm::dmat4x2(0), + glm::dmat4x2( + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest() + ), + glm::dmat4x2( + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max() + ), + glm::dmat4x2( + 0.01, 0.01, 0.01, 0.01, + 0.01, 0.01, 0.01, 0.01 + ), + DEFAULT_FROM_LUA_LAMBDA(glm::dmat4x2), + DEFAULT_TO_LUA_LAMBDA(glm::dmat4x2), + DEFAULT_FROM_STRING_LAMBDA(glm::dmat4x2), + DEFAULT_TO_STRING_LAMBDA(glm::dmat4x2), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/matrix/dmat4x3property.cpp b/src/properties/matrix/dmat4x3property.cpp new file mode 100644 index 0000000000..306e259976 --- /dev/null +++ b/src/properties/matrix/dmat4x3property.cpp @@ -0,0 +1,157 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_getfield(state, -1, std::to_string(number).c_str()); \ + if (lua_isnumber(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i][j] \ + = static_cast<__TYPE__::value_type>(lua_tonumber(state, -1)); \ + lua_pop(state, 1); \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_pushnumber(state, static_cast(value[i][j])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != \ + (ghoul::glm_rows<__TYPE__>::value * ghoul::glm_cols<__TYPE__>::value)) \ + { \ + success = false; \ + return result; \ + } \ + int number = 0; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + std::stringstream s(tokens[number]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else { \ + result[i][j] = v; \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = ""; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + outValue += std::to_string(inValue[i][j]) + ","; \ + } \ + outValue.pop_back(); \ + } \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(DMat4x3Property, glm::dmat4x3, glm::dmat4x3(0), + glm::dmat4x3( + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest() + ), + glm::dmat4x3( + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max() + ), + glm::dmat4x3( + 0.01, 0.01, 0.01, 0.01, + 0.01, 0.01, 0.01, 0.01, + 0.01, 0.01, 0.01, 0.01 + ), + DEFAULT_FROM_LUA_LAMBDA(glm::dmat4x3), + DEFAULT_TO_LUA_LAMBDA(glm::dmat4x3), + DEFAULT_FROM_STRING_LAMBDA(glm::dmat4x3), + DEFAULT_TO_STRING_LAMBDA(glm::dmat4x3), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/matrix/mat2property.cpp b/src/properties/matrix/mat2property.cpp new file mode 100644 index 0000000000..f2736c6a9e --- /dev/null +++ b/src/properties/matrix/mat2property.cpp @@ -0,0 +1,140 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_getfield(state, -1, std::to_string(number).c_str()); \ + if (lua_isnumber(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i][j] \ + = static_cast<__TYPE__::value_type>(lua_tonumber(state, -1)); \ + lua_pop(state, 1); \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_pushnumber(state, static_cast(value[i][j])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != \ + (ghoul::glm_rows<__TYPE__>::value * ghoul::glm_cols<__TYPE__>::value)) \ + { \ + success = false; \ + return result; \ + } \ + int number = 0; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + std::stringstream s(tokens[number]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else { \ + result[i][j] = v; \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = ""; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + outValue += std::to_string(inValue[i][j]) + ","; \ + } \ + outValue.pop_back(); \ + } \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(Mat2Property, glm::mat2x2, glm::mat2x2(0), + glm::mat2x2( + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest() + ), + glm::mat2x2( + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max() + ), + glm::mat2x2( + 0.01f, 0.01f, + 0.01f, 0.01f + ), + DEFAULT_FROM_LUA_LAMBDA(glm::mat2x2), + DEFAULT_TO_LUA_LAMBDA(glm::mat2x2), + DEFAULT_FROM_STRING_LAMBDA(glm::mat2x2), + DEFAULT_TO_STRING_LAMBDA(glm::mat2x2), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/matrix/mat2x3property.cpp b/src/properties/matrix/mat2x3property.cpp new file mode 100644 index 0000000000..cf42b7261a --- /dev/null +++ b/src/properties/matrix/mat2x3property.cpp @@ -0,0 +1,144 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_getfield(state, -1, std::to_string(number).c_str()); \ + if (lua_isnumber(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i][j] \ + = static_cast<__TYPE__::value_type>(lua_tonumber(state, -1)); \ + lua_pop(state, 1); \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_pushnumber(state, static_cast(value[i][j])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != \ + (ghoul::glm_rows<__TYPE__>::value * ghoul::glm_cols<__TYPE__>::value)) \ + { \ + success = false; \ + return result; \ + } \ + int number = 0; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + std::stringstream s(tokens[number]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else { \ + result[i][j] = v; \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = ""; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + outValue += std::to_string(inValue[i][j]) + ","; \ + } \ + outValue.pop_back(); \ + } \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(Mat2x3Property, glm::mat2x3, glm::mat2x3(0), + glm::mat2x3( + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest() + ), + glm::mat2x3( + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max() + ), + glm::mat2x3( + 0.01f, 0.01f, 0.01f, + 0.01f, 0.01f, 0.01f + ), + DEFAULT_FROM_LUA_LAMBDA(glm::mat2x3), + DEFAULT_TO_LUA_LAMBDA(glm::mat2x3), + DEFAULT_FROM_STRING_LAMBDA(glm::mat2x3), + DEFAULT_TO_STRING_LAMBDA(glm::mat2x3), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/matrix/mat2x4property.cpp b/src/properties/matrix/mat2x4property.cpp new file mode 100644 index 0000000000..fac1405f6a --- /dev/null +++ b/src/properties/matrix/mat2x4property.cpp @@ -0,0 +1,148 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_getfield(state, -1, std::to_string(number).c_str()); \ + if (lua_isnumber(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i][j] \ + = static_cast<__TYPE__::value_type>(lua_tonumber(state, -1)); \ + lua_pop(state, 1); \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_pushnumber(state, static_cast(value[i][j])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != \ + (ghoul::glm_rows<__TYPE__>::value * ghoul::glm_cols<__TYPE__>::value)) \ + { \ + success = false; \ + return result; \ + } \ + int number = 0; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + std::stringstream s(tokens[number]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else { \ + result[i][j] = v; \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = ""; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + outValue += std::to_string(inValue[i][j]) + ","; \ + } \ + outValue.pop_back(); \ + } \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(Mat2x4Property, glm::mat2x4, glm::mat2x4(0), + glm::mat2x4( + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest() + ), + glm::mat2x4( + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max() + ), + glm::mat2x4( + 0.01f, 0.01f, 0.01f, 0.01f, + 0.01f, 0.01f, 0.01f, 0.01f + ), + DEFAULT_FROM_LUA_LAMBDA(glm::mat2x4), + DEFAULT_TO_LUA_LAMBDA(glm::mat2x4), + DEFAULT_FROM_STRING_LAMBDA(glm::mat2x4), + DEFAULT_TO_STRING_LAMBDA(glm::mat2x4), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/matrix/mat3property.cpp b/src/properties/matrix/mat3property.cpp new file mode 100644 index 0000000000..fb8f473434 --- /dev/null +++ b/src/properties/matrix/mat3property.cpp @@ -0,0 +1,151 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_getfield(state, -1, std::to_string(number).c_str()); \ + if (lua_isnumber(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i][j] \ + = static_cast<__TYPE__::value_type>(lua_tonumber(state, -1)); \ + lua_pop(state, 1); \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_pushnumber(state, static_cast(value[i][j])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != \ + (ghoul::glm_rows<__TYPE__>::value * ghoul::glm_cols<__TYPE__>::value)) \ + { \ + success = false; \ + return result; \ + } \ + int number = 0; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + std::stringstream s(tokens[number]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else { \ + result[i][j] = v; \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = ""; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + outValue += std::to_string(inValue[i][j]) + ","; \ + } \ + outValue.pop_back(); \ + } \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(Mat3Property, glm::mat3x3, glm::mat3x3(0), + glm::mat3x3( + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest() + ), + glm::mat3x3( + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max() + ), + glm::mat3x3( + 0.01f, 0.01f, 0.01f, + 0.01f, 0.01f, 0.01f, + 0.01f, 0.01f, 0.01f + ), + DEFAULT_FROM_LUA_LAMBDA(glm::mat3x3), + DEFAULT_TO_LUA_LAMBDA(glm::mat3x3), + DEFAULT_FROM_STRING_LAMBDA(glm::mat3x3), + DEFAULT_TO_STRING_LAMBDA(glm::mat3x3), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/matrix/mat3x2property.cpp b/src/properties/matrix/mat3x2property.cpp new file mode 100644 index 0000000000..e230b7904d --- /dev/null +++ b/src/properties/matrix/mat3x2property.cpp @@ -0,0 +1,144 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_getfield(state, -1, std::to_string(number).c_str()); \ + if (lua_isnumber(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i][j] \ + = static_cast<__TYPE__::value_type>(lua_tonumber(state, -1)); \ + lua_pop(state, 1); \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_pushnumber(state, static_cast(value[i][j])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != \ + (ghoul::glm_rows<__TYPE__>::value * ghoul::glm_cols<__TYPE__>::value)) \ + { \ + success = false; \ + return result; \ + } \ + int number = 0; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + std::stringstream s(tokens[number]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else { \ + result[i][j] = v; \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = ""; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + outValue += std::to_string(inValue[i][j]) + ","; \ + } \ + outValue.pop_back(); \ + } \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(Mat3x2Property, glm::mat3x2, glm::mat3x2(0), + glm::mat3x2( + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest() + ), + glm::mat3x2( + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max() + ), + glm::mat3x2( + 0.01f, 0.01f, 0.01f, + 0.01f, 0.01f, 0.01f + ), + DEFAULT_FROM_LUA_LAMBDA(glm::mat3x2), + DEFAULT_TO_LUA_LAMBDA(glm::mat3x2), + DEFAULT_FROM_STRING_LAMBDA(glm::mat3x2), + DEFAULT_TO_STRING_LAMBDA(glm::mat3x2), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/matrix/mat3x4property.cpp b/src/properties/matrix/mat3x4property.cpp new file mode 100644 index 0000000000..f17c44d825 --- /dev/null +++ b/src/properties/matrix/mat3x4property.cpp @@ -0,0 +1,157 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_getfield(state, -1, std::to_string(number).c_str()); \ + if (lua_isnumber(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i][j] \ + = static_cast<__TYPE__::value_type>(lua_tonumber(state, -1)); \ + lua_pop(state, 1); \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_pushnumber(state, static_cast(value[i][j])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != \ + (ghoul::glm_rows<__TYPE__>::value * ghoul::glm_cols<__TYPE__>::value)) \ + { \ + success = false; \ + return result; \ + } \ + int number = 0; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + std::stringstream s(tokens[number]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else { \ + result[i][j] = v; \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = ""; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + outValue += std::to_string(inValue[i][j]) + ","; \ + } \ + outValue.pop_back(); \ + } \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(Mat3x4Property, glm::mat3x4, glm::mat3x4(0), + glm::mat3x4( + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest() + ), + glm::mat3x4( + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max() + ), + glm::mat3x4( + 0.01f, 0.01f, 0.01f, 0.01f, + 0.01f, 0.01f, 0.01f, 0.01f, + 0.01f, 0.01f, 0.01f, 0.01f + ), + DEFAULT_FROM_LUA_LAMBDA(glm::mat3x4), + DEFAULT_TO_LUA_LAMBDA(glm::mat3x4), + DEFAULT_FROM_STRING_LAMBDA(glm::mat3x4), + DEFAULT_TO_STRING_LAMBDA(glm::mat3x4), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/matrix/mat4property.cpp b/src/properties/matrix/mat4property.cpp new file mode 100644 index 0000000000..1d7ff0b614 --- /dev/null +++ b/src/properties/matrix/mat4property.cpp @@ -0,0 +1,166 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_getfield(state, -1, std::to_string(number).c_str()); \ + if (lua_isnumber(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i][j] \ + = static_cast<__TYPE__::value_type>(lua_tonumber(state, -1)); \ + lua_pop(state, 1); \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_pushnumber(state, static_cast(value[i][j])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != \ + (ghoul::glm_rows<__TYPE__>::value * ghoul::glm_cols<__TYPE__>::value)) \ + { \ + success = false; \ + return result; \ + } \ + int number = 0; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + std::stringstream s(tokens[number]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else { \ + result[i][j] = v; \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = ""; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + outValue += std::to_string(inValue[i][j]) + ","; \ + } \ + outValue.pop_back(); \ + } \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(Mat4Property, glm::mat4x4, glm::mat4x4(0), + glm::mat4x4( + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest() + ), + glm::mat4x4( + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max() + ), + glm::mat4x4( + 0.01f, 0.01f, 0.01f, 0.01f, + 0.01f, 0.01f, 0.01f, 0.01f, + 0.01f, 0.01f, 0.01f, 0.01f, + 0.01f, 0.01f, 0.01f, 0.01f + ), + DEFAULT_FROM_LUA_LAMBDA(glm::mat4x4), + DEFAULT_TO_LUA_LAMBDA(glm::mat4x4), + DEFAULT_FROM_STRING_LAMBDA(glm::mat4x4), + DEFAULT_TO_STRING_LAMBDA(glm::mat4x4), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/matrix/mat4x2property.cpp b/src/properties/matrix/mat4x2property.cpp new file mode 100644 index 0000000000..ca90cf41f6 --- /dev/null +++ b/src/properties/matrix/mat4x2property.cpp @@ -0,0 +1,148 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_getfield(state, -1, std::to_string(number).c_str()); \ + if (lua_isnumber(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i][j] \ + = static_cast<__TYPE__::value_type>(lua_tonumber(state, -1)); \ + lua_pop(state, 1); \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_pushnumber(state, static_cast(value[i][j])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != \ + (ghoul::glm_rows<__TYPE__>::value * ghoul::glm_cols<__TYPE__>::value)) \ + { \ + success = false; \ + return result; \ + } \ + int number = 0; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + std::stringstream s(tokens[number]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else { \ + result[i][j] = v; \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = ""; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + outValue += std::to_string(inValue[i][j]) + ","; \ + } \ + outValue.pop_back(); \ + } \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(Mat4x2Property, glm::mat4x2, glm::mat4x2(0), + glm::mat4x2( + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest() + ), + glm::mat4x2( + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max() + ), + glm::mat4x2( + 0.01f, 0.01f, 0.01f, 0.01f, + 0.01f, 0.01f, 0.01f, 0.01f + ), + DEFAULT_FROM_LUA_LAMBDA(glm::mat4x2), + DEFAULT_TO_LUA_LAMBDA(glm::mat4x2), + DEFAULT_FROM_STRING_LAMBDA(glm::mat4x2), + DEFAULT_TO_STRING_LAMBDA(glm::mat4x2), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/matrix/mat4x3property.cpp b/src/properties/matrix/mat4x3property.cpp new file mode 100644 index 0000000000..bdc1fecb21 --- /dev/null +++ b/src/properties/matrix/mat4x3property.cpp @@ -0,0 +1,157 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_getfield(state, -1, std::to_string(number).c_str()); \ + if (lua_isnumber(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i][j] \ + = static_cast<__TYPE__::value_type>(lua_tonumber(state, -1)); \ + lua_pop(state, 1); \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State* state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + lua_pushnumber(state, static_cast(value[i][j])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != \ + (ghoul::glm_rows<__TYPE__>::value * ghoul::glm_cols<__TYPE__>::value)) \ + { \ + success = false; \ + return result; \ + } \ + int number = 0; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + std::stringstream s(tokens[number]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else { \ + result[i][j] = v; \ + ++number; \ + } \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = ""; \ + for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ + for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ + outValue += std::to_string(inValue[i][j]) + ","; \ + } \ + outValue.pop_back(); \ + } \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(Mat4x3Property, glm::mat4x3, glm::mat4x3(0), + glm::mat4x3( + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest(), + numeric_limits::lowest() + ), + glm::mat4x3( + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max(), + numeric_limits::max() + ), + glm::mat4x3( + 0.01f, 0.01f, 0.01f, 0.01f, + 0.01f, 0.01f, 0.01f, 0.01f, + 0.01f, 0.01f, 0.01f, 0.01f + ), + DEFAULT_FROM_LUA_LAMBDA(glm::mat4x3), + DEFAULT_TO_LUA_LAMBDA(glm::mat4x3), + DEFAULT_FROM_STRING_LAMBDA(glm::mat4x3), + DEFAULT_TO_STRING_LAMBDA(glm::mat4x3), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/matrixproperty.cpp b/src/properties/matrixproperty.cpp deleted file mode 100644 index ca33757247..0000000000 --- a/src/properties/matrixproperty.cpp +++ /dev/null @@ -1,721 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#include - -#include - -#include -#include -#include - -using std::numeric_limits; - -namespace openspace { -namespace properties { - -#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__) \ - [](lua_State* state, bool& success) -> __TYPE__ { \ - __TYPE__ result; \ - int number = 1; \ - for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ - for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ - lua_getfield(state, -1, std::to_string(number).c_str()); \ - if (lua_isnumber(state, -1) != 1) { \ - success = false; \ - return __TYPE__(0); \ - } else { \ - result[i][j] \ - = static_cast<__TYPE__::value_type>(lua_tonumber(state, -1)); \ - lua_pop(state, 1); \ - ++number; \ - } \ - } \ - } \ - success = true; \ - return result; \ - } - -#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ - [](lua_State* state, __TYPE__ value) -> bool { \ - lua_newtable(state); \ - int number = 1; \ - for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ - for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ - lua_pushnumber(state, static_cast(value[i][j])); \ - lua_setfield(state, -2, std::to_string(number).c_str()); \ - ++number; \ - } \ - } \ - return true; \ - } - -#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ - [](std::string value, bool& success) -> __TYPE__ { \ - __TYPE__ result; \ - std::vector tokens = ghoul::tokenizeString(value, ','); \ - if (tokens.size() != \ - (ghoul::glm_rows<__TYPE__>::value * ghoul::glm_cols<__TYPE__>::value)) \ - { \ - success = false; \ - return result; \ - } \ - int number = 0; \ - for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ - for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ - std::stringstream s(tokens[number]); \ - __TYPE__::value_type v; \ - s >> v; \ - if (s.fail()) { \ - success = false; \ - return result; \ - } \ - else { \ - result[i][j] = v; \ - ++number; \ - } \ - } \ - } \ - success = true; \ - return result; \ - } - -#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ - [](std::string& outValue, __TYPE__ inValue) -> bool { \ - outValue = ""; \ - for (glm::length_t i = 0; i < ghoul::glm_cols<__TYPE__>::value; ++i) { \ - for (glm::length_t j = 0; j < ghoul::glm_rows<__TYPE__>::value; ++j) { \ - outValue += std::to_string(inValue[i][j]) + ","; \ - } \ - outValue.pop_back(); \ - } \ - return true; \ - } - -REGISTER_NUMERICALPROPERTY_SOURCE(Mat2Property, glm::mat2x2, glm::mat2x2(0), - glm::mat2x2( - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest() - ), - glm::mat2x2( - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max() - ), - glm::mat2x2( - 0.01f, 0.01f, - 0.01f, 0.01f - ), - DEFAULT_FROM_LUA_LAMBDA(glm::mat2x2), - DEFAULT_TO_LUA_LAMBDA(glm::mat2x2), - DEFAULT_FROM_STRING_LAMBDA(glm::mat2x2), - DEFAULT_TO_STRING_LAMBDA(glm::mat2x2), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(Mat2x3Property, glm::mat2x3, glm::mat2x3(0), - glm::mat2x3( - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest() - ), - glm::mat2x3( - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max() - ), - glm::mat2x3( - 0.01f, 0.01f, 0.01f, - 0.01f, 0.01f, 0.01f - ), - DEFAULT_FROM_LUA_LAMBDA(glm::mat2x3), - DEFAULT_TO_LUA_LAMBDA(glm::mat2x3), - DEFAULT_FROM_STRING_LAMBDA(glm::mat2x3), - DEFAULT_TO_STRING_LAMBDA(glm::mat2x3), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(Mat2x4Property, glm::mat2x4, glm::mat2x4(0), - glm::mat2x4( - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest() - ), - glm::mat2x4( - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max() - ), - glm::mat2x4( - 0.01f, 0.01f, 0.01f, 0.01f, - 0.01f, 0.01f, 0.01f, 0.01f - ), - DEFAULT_FROM_LUA_LAMBDA(glm::mat2x4), - DEFAULT_TO_LUA_LAMBDA(glm::mat2x4), - DEFAULT_FROM_STRING_LAMBDA(glm::mat2x4), - DEFAULT_TO_STRING_LAMBDA(glm::mat2x4), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(Mat3x2Property, glm::mat3x2, glm::mat3x2(0), - glm::mat3x2( - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest() - ), - glm::mat3x2( - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max() - ), - glm::mat3x2( - 0.01f, 0.01f, 0.01f, - 0.01f, 0.01f, 0.01f - ), - DEFAULT_FROM_LUA_LAMBDA(glm::mat3x2), - DEFAULT_TO_LUA_LAMBDA(glm::mat3x2), - DEFAULT_FROM_STRING_LAMBDA(glm::mat3x2), - DEFAULT_TO_STRING_LAMBDA(glm::mat3x2), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(Mat3Property, glm::mat3x3, glm::mat3x3(0), - glm::mat3x3( - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest() - ), - glm::mat3x3( - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max() - ), - glm::mat3x3( - 0.01f, 0.01f, 0.01f, - 0.01f, 0.01f, 0.01f, - 0.01f, 0.01f, 0.01f - ), - DEFAULT_FROM_LUA_LAMBDA(glm::mat3x3), - DEFAULT_TO_LUA_LAMBDA(glm::mat3x3), - DEFAULT_FROM_STRING_LAMBDA(glm::mat3x3), - DEFAULT_TO_STRING_LAMBDA(glm::mat3x3), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(Mat3x4Property, glm::mat3x4, glm::mat3x4(0), - glm::mat3x4( - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest() - ), - glm::mat3x4( - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max() - ), - glm::mat3x4( - 0.01f, 0.01f, 0.01f, 0.01f, - 0.01f, 0.01f, 0.01f, 0.01f, - 0.01f, 0.01f, 0.01f, 0.01f - ), - DEFAULT_FROM_LUA_LAMBDA(glm::mat3x4), - DEFAULT_TO_LUA_LAMBDA(glm::mat3x4), - DEFAULT_FROM_STRING_LAMBDA(glm::mat3x4), - DEFAULT_TO_STRING_LAMBDA(glm::mat3x4), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(Mat4x2Property, glm::mat4x2, glm::mat4x2(0), - glm::mat4x2( - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest() - ), - glm::mat4x2( - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max() - ), - glm::mat4x2( - 0.01f, 0.01f, 0.01f, 0.01f, - 0.01f, 0.01f, 0.01f, 0.01f - ), - DEFAULT_FROM_LUA_LAMBDA(glm::mat4x2), - DEFAULT_TO_LUA_LAMBDA(glm::mat4x2), - DEFAULT_FROM_STRING_LAMBDA(glm::mat4x2), - DEFAULT_TO_STRING_LAMBDA(glm::mat4x2), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(Mat4x3Property, glm::mat4x3, glm::mat4x3(0), - glm::mat4x3( - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest() - ), - glm::mat4x3( - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max() - ), - glm::mat4x3( - 0.01f, 0.01f, 0.01f, 0.01f, - 0.01f, 0.01f, 0.01f, 0.01f, - 0.01f, 0.01f, 0.01f, 0.01f - ), - DEFAULT_FROM_LUA_LAMBDA(glm::mat4x3), - DEFAULT_TO_LUA_LAMBDA(glm::mat4x3), - DEFAULT_FROM_STRING_LAMBDA(glm::mat4x3), - DEFAULT_TO_STRING_LAMBDA(glm::mat4x3), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(Mat4Property, glm::mat4x4, glm::mat4x4(0), - glm::mat4x4( - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest() - ), - glm::mat4x4( - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max() - ), - glm::mat4x4( - 0.01f, 0.01f, 0.01f, 0.01f, - 0.01f, 0.01f, 0.01f, 0.01f, - 0.01f, 0.01f, 0.01f, 0.01f, - 0.01f, 0.01f, 0.01f, 0.01f - ), - DEFAULT_FROM_LUA_LAMBDA(glm::mat4x4), - DEFAULT_TO_LUA_LAMBDA(glm::mat4x4), - DEFAULT_FROM_STRING_LAMBDA(glm::mat4x4), - DEFAULT_TO_STRING_LAMBDA(glm::mat4x4), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(DMat2Property, glm::dmat2x2, glm::dmat2x2(0), - glm::dmat2x2( - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest() - ), - glm::dmat2x2( - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max() - ), - glm::dmat2x2( - 0.01, 0.01, - 0.01, 0.01 - ), - DEFAULT_FROM_LUA_LAMBDA(glm::dmat2x2), - DEFAULT_TO_LUA_LAMBDA(glm::dmat2x2), - DEFAULT_FROM_STRING_LAMBDA(glm::dmat2x2), - DEFAULT_TO_STRING_LAMBDA(glm::dmat2x2), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(DMat2x3Property, glm::dmat2x3, glm::dmat2x3(0), - glm::dmat2x3( - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest() - ), - glm::dmat2x3( - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max() - ), - glm::dmat2x3( - 0.01, 0.01, 0.01, - 0.01, 0.01, 0.01 - ), - DEFAULT_FROM_LUA_LAMBDA(glm::dmat2x3), - DEFAULT_TO_LUA_LAMBDA(glm::dmat2x3), - DEFAULT_FROM_STRING_LAMBDA(glm::dmat2x3), - DEFAULT_TO_STRING_LAMBDA(glm::dmat2x3), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(DMat2x4Property, glm::dmat2x4, glm::dmat2x4(0), - glm::dmat2x4( - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest() - ), - glm::dmat2x4( - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max() - ), - glm::dmat2x4( - 0.01, 0.01, 0.01, 0.01, - 0.01, 0.01, 0.01, 0.01 - ), - DEFAULT_FROM_LUA_LAMBDA(glm::dmat2x4), - DEFAULT_TO_LUA_LAMBDA(glm::dmat2x4), - DEFAULT_FROM_STRING_LAMBDA(glm::dmat2x4), - DEFAULT_TO_STRING_LAMBDA(glm::dmat2x4), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(DMat3x2Property, glm::dmat3x2, glm::dmat3x2(0), - glm::dmat3x2( - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest() - ), - glm::dmat3x2( - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max() - ), - glm::dmat3x2( - 0.01, 0.01, 0.01, - 0.01, 0.01, 0.01 - ), - DEFAULT_FROM_LUA_LAMBDA(glm::dmat3x2), - DEFAULT_TO_LUA_LAMBDA(glm::dmat3x2), - DEFAULT_FROM_STRING_LAMBDA(glm::dmat3x2), - DEFAULT_TO_STRING_LAMBDA(glm::dmat3x2), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(DMat3Property, glm::dmat3x3, glm::dmat3x3(0), - glm::dmat3x3( - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest() - ), - glm::dmat3x3( - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max() - ), - glm::dmat3x3( - 0.01, 0.01, 0.01, - 0.01, 0.01, 0.01, - 0.01, 0.01, 0.01 - ), - DEFAULT_FROM_LUA_LAMBDA(glm::dmat3x3), - DEFAULT_TO_LUA_LAMBDA(glm::dmat3x3), - DEFAULT_FROM_STRING_LAMBDA(glm::dmat3x3), - DEFAULT_TO_STRING_LAMBDA(glm::dmat3x3), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(DMat3x4Property, glm::dmat3x4, glm::dmat3x4(0), - glm::dmat3x4( - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest() - ), - glm::dmat3x4( - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max() - ), - glm::dmat3x4( - 0.01, 0.01, 0.01, 0.01, - 0.01, 0.01, 0.01, 0.01, - 0.01, 0.01, 0.01, 0.01 - ), - DEFAULT_FROM_LUA_LAMBDA(glm::dmat3x4), - DEFAULT_TO_LUA_LAMBDA(glm::dmat3x4), - DEFAULT_FROM_STRING_LAMBDA(glm::dmat3x4), - DEFAULT_TO_STRING_LAMBDA(glm::dmat3x4), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(DMat4x2Property, glm::dmat4x2, glm::dmat4x2(0), - glm::dmat4x2( - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest() - ), - glm::dmat4x2( - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max() - ), - glm::dmat4x2( - 0.01, 0.01, 0.01, 0.01, - 0.01, 0.01, 0.01, 0.01 - ), - DEFAULT_FROM_LUA_LAMBDA(glm::dmat4x2), - DEFAULT_TO_LUA_LAMBDA(glm::dmat4x2), - DEFAULT_FROM_STRING_LAMBDA(glm::dmat4x2), - DEFAULT_TO_STRING_LAMBDA(glm::dmat4x2), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(DMat4x3Property, glm::dmat4x3, glm::dmat4x3(0), - glm::dmat4x3( - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest() - ), - glm::dmat4x3( - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max() - ), - glm::dmat4x3( - 0.01, 0.01, 0.01, 0.01, - 0.01, 0.01, 0.01, 0.01, - 0.01, 0.01, 0.01, 0.01 - ), - DEFAULT_FROM_LUA_LAMBDA(glm::dmat4x3), - DEFAULT_TO_LUA_LAMBDA(glm::dmat4x3), - DEFAULT_FROM_STRING_LAMBDA(glm::dmat4x3), - DEFAULT_TO_STRING_LAMBDA(glm::dmat4x3), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(DMat4Property, glm::dmat4x4, glm::dmat4x4(0), - glm::dmat4x4( - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest(), - numeric_limits::lowest() - ), - glm::dmat4x4( - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max(), - numeric_limits::max() - ), - glm::dmat4x4( - 0.01, 0.01, 0.01, 0.01, - 0.01, 0.01, 0.01, 0.01, - 0.01, 0.01, 0.01, 0.01, - 0.01, 0.01, 0.01, 0.01 - ), - DEFAULT_FROM_LUA_LAMBDA(glm::dmat4x4), - DEFAULT_TO_LUA_LAMBDA(glm::dmat4x4), - DEFAULT_FROM_STRING_LAMBDA(glm::dmat4x4), - DEFAULT_TO_STRING_LAMBDA(glm::dmat4x4), - LUA_TTABLE); - -} // namespace properties -} // namespace openspace diff --git a/src/properties/optionproperty.cpp b/src/properties/optionproperty.cpp index b205a4e9fd..8c24ba9036 100644 --- a/src/properties/optionproperty.cpp +++ b/src/properties/optionproperty.cpp @@ -33,13 +33,15 @@ namespace properties { const std::string OptionProperty::OptionsKey = "Options"; -OptionProperty::OptionProperty(std::string identifier, std::string guiName) - : IntProperty(std::move(identifier), std::move(guiName)) - , _displayType(DisplayType::RADIO) +OptionProperty::OptionProperty(std::string identifier, std::string guiName, + Property::Visibility visibility) + : IntProperty(std::move(identifier), std::move(guiName), visibility) + , _displayType(DisplayType::Radio) {} -OptionProperty::OptionProperty(std::string identifier, std::string guiName, DisplayType displayType) - : IntProperty(std::move(identifier), std::move(guiName)) +OptionProperty::OptionProperty(std::string identifier, std::string guiName, + DisplayType displayType, Property::Visibility visibility) + : IntProperty(std::move(identifier), std::move(guiName), visibility) , _displayType(displayType) {} @@ -57,11 +59,9 @@ const std::vector& OptionProperty::options() const { } void OptionProperty::addOption(int value, std::string desc) { - Option option; - option.value = value; - option.description = desc; + Option option = { std::move(value), std::move(desc) }; - for (auto o : _options) { + for (const auto& o : _options) { if (o.value == option.value) { LWARNING("The value of option {" << o.value << " -> " << o.description << "} was already registered when trying to add option {" << option.value << @@ -72,20 +72,9 @@ void OptionProperty::addOption(int value, std::string desc) { _options.push_back(std::move(option)); } -void OptionProperty::addOptions(std::vector values, std::vector descs) { - if (values.size() != descs.size()) { - LERROR("Skipping " << this->fullyQualifiedIdentifier() << ": " - << "number of values (" << values.size() << ") " - << "does not equal number of descriptions (" << descs.size() << ")" - ); - return; - } - for (int i = 0; i < values.size(); i++) { - LDEBUG(this->fullyQualifiedIdentifier() << ": Adding " - << descs[i] - << " (" << values[i] << ")" - ); - this->addOption(values[i], descs[i]); +void OptionProperty::addOptions(std::vector> options) { + for (std::pair& p : options) { + addOption(std::move(p.first), std::move(p.second)); } } diff --git a/src/properties/property.cpp b/src/properties/property.cpp index 265789fadb..aee0f405a8 100644 --- a/src/properties/property.cpp +++ b/src/properties/property.cpp @@ -35,7 +35,7 @@ namespace { const std::string _loggerCat = "Property"; const std::string MetaDataKeyGuiName = "guiName"; const std::string MetaDataKeyGroup = "Group"; - const std::string MetaDataKeyVisible = "isVisible"; + const std::string MetaDataKeyVisibility = "Visibility"; const std::string MetaDataKeyReadOnly = "isReadOnly"; const std::string _metaDataKeyViewPrefix = "view."; @@ -51,14 +51,14 @@ const std::string Property::NameKey = "Name"; const std::string Property::TypeKey = "Type"; const std::string Property::MetaDataKey = "MetaData"; -Property::Property(std::string identifier, std::string guiName) +Property::Property(std::string identifier, std::string guiName, Visibility visibility) : _owner(nullptr) , _identifier(std::move(identifier)) { ghoul_assert(!_identifier.empty(), "Identifier must not be empty"); ghoul_assert(!guiName.empty(), "guiName must not be empty"); - setVisible(true); + setVisibility(visibility); _metaData.setValue(MetaDataKeyGuiName, std::move(guiName)); } @@ -131,14 +131,18 @@ std::string Property::groupIdentifier() const { return result; } -void Property::setVisible(bool state) { - _metaData.setValue(MetaDataKeyVisible, state); +void Property::setVisibility(Visibility visibility) { + _metaData.setValue( + MetaDataKeyVisibility, + static_cast>(visibility) + ); } -bool Property::isVisible() const { - bool visible = true; - _metaData.getValue(MetaDataKeyVisible, visible); - return visible; +Property::Visibility Property::visibility() const { + return + static_cast( + _metaData.value>(MetaDataKeyVisibility) + ); } void Property::setReadOnly(bool state) { @@ -185,15 +189,22 @@ std::string Property::generateBaseDescription() const { } std::string Property::generateMetaDataDescription() const { - bool isVisible, isReadOnly; - _metaData.getValue(MetaDataKeyVisible, isVisible); - _metaData.getValue(MetaDataKeyReadOnly, isReadOnly); + static const std::map VisibilityConverter = { + { Visibility::All, "All" }, + { Visibility::Developer, "Developer" }, + { Visibility::User, "User" }, + { Visibility::None, "None" } + }; + Visibility visibility = _metaData.value(MetaDataKeyVisibility); + bool isReadOnly = _metaData.value(MetaDataKeyReadOnly); + + std::string vis = VisibilityConverter.at(visibility); return MetaDataKey + " = {" + - MetaDataKeyGroup + " = '" + groupIdentifier() + "'," + - MetaDataKeyVisible + " = " + (isVisible ? "true" : "false") + "," + - MetaDataKeyReadOnly +" = " + (isReadOnly ? "true" : "false") + "}"; + MetaDataKeyGroup + " = '" + groupIdentifier() + "'," + + MetaDataKeyVisibility + " = " + vis + "," + + MetaDataKeyReadOnly +" = " + (isReadOnly ? "true" : "false") + "}"; } std::string Property::generateAdditionalDescription() const { diff --git a/src/properties/scalar/boolproperty.cpp b/src/properties/scalar/boolproperty.cpp new file mode 100644 index 0000000000..c150cf276b --- /dev/null +++ b/src/properties/scalar/boolproperty.cpp @@ -0,0 +1,67 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include + +namespace openspace { +namespace properties { + +REGISTER_TEMPLATEPROPERTY_SOURCE(BoolProperty, bool, false, + [](lua_State* state, bool& success) -> bool { + success = (lua_isboolean(state, -1) == 1); + if (success) { + return lua_toboolean(state, -1) == 1; + } + else { + return false; + } + }, + [](lua_State* state, bool value) -> bool { + lua_pushboolean(state, value); + return true; + }, + [](std::string value, bool& success) -> bool { + std::stringstream s(value); + bool v; + s >> v; + success = !s.fail(); + if (success) { + return v; + } + }, + [](std::string& outValue, bool inValue) -> bool { + outValue = inValue ? "true" : "false"; + return true; + }, + LUA_TBOOLEAN +); + + +} // namespace properties +} // namespace openspace diff --git a/src/properties/scalar/charproperty.cpp b/src/properties/scalar/charproperty.cpp new file mode 100644 index 0000000000..57e3b78ff0 --- /dev/null +++ b/src/properties/scalar/charproperty.cpp @@ -0,0 +1,81 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](lua_State* state, bool& success) -> TYPE { \ + success = (lua_isnumber(state, -1) == 1); \ + if (success) { \ + return static_cast(lua_tonumber(state, -1)); \ + } \ + else { \ + return DEFAULT_VALUE; \ + } \ + } + +#define DEFAULT_TO_LUA_LAMBDA(TYPE) \ + [](lua_State* state, TYPE value) -> bool { \ + lua_pushnumber(state, static_cast(value)); \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](std::string value, bool& success) -> TYPE { \ + std::stringstream s(value); \ + TYPE v; \ + s >> v; \ + success = !s.fail(); \ + if (success) { \ + return v; \ + } \ + } + +#define DEFAULT_TO_STRING_LAMBDA(TYPE) \ + [](std::string& outValue, TYPE inValue) -> bool { \ + outValue = std::to_string(inValue); \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(CharProperty, char, char(0), + numeric_limits::lowest(), + numeric_limits::max(), char(1), + DEFAULT_FROM_LUA_LAMBDA(char, char(0)), + DEFAULT_TO_LUA_LAMBDA(char), + DEFAULT_FROM_STRING_LAMBDA(char, char(0)), + DEFAULT_TO_STRING_LAMBDA(char), + LUA_TNUMBER); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/scalar/doubleproperty.cpp b/src/properties/scalar/doubleproperty.cpp new file mode 100644 index 0000000000..0e6d97eb5b --- /dev/null +++ b/src/properties/scalar/doubleproperty.cpp @@ -0,0 +1,81 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](lua_State* state, bool& success) -> TYPE { \ + success = (lua_isnumber(state, -1) == 1); \ + if (success) { \ + return static_cast(lua_tonumber(state, -1)); \ + } \ + else { \ + return DEFAULT_VALUE; \ + } \ + } + +#define DEFAULT_TO_LUA_LAMBDA(TYPE) \ + [](lua_State* state, TYPE value) -> bool { \ + lua_pushnumber(state, static_cast(value)); \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](std::string value, bool& success) -> TYPE { \ + std::stringstream s(value); \ + TYPE v; \ + s >> v; \ + success = !s.fail(); \ + if (success) { \ + return v; \ + } \ + } + +#define DEFAULT_TO_STRING_LAMBDA(TYPE) \ + [](std::string& outValue, TYPE inValue) -> bool { \ + outValue = std::to_string(inValue); \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(DoubleProperty, double, 0.0, + numeric_limits::lowest(), + numeric_limits::max(), 0.01, + DEFAULT_FROM_LUA_LAMBDA(double, double(0)), + DEFAULT_TO_LUA_LAMBDA(double), + DEFAULT_FROM_STRING_LAMBDA(double, double(0)), + DEFAULT_TO_STRING_LAMBDA(double), + LUA_TNUMBER); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/scalar/floatproperty.cpp b/src/properties/scalar/floatproperty.cpp new file mode 100644 index 0000000000..c42df70e76 --- /dev/null +++ b/src/properties/scalar/floatproperty.cpp @@ -0,0 +1,81 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](lua_State* state, bool& success) -> TYPE { \ + success = (lua_isnumber(state, -1) == 1); \ + if (success) { \ + return static_cast(lua_tonumber(state, -1)); \ + } \ + else { \ + return DEFAULT_VALUE; \ + } \ + } + +#define DEFAULT_TO_LUA_LAMBDA(TYPE) \ + [](lua_State* state, TYPE value) -> bool { \ + lua_pushnumber(state, static_cast(value)); \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](std::string value, bool& success) -> TYPE { \ + std::stringstream s(value); \ + TYPE v; \ + s >> v; \ + success = !s.fail(); \ + if (success) { \ + return v; \ + } \ + } + +#define DEFAULT_TO_STRING_LAMBDA(TYPE) \ + [](std::string& outValue, TYPE inValue) -> bool { \ + outValue = std::to_string(inValue); \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(FloatProperty, float, 0.f, + numeric_limits::lowest(), + numeric_limits::max(), 0.01f, + DEFAULT_FROM_LUA_LAMBDA(float, float(0)), + DEFAULT_TO_LUA_LAMBDA(float), + DEFAULT_FROM_STRING_LAMBDA(float, float(0)), + DEFAULT_TO_STRING_LAMBDA(float), + LUA_TNUMBER); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/scalar/intproperty.cpp b/src/properties/scalar/intproperty.cpp new file mode 100644 index 0000000000..43ac9a85f2 --- /dev/null +++ b/src/properties/scalar/intproperty.cpp @@ -0,0 +1,80 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](lua_State* state, bool& success) -> TYPE { \ + success = (lua_isnumber(state, -1) == 1); \ + if (success) { \ + return static_cast(lua_tonumber(state, -1)); \ + } \ + else { \ + return DEFAULT_VALUE; \ + } \ + } + +#define DEFAULT_TO_LUA_LAMBDA(TYPE) \ + [](lua_State* state, TYPE value) -> bool { \ + lua_pushnumber(state, static_cast(value)); \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](std::string value, bool& success) -> TYPE { \ + std::stringstream s(value); \ + TYPE v; \ + s >> v; \ + success = !s.fail(); \ + if (success) { \ + return v; \ + } \ + } + +#define DEFAULT_TO_STRING_LAMBDA(TYPE) \ + [](std::string& outValue, TYPE inValue) -> bool { \ + outValue = std::to_string(inValue); \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(IntProperty, int, int(0), numeric_limits::lowest(), + numeric_limits::max(), int(1), + DEFAULT_FROM_LUA_LAMBDA(int, int(0)), + DEFAULT_TO_LUA_LAMBDA(int), + DEFAULT_FROM_STRING_LAMBDA(int, int(0)), + DEFAULT_TO_STRING_LAMBDA(int), + LUA_TNUMBER); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/scalar/longdoubleproperty.cpp b/src/properties/scalar/longdoubleproperty.cpp new file mode 100644 index 0000000000..2917978abd --- /dev/null +++ b/src/properties/scalar/longdoubleproperty.cpp @@ -0,0 +1,82 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](lua_State* state, bool& success) -> TYPE { \ + success = (lua_isnumber(state, -1) == 1); \ + if (success) { \ + return static_cast(lua_tonumber(state, -1)); \ + } \ + else { \ + return DEFAULT_VALUE; \ + } \ + } + +#define DEFAULT_TO_LUA_LAMBDA(TYPE) \ + [](lua_State* state, TYPE value) -> bool { \ + lua_pushnumber(state, static_cast(value)); \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](std::string value, bool& success) -> TYPE { \ + std::stringstream s(value); \ + TYPE v; \ + s >> v; \ + success = !s.fail(); \ + if (success) { \ + return v; \ + } \ + } + +#define DEFAULT_TO_STRING_LAMBDA(TYPE) \ + [](std::string& outValue, TYPE inValue) -> bool { \ + outValue = std::to_string(inValue); \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(LongDoubleProperty, long double, (long double)0, + numeric_limits::lowest(), + numeric_limits::max(), (long double)0.01f, + DEFAULT_FROM_LUA_LAMBDA(long double, (long double)(0)), + DEFAULT_TO_LUA_LAMBDA(long double), + DEFAULT_FROM_STRING_LAMBDA(long double, + (long double)(0)), + DEFAULT_TO_STRING_LAMBDA(long double), + LUA_TNUMBER); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/scalar/longlongproperty.cpp b/src/properties/scalar/longlongproperty.cpp new file mode 100644 index 0000000000..706ed6cba2 --- /dev/null +++ b/src/properties/scalar/longlongproperty.cpp @@ -0,0 +1,82 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](lua_State* state, bool& success) -> TYPE { \ + success = (lua_isnumber(state, -1) == 1); \ + if (success) { \ + return static_cast(lua_tonumber(state, -1)); \ + } \ + else { \ + return DEFAULT_VALUE; \ + } \ + } + +#define DEFAULT_TO_LUA_LAMBDA(TYPE) \ + [](lua_State* state, TYPE value) -> bool { \ + lua_pushnumber(state, static_cast(value)); \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](std::string value, bool& success) -> TYPE { \ + std::stringstream s(value); \ + TYPE v; \ + s >> v; \ + success = !s.fail(); \ + if (success) { \ + return v; \ + } \ + } + +#define DEFAULT_TO_STRING_LAMBDA(TYPE) \ + [](std::string& outValue, TYPE inValue) -> bool { \ + outValue = std::to_string(inValue); \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(LongLongProperty, long long, (long long)0, + numeric_limits::lowest(), + numeric_limits::max(), (long long)1, + DEFAULT_FROM_LUA_LAMBDA(long long, (long long)(0)), + DEFAULT_TO_LUA_LAMBDA(long long), + DEFAULT_FROM_STRING_LAMBDA(long long, + (long long)(0)), + DEFAULT_TO_STRING_LAMBDA(long long), + LUA_TNUMBER); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/scalar/longproperty.cpp b/src/properties/scalar/longproperty.cpp new file mode 100644 index 0000000000..2e3ddf76f9 --- /dev/null +++ b/src/properties/scalar/longproperty.cpp @@ -0,0 +1,81 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](lua_State* state, bool& success) -> TYPE { \ + success = (lua_isnumber(state, -1) == 1); \ + if (success) { \ + return static_cast(lua_tonumber(state, -1)); \ + } \ + else { \ + return DEFAULT_VALUE; \ + } \ + } + +#define DEFAULT_TO_LUA_LAMBDA(TYPE) \ + [](lua_State* state, TYPE value) -> bool { \ + lua_pushnumber(state, static_cast(value)); \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](std::string value, bool& success) -> TYPE { \ + std::stringstream s(value); \ + TYPE v; \ + s >> v; \ + success = !s.fail(); \ + if (success) { \ + return v; \ + } \ + } + +#define DEFAULT_TO_STRING_LAMBDA(TYPE) \ + [](std::string& outValue, TYPE inValue) -> bool { \ + outValue = std::to_string(inValue); \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(LongProperty, long, long(0), + numeric_limits::lowest(), + numeric_limits::max(), long(1), + DEFAULT_FROM_LUA_LAMBDA(long, long(0)), + DEFAULT_TO_LUA_LAMBDA(long), + DEFAULT_FROM_STRING_LAMBDA(long, long(0)), + DEFAULT_TO_STRING_LAMBDA(long), + LUA_TNUMBER); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/scalar/shortproperty.cpp b/src/properties/scalar/shortproperty.cpp new file mode 100644 index 0000000000..d95b09bbee --- /dev/null +++ b/src/properties/scalar/shortproperty.cpp @@ -0,0 +1,81 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](lua_State* state, bool& success) -> TYPE { \ + success = (lua_isnumber(state, -1) == 1); \ + if (success) { \ + return static_cast(lua_tonumber(state, -1)); \ + } \ + else { \ + return DEFAULT_VALUE; \ + } \ + } + +#define DEFAULT_TO_LUA_LAMBDA(TYPE) \ + [](lua_State* state, TYPE value) -> bool { \ + lua_pushnumber(state, static_cast(value)); \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](std::string value, bool& success) -> TYPE { \ + std::stringstream s(value); \ + TYPE v; \ + s >> v; \ + success = !s.fail(); \ + if (success) { \ + return v; \ + } \ + } + +#define DEFAULT_TO_STRING_LAMBDA(TYPE) \ + [](std::string& outValue, TYPE inValue) -> bool { \ + outValue = std::to_string(inValue); \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(ShortProperty, short, short(0), + numeric_limits::lowest(), + numeric_limits::max(), short(1), + DEFAULT_FROM_LUA_LAMBDA(short, short(0)), + DEFAULT_TO_LUA_LAMBDA(short), + DEFAULT_FROM_STRING_LAMBDA(short, short(0)), + DEFAULT_TO_STRING_LAMBDA(short), + LUA_TNUMBER); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/scalar/signedcharproperty.cpp b/src/properties/scalar/signedcharproperty.cpp new file mode 100644 index 0000000000..3f0e7e068a --- /dev/null +++ b/src/properties/scalar/signedcharproperty.cpp @@ -0,0 +1,81 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](lua_State* state, bool& success) -> TYPE { \ + success = (lua_isnumber(state, -1) == 1); \ + if (success) { \ + return static_cast(lua_tonumber(state, -1)); \ + } \ + else { \ + return DEFAULT_VALUE; \ + } \ + } + +#define DEFAULT_TO_LUA_LAMBDA(TYPE) \ + [](lua_State* state, TYPE value) -> bool { \ + lua_pushnumber(state, static_cast(value)); \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](std::string value, bool& success) -> TYPE { \ + std::stringstream s(value); \ + TYPE v; \ + s >> v; \ + success = !s.fail(); \ + if (success) { \ + return v; \ + } \ + } + +#define DEFAULT_TO_STRING_LAMBDA(TYPE) \ + [](std::string& outValue, TYPE inValue) -> bool { \ + outValue = std::to_string(inValue); \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(SignedCharProperty, signed char, (signed char)(0), + numeric_limits::lowest(), + numeric_limits::max(), (signed char)0, + DEFAULT_FROM_LUA_LAMBDA(signed char, (signed char)(0)), + DEFAULT_TO_LUA_LAMBDA(signed char), + DEFAULT_FROM_STRING_LAMBDA(signed char, (signed char)(0)), + DEFAULT_TO_STRING_LAMBDA(signed char), + LUA_TNUMBER); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/scalar/ucharproperty.cpp b/src/properties/scalar/ucharproperty.cpp new file mode 100644 index 0000000000..17ecca1c52 --- /dev/null +++ b/src/properties/scalar/ucharproperty.cpp @@ -0,0 +1,80 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](lua_State* state, bool& success) -> TYPE { \ + success = (lua_isnumber(state, -1) == 1); \ + if (success) \ + return static_cast(lua_tonumber(state, -1)); \ + else \ + return DEFAULT_VALUE; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(TYPE) \ + [](lua_State* state, TYPE value) -> bool { \ + lua_pushnumber(state, static_cast(value)); \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](std::string value, bool& success) -> TYPE { \ + std::stringstream s(value); \ + TYPE v; \ + s >> v; \ + success = !s.fail(); \ + if (success) \ + return v; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(TYPE) \ + [](std::string& outValue, TYPE inValue) -> bool { \ + outValue = std::to_string(inValue); \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(UCharProperty, unsigned char, (unsigned char)0, + numeric_limits::lowest(), + numeric_limits::max(), (unsigned char)1, + DEFAULT_FROM_LUA_LAMBDA(unsigned char, + (unsigned char)(0)), + DEFAULT_TO_LUA_LAMBDA(unsigned char), + DEFAULT_FROM_STRING_LAMBDA(unsigned char, + (unsigned char)(0)), + DEFAULT_TO_STRING_LAMBDA(unsigned char), + LUA_TNUMBER); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/scalar/uintproperty.cpp b/src/properties/scalar/uintproperty.cpp new file mode 100644 index 0000000000..f60782cbd8 --- /dev/null +++ b/src/properties/scalar/uintproperty.cpp @@ -0,0 +1,80 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](lua_State* state, bool& success) -> TYPE { \ + success = (lua_isnumber(state, -1) == 1); \ + if (success) \ + return static_cast(lua_tonumber(state, -1)); \ + else \ + return DEFAULT_VALUE; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(TYPE) \ + [](lua_State* state, TYPE value) -> bool { \ + lua_pushnumber(state, static_cast(value)); \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](std::string value, bool& success) -> TYPE { \ + std::stringstream s(value); \ + TYPE v; \ + s >> v; \ + success = !s.fail(); \ + if (success) \ + return v; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(TYPE) \ + [](std::string& outValue, TYPE inValue) -> bool { \ + outValue = std::to_string(inValue); \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(UCharProperty, unsigned int, (unsigned int)0, + numeric_limits::lowest(), + numeric_limits::max(), (unsigned int)1, + DEFAULT_FROM_LUA_LAMBDA(unsigned int, + (unsigned int)(0)), + DEFAULT_TO_LUA_LAMBDA(unsigned int), + DEFAULT_FROM_STRING_LAMBDA(unsigned int, + (unsigned int)(0)), + DEFAULT_TO_STRING_LAMBDA(unsigned int), + LUA_TNUMBER); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/scalar/ulonglongproperty.cpp b/src/properties/scalar/ulonglongproperty.cpp new file mode 100644 index 0000000000..6dc195639c --- /dev/null +++ b/src/properties/scalar/ulonglongproperty.cpp @@ -0,0 +1,85 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](lua_State* state, bool& success) -> TYPE { \ + success = (lua_isnumber(state, -1) == 1); \ + if (success) { \ + return static_cast(lua_tonumber(state, -1)); \ + } \ + else { \ + return DEFAULT_VALUE; \ + } \ + } + +#define DEFAULT_TO_LUA_LAMBDA(TYPE) \ + [](lua_State* state, TYPE value) -> bool { \ + lua_pushnumber(state, static_cast(value)); \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](std::string value, bool& success) -> TYPE { \ + std::stringstream s(value); \ + TYPE v; \ + s >> v; \ + success = !s.fail(); \ + if (success) { \ + return v; \ + } \ + } + +#define DEFAULT_TO_STRING_LAMBDA(TYPE) \ + [](std::string& outValue, TYPE inValue) -> bool { \ + outValue = std::to_string(inValue); \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(ULongLongProperty, unsigned long long, + (unsigned long long)1, + numeric_limits::lowest(), + numeric_limits::max(), + (unsigned long long)1, + DEFAULT_FROM_LUA_LAMBDA(unsigned long long, + (unsigned long long)(0)), + DEFAULT_TO_LUA_LAMBDA(unsigned long long), + DEFAULT_FROM_STRING_LAMBDA(unsigned long long, + (unsigned long long)(0)), + DEFAULT_TO_STRING_LAMBDA(unsigned long long), + LUA_TNUMBER); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/scalar/ulongproperty.cpp b/src/properties/scalar/ulongproperty.cpp new file mode 100644 index 0000000000..974204164d --- /dev/null +++ b/src/properties/scalar/ulongproperty.cpp @@ -0,0 +1,83 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](lua_State* state, bool& success) -> TYPE { \ + success = (lua_isnumber(state, -1) == 1); \ + if (success) { \ + return static_cast(lua_tonumber(state, -1)); \ + } \ + else { \ + return DEFAULT_VALUE; \ + } \ + } + +#define DEFAULT_TO_LUA_LAMBDA(TYPE) \ + [](lua_State* state, TYPE value) -> bool { \ + lua_pushnumber(state, static_cast(value)); \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](std::string value, bool& success) -> TYPE { \ + std::stringstream s(value); \ + TYPE v; \ + s >> v; \ + success = !s.fail(); \ + if (success) { \ + return v; \ + } \ + } + +#define DEFAULT_TO_STRING_LAMBDA(TYPE) \ + [](std::string& outValue, TYPE inValue) -> bool { \ + outValue = std::to_string(inValue); \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(ULongProperty, unsigned long, (unsigned long)0, + numeric_limits::lowest(), + numeric_limits::max(), (unsigned long)1, + DEFAULT_FROM_LUA_LAMBDA(unsigned long, + (unsigned long)(0)), + DEFAULT_TO_LUA_LAMBDA(unsigned long), + DEFAULT_FROM_STRING_LAMBDA(unsigned long, + (unsigned long)(0)), + DEFAULT_TO_STRING_LAMBDA(unsigned long), + LUA_TNUMBER); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/scalar/ushortproperty.cpp b/src/properties/scalar/ushortproperty.cpp new file mode 100644 index 0000000000..3369f51f44 --- /dev/null +++ b/src/properties/scalar/ushortproperty.cpp @@ -0,0 +1,84 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](lua_State* state, bool& success) -> TYPE { \ + success = (lua_isnumber(state, -1) == 1); \ + if (success) { \ + return static_cast(lua_tonumber(state, -1)); \ + } \ + else { \ + return DEFAULT_VALUE; \ + } \ + } + +#define DEFAULT_TO_LUA_LAMBDA(TYPE) \ + [](lua_State* state, TYPE value) -> bool { \ + lua_pushnumber(state, static_cast(value)); \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](std::string value, bool& success) -> TYPE { \ + std::stringstream s(value); \ + TYPE v; \ + s >> v; \ + success = !s.fail(); \ + if (success) { \ + return v; \ + } \ + } + +#define DEFAULT_TO_STRING_LAMBDA(TYPE) \ + [](std::string& outValue, TYPE inValue) -> bool { \ + outValue = std::to_string(inValue); \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(UShortProperty, unsigned short, (unsigned short)(0), + numeric_limits::lowest(), + numeric_limits::max(), + (unsigned short)1, + DEFAULT_FROM_LUA_LAMBDA(unsigned short, + (unsigned short)(0)), + DEFAULT_TO_LUA_LAMBDA(unsigned short), + DEFAULT_FROM_STRING_LAMBDA(unsigned short, + (unsigned short)(0)), + DEFAULT_TO_STRING_LAMBDA(unsigned short), + LUA_TNUMBER); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/scalar/wcharproperty.cpp b/src/properties/scalar/wcharproperty.cpp new file mode 100644 index 0000000000..9a8c60b1a3 --- /dev/null +++ b/src/properties/scalar/wcharproperty.cpp @@ -0,0 +1,75 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](lua_State* state, bool& success) -> TYPE { \ + success = (lua_isnumber(state, -1) == 1); \ + if (success) { \ + return static_cast(lua_tonumber(state, -1)); \ + } \ + else { \ + return DEFAULT_VALUE; \ + } \ + } + +#define DEFAULT_TO_LUA_LAMBDA(TYPE) \ + [](lua_State* state, TYPE value) -> bool { \ + lua_pushnumber(state, static_cast(value)); \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(TYPE, DEFAULT_VALUE) \ + [](std::string value, bool& success) -> TYPE { \ + std::stringstream s(value); \ + TYPE v; \ + s >> v; \ + success = !s.fail(); \ + if (success) { \ + return v; \ + } \ + } + +//REGISTER_NUMERICALPROPERTY_SOURCE(WCharProperty, wchar_t, wchar_t(0), +// numeric_limits::lowest(), +// numeric_limits::max(), wchar_t(1), +// DEFAULT_FROM_LUA_LAMBDA(wchar_t, wchar_t(0)), +// DEFAULT_TO_LUA_LAMBDA(wchar_t), +// DEFAULT_FROM_STRING_LAMBDA(wchar_t, wchar_t(0)), +// DEFAULT_TO_STRING_LAMBDA(wchar_t), +// LUA_TNUMBER); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/scalarproperty.cpp b/src/properties/scalarproperty.cpp deleted file mode 100644 index d21ba5b5b6..0000000000 --- a/src/properties/scalarproperty.cpp +++ /dev/null @@ -1,247 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#include "openspace/properties/scalarproperty.h" - -#include - -#include -#include - -using std::numeric_limits; - -namespace openspace { -namespace properties { - -#define DEFAULT_FROM_LUA_LAMBDA(TYPE, DEFAULT_VALUE) \ - [](lua_State* state, bool& success) -> TYPE { \ - success = (lua_isnumber(state, -1) == 1); \ - if (success) \ - return static_cast(lua_tonumber(state, -1)); \ - else \ - return DEFAULT_VALUE; \ - } - -#define DEFAULT_TO_LUA_LAMBDA(TYPE) \ - [](lua_State* state, TYPE value) -> bool { \ - lua_pushnumber(state, static_cast(value)); \ - return true; \ - } - -#define DEFAULT_FROM_STRING_LAMBDA(TYPE, DEFAULT_VALUE) \ - [](std::string value, bool& success) -> TYPE { \ - std::stringstream s(value); \ - TYPE v; \ - s >> v; \ - success = !s.fail(); \ - if (success) \ - return v; \ - } - -#define DEFAULT_TO_STRING_LAMBDA(TYPE) \ - [](std::string& outValue, TYPE inValue) -> bool { \ - outValue = std::to_string(inValue); \ - return true; \ - } - -// char16_t and char32_t are not supported on Visual Studio 2013 and are defined to -// be equal to unsigned short and unsigned int which causes a compile error - -REGISTER_TEMPLATEPROPERTY_SOURCE(BoolProperty, bool, false, - [](lua_State* state, bool& success) -> bool { - success = (lua_isboolean(state, -1) == 1); - if (success) - return lua_toboolean(state, -1) == 1; - else - return false; - }, - [](lua_State* state, bool value) -> bool { - lua_pushboolean(state, value); - return true; - }, - DEFAULT_FROM_STRING_LAMBDA(bool, false), - [](std::string& outValue, bool inValue) -> bool { - outValue = inValue ? "true" : "false"; - return true; - }, - LUA_TBOOLEAN - ); - -REGISTER_NUMERICALPROPERTY_SOURCE(CharProperty, char, char(0), - numeric_limits::lowest(), - numeric_limits::max(), char(1), - DEFAULT_FROM_LUA_LAMBDA(char, char(0)), - DEFAULT_TO_LUA_LAMBDA(char), - DEFAULT_FROM_STRING_LAMBDA(char, char(0)), - DEFAULT_TO_STRING_LAMBDA(char), - LUA_TNUMBER); - -// REGISTER_NUMERICALPROPERTY_SOURCE(Char16Property, char16_t, char16_t(0), -// numeric_limits::lowest(), numeric_limits::max(), char16_t(1)); - -// REGISTER_NUMERICALPROPERTY_SOURCE(Char32Property, char32_t, char32_t(0), -// numeric_limits::lowest(), numeric_limits::max(), char32_t(1)); - -//REGISTER_NUMERICALPROPERTY_SOURCE(WCharProperty, wchar_t, wchar_t(0), -// numeric_limits::lowest(), -// numeric_limits::max(), wchar_t(1), -// DEFAULT_FROM_LUA_LAMBDA(wchar_t, wchar_t(0)), -// DEFAULT_TO_LUA_LAMBDA(wchar_t), -// DEFAULT_FROM_STRING_LAMBDA(wchar_t, wchar_t(0)), -// DEFAULT_TO_STRING_LAMBDA(wchar_t), -// LUA_TNUMBER); - -REGISTER_NUMERICALPROPERTY_SOURCE(SignedCharProperty, signed char, (signed char)(0), - numeric_limits::lowest(), - numeric_limits::max(), (signed char)0, - DEFAULT_FROM_LUA_LAMBDA(signed char, (signed char)(0)), - DEFAULT_TO_LUA_LAMBDA(signed char), - DEFAULT_FROM_STRING_LAMBDA(signed char, (signed char)(0)), - DEFAULT_TO_STRING_LAMBDA(signed char), - LUA_TNUMBER); - -REGISTER_NUMERICALPROPERTY_SOURCE(UCharProperty, unsigned char, (unsigned char)0, - numeric_limits::lowest(), - numeric_limits::max(), (unsigned char)1, - DEFAULT_FROM_LUA_LAMBDA(unsigned char, - (unsigned char)(0)), - DEFAULT_TO_LUA_LAMBDA(unsigned char), - DEFAULT_FROM_STRING_LAMBDA(unsigned char, - (unsigned char)(0)), - DEFAULT_TO_STRING_LAMBDA(unsigned char), - LUA_TNUMBER); - -REGISTER_NUMERICALPROPERTY_SOURCE(ShortProperty, short, short(0), - numeric_limits::lowest(), - numeric_limits::max(), short(1), - DEFAULT_FROM_LUA_LAMBDA(short, short(0)), - DEFAULT_TO_LUA_LAMBDA(short), - DEFAULT_FROM_STRING_LAMBDA(short, short(0)), - DEFAULT_TO_STRING_LAMBDA(short), - LUA_TNUMBER); - -REGISTER_NUMERICALPROPERTY_SOURCE(UShortProperty, unsigned short, (unsigned short)(0), - numeric_limits::lowest(), - numeric_limits::max(), - (unsigned short)1, - DEFAULT_FROM_LUA_LAMBDA(unsigned short, - (unsigned short)(0)), - DEFAULT_TO_LUA_LAMBDA(unsigned short), - DEFAULT_FROM_STRING_LAMBDA(unsigned short, - (unsigned short)(0)), - DEFAULT_TO_STRING_LAMBDA(unsigned short), - LUA_TNUMBER); - -REGISTER_NUMERICALPROPERTY_SOURCE(IntProperty, int, int(0), numeric_limits::lowest(), - numeric_limits::max(), int(1), - DEFAULT_FROM_LUA_LAMBDA(int, int(0)), - DEFAULT_TO_LUA_LAMBDA(int), - DEFAULT_FROM_STRING_LAMBDA(int, int(0)), - DEFAULT_TO_STRING_LAMBDA(int), - LUA_TNUMBER); - -REGISTER_NUMERICALPROPERTY_SOURCE(UIntProperty, unsigned int, (unsigned int)0, - numeric_limits::lowest(), - numeric_limits::max(), (unsigned int)1, - DEFAULT_FROM_LUA_LAMBDA(unsigned int, - (unsigned int)(0)), - DEFAULT_TO_LUA_LAMBDA(unsigned int), - DEFAULT_FROM_STRING_LAMBDA(unsigned int, - (unsigned int)(0)), - DEFAULT_TO_STRING_LAMBDA(unsigned int), - LUA_TNUMBER); - -REGISTER_NUMERICALPROPERTY_SOURCE(LongProperty, long, long(0), - numeric_limits::lowest(), - numeric_limits::max(), long(1), - DEFAULT_FROM_LUA_LAMBDA(long, long(0)), - DEFAULT_TO_LUA_LAMBDA(long), - DEFAULT_FROM_STRING_LAMBDA(long, long(0)), - DEFAULT_TO_STRING_LAMBDA(long), - LUA_TNUMBER); - -REGISTER_NUMERICALPROPERTY_SOURCE(ULongProperty, unsigned long, (unsigned long)0, - numeric_limits::lowest(), - numeric_limits::max(), (unsigned long)1, - DEFAULT_FROM_LUA_LAMBDA(unsigned long, - (unsigned long)(0)), - DEFAULT_TO_LUA_LAMBDA(unsigned long), - DEFAULT_FROM_STRING_LAMBDA(unsigned long, - (unsigned long)(0)), - DEFAULT_TO_STRING_LAMBDA(unsigned long), - LUA_TNUMBER); - -REGISTER_NUMERICALPROPERTY_SOURCE(LongLongProperty, long long, (long long)0, - numeric_limits::lowest(), - numeric_limits::max(), (long long)1, - DEFAULT_FROM_LUA_LAMBDA(long long, (long long)(0)), - DEFAULT_TO_LUA_LAMBDA(long long), - DEFAULT_FROM_STRING_LAMBDA(long long, - (long long)(0)), - DEFAULT_TO_STRING_LAMBDA(long long), - LUA_TNUMBER); - -REGISTER_NUMERICALPROPERTY_SOURCE(ULongLongProperty, unsigned long long, - (unsigned long long)1, - numeric_limits::lowest(), - numeric_limits::max(), - (unsigned long long)1, - DEFAULT_FROM_LUA_LAMBDA(unsigned long long, - (unsigned long long)(0)), - DEFAULT_TO_LUA_LAMBDA(unsigned long long), - DEFAULT_FROM_STRING_LAMBDA(unsigned long long, - (unsigned long long)(0)), - DEFAULT_TO_STRING_LAMBDA(unsigned long long), - LUA_TNUMBER); - -REGISTER_NUMERICALPROPERTY_SOURCE(FloatProperty, float, 0.f, - numeric_limits::lowest(), - numeric_limits::max(), 0.01f, - DEFAULT_FROM_LUA_LAMBDA(float, float(0)), - DEFAULT_TO_LUA_LAMBDA(float), - DEFAULT_FROM_STRING_LAMBDA(float, float(0)), - DEFAULT_TO_STRING_LAMBDA(float), - LUA_TNUMBER); - -REGISTER_NUMERICALPROPERTY_SOURCE(DoubleProperty, double, 0.0, - numeric_limits::lowest(), - numeric_limits::max(), 0.01, - DEFAULT_FROM_LUA_LAMBDA(double, double(0)), - DEFAULT_TO_LUA_LAMBDA(double), - DEFAULT_FROM_STRING_LAMBDA(double, double(0)), - DEFAULT_TO_STRING_LAMBDA(double), - LUA_TNUMBER); - -REGISTER_NUMERICALPROPERTY_SOURCE(LongDoubleProperty, long double, (long double)0, - numeric_limits::lowest(), - numeric_limits::max(), (long double)0.01f, - DEFAULT_FROM_LUA_LAMBDA(long double, (long double)(0)), - DEFAULT_TO_LUA_LAMBDA(long double), - DEFAULT_FROM_STRING_LAMBDA(long double, - (long double)(0)), - DEFAULT_TO_STRING_LAMBDA(long double), - LUA_TNUMBER); - -} // namespace properties -} // namespace openspace diff --git a/src/properties/selectionproperty.cpp b/src/properties/selectionproperty.cpp index 601176f440..adeefb3f5b 100644 --- a/src/properties/selectionproperty.cpp +++ b/src/properties/selectionproperty.cpp @@ -24,6 +24,8 @@ #include +#include + namespace { const std::string _loggerCat = "SelectionProperty"; @@ -35,8 +37,10 @@ namespace properties { const std::string SelectionProperty::OptionsKey = "Options"; -SelectionProperty::SelectionProperty(std::string identifier, std::string guiName) - : TemplateProperty(std::move(identifier), std::move(guiName), std::vector()) +SelectionProperty::SelectionProperty(std::string identifier, std::string guiName, + Property::Visibility visibility) + : TemplateProperty(std::move(identifier), std::move(guiName), std::vector(), + visibility) {} void SelectionProperty::addOption(Option option) { diff --git a/src/properties/triggerproperty.cpp b/src/properties/triggerproperty.cpp index e0f024f522..9f40a36345 100644 --- a/src/properties/triggerproperty.cpp +++ b/src/properties/triggerproperty.cpp @@ -27,8 +27,9 @@ namespace openspace { namespace properties { -TriggerProperty::TriggerProperty(std::string identifier, std::string guiName) - : Property(std::move(identifier), std::move(guiName)) +TriggerProperty::TriggerProperty(std::string identifier, std::string guiName, + Property::Visibility visibility) + : Property(std::move(identifier), std::move(guiName), visibility) {} std::string TriggerProperty::className() const { diff --git a/src/properties/vector/bvec2property.cpp b/src/properties/vector/bvec2property.cpp new file mode 100644 index 0000000000..4e48dd1de5 --- /dev/null +++ b/src/properties/vector/bvec2property.cpp @@ -0,0 +1,125 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include + +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__, __CONVFUNC__, __TESTFUNC__) \ + [](lua_State * state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + lua_pushnil(state); \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + int success = lua_next(state, -2); \ + if (success != 1) { \ + success = false; \ + return __TYPE__(0); \ + } \ + if (__TESTFUNC__(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i] = static_cast<__TYPE__::value_type>(__CONVFUNC__(state, -1)); \ + lua_pop(state, 1); \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State * state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + lua_pushnumber(state, static_cast(value[i])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != result.length()) { \ + success = false; \ + return result; \ + } \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + std::stringstream s(tokens[i]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else \ + result[i] = v; \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = "{"; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) \ + outValue += std::to_string(inValue[i]) + ","; \ + outValue.pop_back(); \ + outValue += "}"; \ + return true; \ + } + + +// Forcing value from int to bool is acceptable here (line 48) +#ifdef WIN32 +#pragma warning(disable : 4800) +#endif + + +REGISTER_TEMPLATEPROPERTY_SOURCE(BVec2Property, glm::bvec2, glm::bvec2(false), + DEFAULT_FROM_LUA_LAMBDA(glm::bvec2, lua_toboolean, + lua_isboolean), + DEFAULT_TO_LUA_LAMBDA(glm::bvec2), + DEFAULT_FROM_STRING_LAMBDA(glm::bvec2), + DEFAULT_TO_STRING_LAMBDA(glm::bvec2), + LUA_TTABLE); + +#ifdef WIN32 +#pragma warning(default : 4800) +#endif + +} // namespace properties +} // namespace openspace diff --git a/src/properties/vector/bvec3property.cpp b/src/properties/vector/bvec3property.cpp new file mode 100644 index 0000000000..9891b42f2f --- /dev/null +++ b/src/properties/vector/bvec3property.cpp @@ -0,0 +1,124 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include + +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__, __CONVFUNC__, __TESTFUNC__) \ + [](lua_State * state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + lua_pushnil(state); \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + int success = lua_next(state, -2); \ + if (success != 1) { \ + success = false; \ + return __TYPE__(0); \ + } \ + if (__TESTFUNC__(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i] = static_cast<__TYPE__::value_type>(__CONVFUNC__(state, -1)); \ + lua_pop(state, 1); \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State * state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + lua_pushnumber(state, static_cast(value[i])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != result.length()) { \ + success = false; \ + return result; \ + } \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + std::stringstream s(tokens[i]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else \ + result[i] = v; \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = "{"; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) \ + outValue += std::to_string(inValue[i]) + ","; \ + outValue.pop_back(); \ + outValue += "}"; \ + return true; \ + } + + +// Forcing value from int to bool is acceptable here (line 48) +#ifdef WIN32 +#pragma warning(disable : 4800) +#endif + +REGISTER_TEMPLATEPROPERTY_SOURCE(BVec3Property, glm::bvec3, glm::bvec3(false), + DEFAULT_FROM_LUA_LAMBDA(glm::bvec3, lua_toboolean, + lua_isboolean), + DEFAULT_TO_LUA_LAMBDA(glm::bvec3), + DEFAULT_FROM_STRING_LAMBDA(glm::bvec3), + DEFAULT_TO_STRING_LAMBDA(glm::bvec3), + LUA_TTABLE); + +#ifdef WIN32 +#pragma warning(default : 4800) +#endif + +} // namespace properties +} // namespace openspace diff --git a/src/properties/vector/bvec4property.cpp b/src/properties/vector/bvec4property.cpp new file mode 100644 index 0000000000..9ec01527e2 --- /dev/null +++ b/src/properties/vector/bvec4property.cpp @@ -0,0 +1,124 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include + +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__, __CONVFUNC__, __TESTFUNC__) \ + [](lua_State * state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + lua_pushnil(state); \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + int success = lua_next(state, -2); \ + if (success != 1) { \ + success = false; \ + return __TYPE__(0); \ + } \ + if (__TESTFUNC__(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i] = static_cast<__TYPE__::value_type>(__CONVFUNC__(state, -1)); \ + lua_pop(state, 1); \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State * state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + lua_pushnumber(state, static_cast(value[i])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != result.length()) { \ + success = false; \ + return result; \ + } \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + std::stringstream s(tokens[i]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else \ + result[i] = v; \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = "{"; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) \ + outValue += std::to_string(inValue[i]) + ","; \ + outValue.pop_back(); \ + outValue += "}"; \ + return true; \ + } + + +// Forcing value from int to bool is acceptable here (line 48) +#ifdef WIN32 +#pragma warning(disable : 4800) +#endif + +REGISTER_TEMPLATEPROPERTY_SOURCE(BVec4Property, glm::bvec4, glm::bvec4(false), + DEFAULT_FROM_LUA_LAMBDA(glm::bvec4, lua_toboolean, + lua_isboolean), + DEFAULT_TO_LUA_LAMBDA(glm::bvec4), + DEFAULT_FROM_STRING_LAMBDA(glm::bvec4), + DEFAULT_TO_STRING_LAMBDA(glm::bvec4), + LUA_TTABLE); + +#ifdef WIN32 +#pragma warning(default : 4800) +#endif + +} // namespace properties +} // namespace openspace diff --git a/src/properties/vector/dvec2property.cpp b/src/properties/vector/dvec2property.cpp new file mode 100644 index 0000000000..2c70902f22 --- /dev/null +++ b/src/properties/vector/dvec2property.cpp @@ -0,0 +1,117 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include + +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__, __CONVFUNC__, __TESTFUNC__) \ + [](lua_State * state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + lua_pushnil(state); \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + int success = lua_next(state, -2); \ + if (success != 1) { \ + success = false; \ + return __TYPE__(0); \ + } \ + if (__TESTFUNC__(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i] = static_cast<__TYPE__::value_type>(__CONVFUNC__(state, -1)); \ + lua_pop(state, 1); \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State * state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + lua_pushnumber(state, static_cast(value[i])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != result.length()) { \ + success = false; \ + return result; \ + } \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + std::stringstream s(tokens[i]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else \ + result[i] = v; \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = "{"; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) \ + outValue += std::to_string(inValue[i]) + ","; \ + outValue.pop_back(); \ + outValue += "}"; \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(DVec2Property, glm::dvec2, glm::dvec2(0), + glm::dvec2(numeric_limits::lowest()), + glm::dvec2(numeric_limits::max()), + glm::dvec2(0.01), + DEFAULT_FROM_LUA_LAMBDA(glm::dvec2, lua_tonumber, + lua_isnumber), + DEFAULT_TO_LUA_LAMBDA(glm::dvec2), + DEFAULT_FROM_STRING_LAMBDA(glm::dvec2), + DEFAULT_TO_STRING_LAMBDA(glm::dvec2), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/vector/dvec3property.cpp b/src/properties/vector/dvec3property.cpp new file mode 100644 index 0000000000..80d9b4db3f --- /dev/null +++ b/src/properties/vector/dvec3property.cpp @@ -0,0 +1,117 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include + +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__, __CONVFUNC__, __TESTFUNC__) \ + [](lua_State * state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + lua_pushnil(state); \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + int success = lua_next(state, -2); \ + if (success != 1) { \ + success = false; \ + return __TYPE__(0); \ + } \ + if (__TESTFUNC__(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i] = static_cast<__TYPE__::value_type>(__CONVFUNC__(state, -1)); \ + lua_pop(state, 1); \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State * state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + lua_pushnumber(state, static_cast(value[i])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != result.length()) { \ + success = false; \ + return result; \ + } \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + std::stringstream s(tokens[i]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else \ + result[i] = v; \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = "{"; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) \ + outValue += std::to_string(inValue[i]) + ","; \ + outValue.pop_back(); \ + outValue += "}"; \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(DVec3Property, glm::dvec3, glm::dvec3(0), + glm::dvec3(numeric_limits::lowest()), + glm::dvec3(numeric_limits::max()), + glm::dvec3(0.01), + DEFAULT_FROM_LUA_LAMBDA(glm::dvec3, lua_tonumber, + lua_isnumber), + DEFAULT_TO_LUA_LAMBDA(glm::dvec3), + DEFAULT_FROM_STRING_LAMBDA(glm::dvec3), + DEFAULT_TO_STRING_LAMBDA(glm::dvec3), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/vector/dvec4property.cpp b/src/properties/vector/dvec4property.cpp new file mode 100644 index 0000000000..2a8393437b --- /dev/null +++ b/src/properties/vector/dvec4property.cpp @@ -0,0 +1,117 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include + +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__, __CONVFUNC__, __TESTFUNC__) \ + [](lua_State * state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + lua_pushnil(state); \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + int success = lua_next(state, -2); \ + if (success != 1) { \ + success = false; \ + return __TYPE__(0); \ + } \ + if (__TESTFUNC__(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i] = static_cast<__TYPE__::value_type>(__CONVFUNC__(state, -1)); \ + lua_pop(state, 1); \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State * state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + lua_pushnumber(state, static_cast(value[i])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != result.length()) { \ + success = false; \ + return result; \ + } \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + std::stringstream s(tokens[i]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else \ + result[i] = v; \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = "{"; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) \ + outValue += std::to_string(inValue[i]) + ","; \ + outValue.pop_back(); \ + outValue += "}"; \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(DVec4Property, glm::dvec4, glm::dvec4(0), + glm::dvec4(numeric_limits::lowest()), + glm::dvec4(numeric_limits::max()), + glm::dvec4(0.01), + DEFAULT_FROM_LUA_LAMBDA(glm::dvec4, lua_tonumber, + lua_isnumber), + DEFAULT_TO_LUA_LAMBDA(glm::dvec4), + DEFAULT_FROM_STRING_LAMBDA(glm::dvec4), + DEFAULT_TO_STRING_LAMBDA(glm::dvec4), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/vector/ivec2property.cpp b/src/properties/vector/ivec2property.cpp new file mode 100644 index 0000000000..3949a09bb1 --- /dev/null +++ b/src/properties/vector/ivec2property.cpp @@ -0,0 +1,116 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include + +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__, __CONVFUNC__, __TESTFUNC__) \ + [](lua_State * state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + lua_pushnil(state); \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + int success = lua_next(state, -2); \ + if (success != 1) { \ + success = false; \ + return __TYPE__(0); \ + } \ + if (__TESTFUNC__(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i] = static_cast<__TYPE__::value_type>(__CONVFUNC__(state, -1)); \ + lua_pop(state, 1); \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State * state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + lua_pushnumber(state, static_cast(value[i])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != result.length()) { \ + success = false; \ + return result; \ + } \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + std::stringstream s(tokens[i]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else \ + result[i] = v; \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = "{"; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) \ + outValue += std::to_string(inValue[i]) + ","; \ + outValue.pop_back(); \ + outValue += "}"; \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(IVec2Property, glm::ivec2, glm::ivec2(0), + glm::ivec2(numeric_limits::lowest()), + glm::ivec2(numeric_limits::max()), glm::ivec2(1), + DEFAULT_FROM_LUA_LAMBDA(glm::ivec2, lua_tonumber, + lua_isnumber), + DEFAULT_TO_LUA_LAMBDA(glm::ivec2), + DEFAULT_FROM_STRING_LAMBDA(glm::ivec2), + DEFAULT_TO_STRING_LAMBDA(glm::ivec2), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/vector/ivec3property.cpp b/src/properties/vector/ivec3property.cpp new file mode 100644 index 0000000000..f7e4207e87 --- /dev/null +++ b/src/properties/vector/ivec3property.cpp @@ -0,0 +1,116 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include + +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__, __CONVFUNC__, __TESTFUNC__) \ + [](lua_State * state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + lua_pushnil(state); \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + int success = lua_next(state, -2); \ + if (success != 1) { \ + success = false; \ + return __TYPE__(0); \ + } \ + if (__TESTFUNC__(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i] = static_cast<__TYPE__::value_type>(__CONVFUNC__(state, -1)); \ + lua_pop(state, 1); \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State * state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + lua_pushnumber(state, static_cast(value[i])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != result.length()) { \ + success = false; \ + return result; \ + } \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + std::stringstream s(tokens[i]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else \ + result[i] = v; \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = "{"; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) \ + outValue += std::to_string(inValue[i]) + ","; \ + outValue.pop_back(); \ + outValue += "}"; \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(IVec3Property, glm::ivec3, glm::ivec3(0), + glm::ivec3(numeric_limits::lowest()), + glm::ivec3(numeric_limits::max()), glm::ivec3(1), + DEFAULT_FROM_LUA_LAMBDA(glm::ivec3, lua_tonumber, + lua_isnumber), + DEFAULT_TO_LUA_LAMBDA(glm::ivec3), + DEFAULT_FROM_STRING_LAMBDA(glm::ivec3), + DEFAULT_TO_STRING_LAMBDA(glm::ivec3), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/vector/ivec4property.cpp b/src/properties/vector/ivec4property.cpp new file mode 100644 index 0000000000..2c357001d6 --- /dev/null +++ b/src/properties/vector/ivec4property.cpp @@ -0,0 +1,116 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include + +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__, __CONVFUNC__, __TESTFUNC__) \ + [](lua_State * state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + lua_pushnil(state); \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + int success = lua_next(state, -2); \ + if (success != 1) { \ + success = false; \ + return __TYPE__(0); \ + } \ + if (__TESTFUNC__(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i] = static_cast<__TYPE__::value_type>(__CONVFUNC__(state, -1)); \ + lua_pop(state, 1); \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State * state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + lua_pushnumber(state, static_cast(value[i])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != result.length()) { \ + success = false; \ + return result; \ + } \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + std::stringstream s(tokens[i]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else \ + result[i] = v; \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = "{"; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) \ + outValue += std::to_string(inValue[i]) + ","; \ + outValue.pop_back(); \ + outValue += "}"; \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(IVec4Property, glm::ivec4, glm::ivec4(0), + glm::ivec4(numeric_limits::lowest()), + glm::ivec4(numeric_limits::max()), glm::ivec4(1), + DEFAULT_FROM_LUA_LAMBDA(glm::ivec4, lua_tonumber, + lua_isnumber), + DEFAULT_TO_LUA_LAMBDA(glm::ivec4), + DEFAULT_FROM_STRING_LAMBDA(glm::ivec4), + DEFAULT_TO_STRING_LAMBDA(glm::ivec4), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/vector/uvec2property.cpp b/src/properties/vector/uvec2property.cpp new file mode 100644 index 0000000000..50bc166cba --- /dev/null +++ b/src/properties/vector/uvec2property.cpp @@ -0,0 +1,117 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include + +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__, __CONVFUNC__, __TESTFUNC__) \ + [](lua_State * state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + lua_pushnil(state); \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + int success = lua_next(state, -2); \ + if (success != 1) { \ + success = false; \ + return __TYPE__(0); \ + } \ + if (__TESTFUNC__(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i] = static_cast<__TYPE__::value_type>(__CONVFUNC__(state, -1)); \ + lua_pop(state, 1); \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State * state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + lua_pushnumber(state, static_cast(value[i])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != result.length()) { \ + success = false; \ + return result; \ + } \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + std::stringstream s(tokens[i]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else \ + result[i] = v; \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = "{"; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) \ + outValue += std::to_string(inValue[i]) + ","; \ + outValue.pop_back(); \ + outValue += "}"; \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(UVec2Property, glm::uvec2, glm::uvec2(0), + glm::uvec2(numeric_limits::lowest()), + glm::uvec2(numeric_limits::max()), + glm::uvec2(1), + DEFAULT_FROM_LUA_LAMBDA(glm::uvec2, lua_tonumber, + lua_isnumber), + DEFAULT_TO_LUA_LAMBDA(glm::uvec2), + DEFAULT_FROM_STRING_LAMBDA(glm::uvec2), + DEFAULT_TO_STRING_LAMBDA(glm::uvec2), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/vector/uvec3property.cpp b/src/properties/vector/uvec3property.cpp new file mode 100644 index 0000000000..0feb1188e8 --- /dev/null +++ b/src/properties/vector/uvec3property.cpp @@ -0,0 +1,117 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include + +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__, __CONVFUNC__, __TESTFUNC__) \ + [](lua_State * state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + lua_pushnil(state); \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + int success = lua_next(state, -2); \ + if (success != 1) { \ + success = false; \ + return __TYPE__(0); \ + } \ + if (__TESTFUNC__(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i] = static_cast<__TYPE__::value_type>(__CONVFUNC__(state, -1)); \ + lua_pop(state, 1); \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State * state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + lua_pushnumber(state, static_cast(value[i])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != result.length()) { \ + success = false; \ + return result; \ + } \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + std::stringstream s(tokens[i]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else \ + result[i] = v; \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = "{"; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) \ + outValue += std::to_string(inValue[i]) + ","; \ + outValue.pop_back(); \ + outValue += "}"; \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(UVec3Property, glm::uvec3, glm::uvec3(0), + glm::uvec3(numeric_limits::lowest()), + glm::uvec3(numeric_limits::max()), + glm::uvec3(1), + DEFAULT_FROM_LUA_LAMBDA(glm::uvec3, lua_tonumber, + lua_isnumber), + DEFAULT_TO_LUA_LAMBDA(glm::uvec3), + DEFAULT_FROM_STRING_LAMBDA(glm::uvec3), + DEFAULT_TO_STRING_LAMBDA(glm::uvec3), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/vector/uvec4property.cpp b/src/properties/vector/uvec4property.cpp new file mode 100644 index 0000000000..333907eb7c --- /dev/null +++ b/src/properties/vector/uvec4property.cpp @@ -0,0 +1,117 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include + +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__, __CONVFUNC__, __TESTFUNC__) \ + [](lua_State * state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + lua_pushnil(state); \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + int success = lua_next(state, -2); \ + if (success != 1) { \ + success = false; \ + return __TYPE__(0); \ + } \ + if (__TESTFUNC__(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i] = static_cast<__TYPE__::value_type>(__CONVFUNC__(state, -1)); \ + lua_pop(state, 1); \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State * state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + lua_pushnumber(state, static_cast(value[i])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != result.length()) { \ + success = false; \ + return result; \ + } \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + std::stringstream s(tokens[i]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else \ + result[i] = v; \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = "{"; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) \ + outValue += std::to_string(inValue[i]) + ","; \ + outValue.pop_back(); \ + outValue += "}"; \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(UVec4Property, glm::uvec4, glm::uvec4(0), + glm::uvec4(numeric_limits::lowest()), + glm::uvec4(numeric_limits::max()), + glm::uvec4(1), + DEFAULT_FROM_LUA_LAMBDA(glm::uvec4, lua_tonumber, + lua_isnumber), + DEFAULT_TO_LUA_LAMBDA(glm::uvec4), + DEFAULT_FROM_STRING_LAMBDA(glm::uvec4), + DEFAULT_TO_STRING_LAMBDA(glm::uvec4), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/vector/vec2property.cpp b/src/properties/vector/vec2property.cpp new file mode 100644 index 0000000000..4cef6f2c28 --- /dev/null +++ b/src/properties/vector/vec2property.cpp @@ -0,0 +1,117 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include + +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__, __CONVFUNC__, __TESTFUNC__) \ + [](lua_State * state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + lua_pushnil(state); \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + int success = lua_next(state, -2); \ + if (success != 1) { \ + success = false; \ + return __TYPE__(0); \ + } \ + if (__TESTFUNC__(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i] = static_cast<__TYPE__::value_type>(__CONVFUNC__(state, -1)); \ + lua_pop(state, 1); \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State * state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + lua_pushnumber(state, static_cast(value[i])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != result.length()) { \ + success = false; \ + return result; \ + } \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + std::stringstream s(tokens[i]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else \ + result[i] = v; \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = "{"; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) \ + outValue += std::to_string(inValue[i]) + ","; \ + outValue.pop_back(); \ + outValue += "}"; \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(Vec2Property, glm::vec2, glm::vec2(0), + glm::vec2(numeric_limits::lowest()), + glm::vec2(numeric_limits::max()), + glm::vec2(0.01f), + DEFAULT_FROM_LUA_LAMBDA(glm::vec2, lua_tonumber, + lua_isnumber), + DEFAULT_TO_LUA_LAMBDA(glm::vec2), + DEFAULT_FROM_STRING_LAMBDA(glm::vec2), + DEFAULT_TO_STRING_LAMBDA(glm::vec2), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/vector/vec3property.cpp b/src/properties/vector/vec3property.cpp new file mode 100644 index 0000000000..3c237bea2a --- /dev/null +++ b/src/properties/vector/vec3property.cpp @@ -0,0 +1,117 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include + +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__, __CONVFUNC__, __TESTFUNC__) \ + [](lua_State * state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + lua_pushnil(state); \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + int success = lua_next(state, -2); \ + if (success != 1) { \ + success = false; \ + return __TYPE__(0); \ + } \ + if (__TESTFUNC__(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i] = static_cast<__TYPE__::value_type>(__CONVFUNC__(state, -1)); \ + lua_pop(state, 1); \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State * state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + lua_pushnumber(state, static_cast(value[i])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != result.length()) { \ + success = false; \ + return result; \ + } \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + std::stringstream s(tokens[i]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else \ + result[i] = v; \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = "{"; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) \ + outValue += std::to_string(inValue[i]) + ","; \ + outValue.pop_back(); \ + outValue += "}"; \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(Vec3Property, glm::vec3, glm::vec3(0), + glm::vec3(numeric_limits::lowest()), + glm::vec3(numeric_limits::max()), + glm::vec3(0.01f), + DEFAULT_FROM_LUA_LAMBDA(glm::vec3, lua_tonumber, + lua_isnumber), + DEFAULT_TO_LUA_LAMBDA(glm::vec3), + DEFAULT_FROM_STRING_LAMBDA(glm::vec3), + DEFAULT_TO_STRING_LAMBDA(glm::vec3), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/vector/vec4property.cpp b/src/properties/vector/vec4property.cpp new file mode 100644 index 0000000000..196fc28036 --- /dev/null +++ b/src/properties/vector/vec4property.cpp @@ -0,0 +1,117 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include + +#include + +using std::numeric_limits; + +namespace openspace { +namespace properties { + +#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__, __CONVFUNC__, __TESTFUNC__) \ + [](lua_State * state, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + lua_pushnil(state); \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + int success = lua_next(state, -2); \ + if (success != 1) { \ + success = false; \ + return __TYPE__(0); \ + } \ + if (__TESTFUNC__(state, -1) != 1) { \ + success = false; \ + return __TYPE__(0); \ + } else { \ + result[i] = static_cast<__TYPE__::value_type>(__CONVFUNC__(state, -1)); \ + lua_pop(state, 1); \ + } \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ + [](lua_State * state, __TYPE__ value) -> bool { \ + lua_newtable(state); \ + int number = 1; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + lua_pushnumber(state, static_cast(value[i])); \ + lua_setfield(state, -2, std::to_string(number).c_str()); \ + ++number; \ + } \ + return true; \ + } + +#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ + [](std::string value, bool& success) -> __TYPE__ { \ + __TYPE__ result; \ + std::vector tokens = ghoul::tokenizeString(value, ','); \ + if (tokens.size() != result.length()) { \ + success = false; \ + return result; \ + } \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ + std::stringstream s(tokens[i]); \ + __TYPE__::value_type v; \ + s >> v; \ + if (s.fail()) { \ + success = false; \ + return result; \ + } \ + else \ + result[i] = v; \ + } \ + success = true; \ + return result; \ + } + +#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ + [](std::string& outValue, __TYPE__ inValue) -> bool { \ + outValue = "{"; \ + for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) \ + outValue += std::to_string(inValue[i]) + ","; \ + outValue.pop_back(); \ + outValue += "}"; \ + return true; \ + } + +REGISTER_NUMERICALPROPERTY_SOURCE(Vec4Property, glm::vec4, glm::vec4(0), + glm::vec4(numeric_limits::lowest()), + glm::vec4(numeric_limits::max()), + glm::vec4(0.01f), + DEFAULT_FROM_LUA_LAMBDA(glm::vec4, lua_tonumber, + lua_isnumber), + DEFAULT_TO_LUA_LAMBDA(glm::vec4), + DEFAULT_FROM_STRING_LAMBDA(glm::vec4), + DEFAULT_TO_STRING_LAMBDA(glm::vec4), + LUA_TTABLE); + +} // namespace properties +} // namespace openspace diff --git a/src/properties/vectorproperty.cpp b/src/properties/vectorproperty.cpp deleted file mode 100644 index 22ce875f6b..0000000000 --- a/src/properties/vectorproperty.cpp +++ /dev/null @@ -1,271 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2016 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#include "openspace/properties/vectorproperty.h" - -#include -#include -#include - -#include - -using std::numeric_limits; - -namespace openspace { -namespace properties { - -#define DEFAULT_FROM_LUA_LAMBDA(__TYPE__, __CONVFUNC__, __TESTFUNC__) \ - [](lua_State * state, bool& success) -> __TYPE__ { \ - __TYPE__ result; \ - lua_pushnil(state); \ - for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ - int success = lua_next(state, -2); \ - if (success != 1) { \ - success = false; \ - return __TYPE__(0); \ - } \ - if (__TESTFUNC__(state, -1) != 1) { \ - success = false; \ - return __TYPE__(0); \ - } else { \ - result[i] = static_cast<__TYPE__::value_type>(__CONVFUNC__(state, -1)); \ - lua_pop(state, 1); \ - } \ - } \ - success = true; \ - return result; \ - } - -#define DEFAULT_TO_LUA_LAMBDA(__TYPE__) \ - [](lua_State * state, __TYPE__ value) -> bool { \ - lua_newtable(state); \ - int number = 1; \ - for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ - lua_pushnumber(state, static_cast(value[i])); \ - lua_setfield(state, -2, std::to_string(number).c_str()); \ - ++number; \ - } \ - return true; \ - } - -#define DEFAULT_FROM_STRING_LAMBDA(__TYPE__) \ - [](std::string value, bool& success) -> __TYPE__ { \ - __TYPE__ result; \ - std::vector tokens = ghoul::tokenizeString(value, ','); \ - if (tokens.size() != result.length()) { \ - success = false; \ - return result; \ - } \ - for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) { \ - std::stringstream s(tokens[i]); \ - __TYPE__::value_type v; \ - s >> v; \ - if (s.fail()) { \ - success = false; \ - return result; \ - } \ - else \ - result[i] = v; \ - } \ - success = true; \ - return result; \ - } - -#define DEFAULT_TO_STRING_LAMBDA(__TYPE__) \ - [](std::string& outValue, __TYPE__ inValue) -> bool { \ - outValue = "{"; \ - for (glm::length_t i = 0; i < ghoul::glm_components<__TYPE__>::value; ++i) \ - outValue += std::to_string(inValue[i]) + ","; \ - outValue.pop_back(); \ - outValue += "}"; \ - return true; \ - } - - -// Forcing value from int to bool is acceptable here (line 48) -#ifdef WIN32 -#pragma warning(disable : 4800) -#endif - - -REGISTER_TEMPLATEPROPERTY_SOURCE(BVec2Property, glm::bvec2, glm::bvec2(false), - DEFAULT_FROM_LUA_LAMBDA(glm::bvec2, lua_toboolean, - lua_isboolean), - DEFAULT_TO_LUA_LAMBDA(glm::bvec2), - DEFAULT_FROM_STRING_LAMBDA(glm::bvec2), - DEFAULT_TO_STRING_LAMBDA(glm::bvec2), - LUA_TTABLE); - -REGISTER_TEMPLATEPROPERTY_SOURCE(BVec3Property, glm::bvec3, glm::bvec3(false), - DEFAULT_FROM_LUA_LAMBDA(glm::bvec3, lua_toboolean, - lua_isboolean), - DEFAULT_TO_LUA_LAMBDA(glm::bvec3), - DEFAULT_FROM_STRING_LAMBDA(glm::bvec3), - DEFAULT_TO_STRING_LAMBDA(glm::bvec3), - LUA_TTABLE); - -REGISTER_TEMPLATEPROPERTY_SOURCE(BVec4Property, glm::bvec4, glm::bvec4(false), - DEFAULT_FROM_LUA_LAMBDA(glm::bvec4, lua_toboolean, - lua_isboolean), - DEFAULT_TO_LUA_LAMBDA(glm::bvec4), - DEFAULT_FROM_STRING_LAMBDA(glm::bvec4), - DEFAULT_TO_STRING_LAMBDA(glm::bvec4), - LUA_TTABLE); - -#ifdef WIN32 -#pragma warning(default : 4800) -#endif - - -REGISTER_NUMERICALPROPERTY_SOURCE(Vec2Property, glm::vec2, glm::vec2(0), - glm::vec2(numeric_limits::lowest()), - glm::vec2(numeric_limits::max()), - glm::vec2(0.01f), - DEFAULT_FROM_LUA_LAMBDA(glm::vec2, lua_tonumber, - lua_isnumber), - DEFAULT_TO_LUA_LAMBDA(glm::vec2), - DEFAULT_FROM_STRING_LAMBDA(glm::vec2), - DEFAULT_TO_STRING_LAMBDA(glm::vec2), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(Vec3Property, glm::vec3, glm::vec3(0), - glm::vec3(numeric_limits::lowest()), - glm::vec3(numeric_limits::max()), - glm::vec3(0.01f), - DEFAULT_FROM_LUA_LAMBDA(glm::vec3, lua_tonumber, - lua_isnumber), - DEFAULT_TO_LUA_LAMBDA(glm::vec3), - DEFAULT_FROM_STRING_LAMBDA(glm::vec3), - DEFAULT_TO_STRING_LAMBDA(glm::vec3), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(Vec4Property, glm::vec4, glm::vec4(0), - glm::vec4(numeric_limits::lowest()), - glm::vec4(numeric_limits::max()), - glm::vec4(0.01f), - DEFAULT_FROM_LUA_LAMBDA(glm::vec4, lua_tonumber, - lua_isnumber), - DEFAULT_TO_LUA_LAMBDA(glm::vec4), - DEFAULT_FROM_STRING_LAMBDA(glm::vec4), - DEFAULT_TO_STRING_LAMBDA(glm::vec4), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(DVec2Property, glm::dvec2, glm::dvec2(0), - glm::dvec2(numeric_limits::lowest()), - glm::dvec2(numeric_limits::max()), - glm::dvec2(0.01), - DEFAULT_FROM_LUA_LAMBDA(glm::dvec2, lua_tonumber, - lua_isnumber), - DEFAULT_TO_LUA_LAMBDA(glm::dvec2), - DEFAULT_FROM_STRING_LAMBDA(glm::dvec2), - DEFAULT_TO_STRING_LAMBDA(glm::dvec2), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(DVec3Property, glm::dvec3, glm::dvec3(0), - glm::dvec3(numeric_limits::lowest()), - glm::dvec3(numeric_limits::max()), - glm::dvec3(0.01), - DEFAULT_FROM_LUA_LAMBDA(glm::dvec3, lua_tonumber, - lua_isnumber), - DEFAULT_TO_LUA_LAMBDA(glm::dvec3), - DEFAULT_FROM_STRING_LAMBDA(glm::dvec3), - DEFAULT_TO_STRING_LAMBDA(glm::dvec3), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(DVec4Property, glm::dvec4, glm::dvec4(0), - glm::dvec4(numeric_limits::lowest()), - glm::dvec4(numeric_limits::max()), - glm::dvec4(0.01), - DEFAULT_FROM_LUA_LAMBDA(glm::dvec4, lua_tonumber, - lua_isnumber), - DEFAULT_TO_LUA_LAMBDA(glm::dvec4), - DEFAULT_FROM_STRING_LAMBDA(glm::dvec4), - DEFAULT_TO_STRING_LAMBDA(glm::dvec4), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(IVec2Property, glm::ivec2, glm::ivec2(0), - glm::ivec2(numeric_limits::lowest()), - glm::ivec2(numeric_limits::max()), glm::ivec2(1), - DEFAULT_FROM_LUA_LAMBDA(glm::ivec2, lua_tonumber, - lua_isnumber), - DEFAULT_TO_LUA_LAMBDA(glm::ivec2), - DEFAULT_FROM_STRING_LAMBDA(glm::ivec2), - DEFAULT_TO_STRING_LAMBDA(glm::ivec2), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(IVec3Property, glm::ivec3, glm::ivec3(0), - glm::ivec3(numeric_limits::lowest()), - glm::ivec3(numeric_limits::max()), glm::ivec3(1), - DEFAULT_FROM_LUA_LAMBDA(glm::ivec3, lua_tonumber, - lua_isnumber), - DEFAULT_TO_LUA_LAMBDA(glm::ivec3), - DEFAULT_FROM_STRING_LAMBDA(glm::ivec3), - DEFAULT_TO_STRING_LAMBDA(glm::ivec3), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(IVec4Property, glm::ivec4, glm::ivec4(0), - glm::ivec4(numeric_limits::lowest()), - glm::ivec4(numeric_limits::max()), glm::ivec4(1), - DEFAULT_FROM_LUA_LAMBDA(glm::ivec4, lua_tonumber, - lua_isnumber), - DEFAULT_TO_LUA_LAMBDA(glm::ivec4), - DEFAULT_FROM_STRING_LAMBDA(glm::ivec4), - DEFAULT_TO_STRING_LAMBDA(glm::ivec4), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(UVec2Property, glm::uvec2, glm::uvec2(0), - glm::uvec2(numeric_limits::lowest()), - glm::uvec2(numeric_limits::max()), - glm::uvec2(1), - DEFAULT_FROM_LUA_LAMBDA(glm::uvec2, lua_tonumber, - lua_isnumber), - DEFAULT_TO_LUA_LAMBDA(glm::uvec2), - DEFAULT_FROM_STRING_LAMBDA(glm::uvec2), - DEFAULT_TO_STRING_LAMBDA(glm::uvec2), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(UVec3Property, glm::uvec3, glm::uvec3(0), - glm::uvec3(numeric_limits::lowest()), - glm::uvec3(numeric_limits::max()), - glm::uvec3(1), - DEFAULT_FROM_LUA_LAMBDA(glm::uvec3, lua_tonumber, - lua_isnumber), - DEFAULT_TO_LUA_LAMBDA(glm::uvec3), - DEFAULT_FROM_STRING_LAMBDA(glm::uvec3), - DEFAULT_TO_STRING_LAMBDA(glm::uvec3), - LUA_TTABLE); - -REGISTER_NUMERICALPROPERTY_SOURCE(UVec4Property, glm::uvec4, glm::uvec4(0), - glm::uvec4(numeric_limits::lowest()), - glm::uvec4(numeric_limits::max()), - glm::uvec4(1), - DEFAULT_FROM_LUA_LAMBDA(glm::uvec4, lua_tonumber, - lua_isnumber), - DEFAULT_TO_LUA_LAMBDA(glm::uvec4), - DEFAULT_FROM_STRING_LAMBDA(glm::uvec4), - DEFAULT_TO_STRING_LAMBDA(glm::uvec4), - LUA_TTABLE); - -} // namespace properties -} // namespace openspace diff --git a/src/query/query.cpp b/src/query/query.cpp index 7d87a9ccbf..224fd7fb1c 100644 --- a/src/query/query.cpp +++ b/src/query/query.cpp @@ -31,7 +31,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/rendering/abufferrenderer.cpp b/src/rendering/abufferrenderer.cpp index c38e3c9487..2cc1c2025e 100644 --- a/src/rendering/abufferrenderer.cpp +++ b/src/rendering/abufferrenderer.cpp @@ -50,7 +50,6 @@ namespace { const std::string _loggerCat = "ABufferRenderer"; const std::string BoundsFragmentShaderPath = "${SHADERS}/abuffer/boundsabuffer.frag"; const std::string RenderFragmentShaderPath = "${SHADERS}/abuffer/renderabuffer.frag"; - const std::string PostRenderFragmentShaderPath = "${SHADERS}/abuffer/postrenderabuffer.frag"; const int MaxRaycasters = 32; const int MaxLayers = 32; const int MaxAverageLayers = 8; @@ -322,8 +321,6 @@ void ABufferRenderer::render(float blackoutFactor, bool doPerformanceMeasurement _resolveProgram->deactivate(); - _scene->postRender(data); - _mainColorTextureUnit = nullptr; _mainDepthTextureUnit = nullptr; } @@ -561,10 +558,7 @@ void ABufferRenderer::updateRendererData() { PerfMeasure("ABufferRenderer::updateRendererData"); ghoul::Dictionary dict; - dict.setValue("windowWidth", _resolution.x); - dict.setValue("windowHeight", _resolution.y); dict.setValue("fragmentRendererPath", std::string(RenderFragmentShaderPath)); - dict.setValue("postFragmentRendererPath", std::string(PostRenderFragmentShaderPath)); dict.setValue("maxLayers", MaxLayers); dict.setValue("maxTotalFragments", MaxLayers * _resolution.x * _resolution.y); diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index af1c2c23c2..63041636f3 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -47,7 +47,6 @@ namespace { const std::string ExitFragmentShaderPath = "${SHADERS}/framebuffer/exitframebuffer.frag"; const std::string RaycastFragmentShaderPath = "${SHADERS}/framebuffer/raycastframebuffer.frag"; const std::string RenderFragmentShaderPath = "${SHADERS}/framebuffer/renderframebuffer.frag"; - const std::string PostRenderFragmentShaderPath = "${SHADERS}/framebuffer/postrenderframebuffer.frag"; } namespace openspace { @@ -125,8 +124,6 @@ void FramebufferRenderer::initialize() { } OsEng.renderEngine().raycasterManager().addListener(*this); - - } void FramebufferRenderer::deinitialize() { @@ -153,8 +150,6 @@ void FramebufferRenderer::raycastersChanged(VolumeRaycaster& raycaster, bool att } void FramebufferRenderer::update() { - PerfMeasure("FramebufferRenderer::update"); - if (_dirtyResolution) { updateResolution(); } @@ -206,14 +201,11 @@ void FramebufferRenderer::update() { } void FramebufferRenderer::updateResolution() { - int nSamples = _nAaSamples; - PerfMeasure("FramebufferRenderer::updateResolution"); - glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, _mainColorTexture); glTexImage2DMultisample( GL_TEXTURE_2D_MULTISAMPLE, - nSamples, + _nAaSamples, GL_RGBA, GLsizei(_resolution.x), GLsizei(_resolution.y), @@ -222,7 +214,7 @@ void FramebufferRenderer::updateResolution() { glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, _mainDepthTexture); glTexImage2DMultisample( GL_TEXTURE_2D_MULTISAMPLE, - nSamples, + _nAaSamples, GL_DEPTH_COMPONENT32F, GLsizei(_resolution.x), GLsizei(_resolution.y), @@ -263,8 +255,6 @@ void FramebufferRenderer::updateResolution() { } void FramebufferRenderer::updateRaycastData() { - PerfMeasure("FramebufferRenderer::updateRaycastData"); - _raycastData.clear(); _exitPrograms.clear(); _raycastPrograms.clear(); @@ -319,7 +309,13 @@ void FramebufferRenderer::updateRaycastData() { } void FramebufferRenderer::render(float blackoutFactor, bool doPerformanceMeasurements) { - PerfMeasure("FramebufferRenderer::render"); + std::unique_ptr perf; + if (doPerformanceMeasurements) { + perf = std::make_unique( + "FramebufferRenderer::render", + OsEng.renderEngine().performanceManager() + ); + } if (!_scene) return; @@ -401,6 +397,7 @@ void FramebufferRenderer::render(float blackoutFactor, bool doPerformanceMeasure raycastProgram->setUniform("mainDepthTexture", mainDepthTextureUnit); raycastProgram->setUniform("nAaSamples", _nAaSamples); + raycastProgram->setUniform("windowSize", glm::vec2(_resolution)); glDisable(GL_DEPTH_TEST); @@ -467,19 +464,12 @@ void FramebufferRenderer::setNAaSamples(int nAaSamples) { } void FramebufferRenderer::updateRendererData() { - PerfMeasure("FramebufferRenderer::updateRendererData"); - ghoul::Dictionary dict; dict.setValue("fragmentRendererPath", std::string(RenderFragmentShaderPath)); - dict.setValue("postFragmentRendererPath", std::string(PostRenderFragmentShaderPath)); - dict.setValue("windowWidth", _resolution.x); - dict.setValue("windowHeight", _resolution.y); _rendererData = dict; OsEng.renderEngine().setRendererData(dict); } - } - diff --git a/src/rendering/renderable.cpp b/src/rendering/renderable.cpp index 3313c432ef..58826b0b0d 100644 --- a/src/rendering/renderable.cpp +++ b/src/rendering/renderable.cpp @@ -134,8 +134,6 @@ void Renderable::render(const RenderData& data, RendererTasks&) { void Renderable::render(const RenderData& data) {} -void Renderable::postRender(const RenderData& data) {} - void Renderable::setPscUniforms( ghoul::opengl::ProgramObject& program, const Camera& camera, diff --git a/src/rendering/renderengine.cpp b/src/rendering/renderengine.cpp index 54f7b92a33..85fd0b77a6 100644 --- a/src/rendering/renderengine.cpp +++ b/src/rendering/renderengine.cpp @@ -24,6 +24,8 @@ #include +#include + #ifdef OPENSPACE_MODULE_NEWHORIZONS_ENABLED #include #endif @@ -59,6 +61,7 @@ #include #include #include +#include #include #include #include @@ -81,13 +84,8 @@ #include #include -#include #include -// These are temporary ---abock -#include -#include - // ABuffer defines #define RENDERER_FRAMEBUFFER 0 #define RENDERER_ABUFFER 1 @@ -101,7 +99,6 @@ namespace { std::chrono::seconds ScreenLogTimeToLive(15); const std::string DefaultRenderingMethod = "ABuffer"; const std::string RenderFsPath = "${SHADERS}/render.frag"; - const std::string PostRenderFsPath = "${SHADERS}/postrender.frag"; } @@ -117,6 +114,12 @@ const std::vector RenderEngine::FrametimeTypes({ RenderEngine::RenderEngine() : _mainCamera(nullptr) + , _performanceMeasurements("performanceMeasurements", "Performance Measurements") + , _frametimeType( + "frametimeType", + "Type of the frametime display", + properties::OptionProperty::DisplayType::Dropdown + ) , _sceneGraph(nullptr) , _renderer(nullptr) , _rendererImplementation(RendererImplementation::Invalid) @@ -131,14 +134,36 @@ RenderEngine::RenderEngine() , _currentFadeTime(0.f) , _fadeDirection(0) , _frameNumber(0) - , _frametimeType(FrametimeType::DtTimeAvg) - // , _sgctRenderStatisticsVisible(false) + //, _frametimeType(FrametimeType::DtTimeAvg) { - _onScreenInformation = { - glm::vec2(0.f), - 12, - -1 - }; + setName("RenderEngine"); + + _performanceMeasurements.onChange([this](){ + if (_performanceMeasurements) { + if (!_performanceManager) { + _performanceManager = std::make_unique(); + } + } + else { + _performanceManager = nullptr; + } + + }); + addProperty(_performanceMeasurements); + + _frametimeType.addOption( + static_cast(FrametimeType::DtTimeAvg), + "Average Deltatime" + ); + _frametimeType.addOption( + static_cast(FrametimeType::FPS), + "Frames per second" + ); + _frametimeType.addOption( + static_cast(FrametimeType::FPSAvg), + "Average frames per second" + ); + addProperty(_frametimeType); } RenderEngine::~RenderEngine() { @@ -155,9 +180,7 @@ bool RenderEngine::deinitialize() { screenspacerenderable->deinitialize(); } -#ifdef OPENSPACE_MODULE_NEWHORIZONS_ENABLED MissionManager::deinitialize(); -#endif _sceneGraph->clearSceneGraph(); return true; @@ -228,10 +251,7 @@ bool RenderEngine::initialize() { ghoul::io::TextureReader::ref().addReader(std::make_shared()); -#ifdef OPENSPACE_MODULE_NEWHORIZONS_ENABLED MissionManager::initialize(); -#endif - return true; } @@ -347,8 +367,9 @@ void RenderEngine::updateSceneGraph() { glm::dmat3(1), 1, Time::ref().j2000Seconds(), - Time::ref().timeJumped(), Time::ref().deltaTime(), + Time::ref().paused(), + Time::ref().timeJumped(), _performanceManager != nullptr }); @@ -378,9 +399,11 @@ void RenderEngine::updateRenderer() { bool windowResized = OsEng.windowWrapper().windowHasResized(); if (windowResized) { - glm::ivec2 res = OsEng.windowWrapper().currentDrawBufferResolution(); - _renderer->setResolution(res); - ghoul::fontrendering::FontRenderer::defaultRenderer().setFramebufferSize(glm::vec2(res)); + _renderer->setResolution(renderingResolution()); + + ghoul::fontrendering::FontRenderer::defaultRenderer().setFramebufferSize( + fontResolution() + ); } _renderer->update(); @@ -392,6 +415,31 @@ void RenderEngine::updateScreenSpaceRenderables() { } } +glm::ivec2 RenderEngine::renderingResolution() const { + if (OsEng.windowWrapper().isRegularRendering()) { + return OsEng.windowWrapper().currentWindowResolution(); + } + else { + return OsEng.windowWrapper().currentDrawBufferResolution(); + } +} + +glm::ivec2 RenderEngine::fontResolution() const { + std::string value; + bool hasValue = OsEng.configurationManager().getValue( + ConfigurationManager::KeyOnScreenTextScaling, + value + ); + if (hasValue && value == "framebuffer") { + return OsEng.windowWrapper().currentWindowResolution(); + } + else { + // The default is to use the window size + return OsEng.windowWrapper().currentWindowSize(); + } +} + + void RenderEngine::updateFade() { //temporary fade funtionality float fadedIn = 1.0; @@ -497,21 +545,6 @@ void RenderEngine::toggleInfoText(bool b) { _showInfo = b; } -void RenderEngine::toggleFrametimeType(int t) { - std::vector::const_iterator it = std::find( - FrametimeTypes.begin(), FrametimeTypes.end(), _frametimeType); - - if (!t && it == FrametimeTypes.begin()) - it = FrametimeTypes.end(); - - t > 0 ? ++it : --it; - - if (t && it == FrametimeTypes.end()) - it = FrametimeTypes.begin(); - - _frametimeType = *it; -} - Scene* RenderEngine::scene() { ghoul_assert(_sceneGraph, "Scenegraph not initialized"); return _sceneGraph; @@ -558,8 +591,7 @@ std::unique_ptr RenderEngine::buildRenderProgram( std::string name, std::string vsPath, std::string fsPath, - const ghoul::Dictionary& data, - RenderEngine::RenderProgramType type) { + const ghoul::Dictionary& data) { ghoul::Dictionary dict = data; @@ -570,16 +602,10 @@ std::unique_ptr RenderEngine::buildRenderProgram( // instead of a void main() setting glFragColor, glFragDepth, etc. dict.setValue("fragmentPath", fsPath); - if (type == RenderEngine::RenderProgramType::Post) { - dict.setValue("resolveData", _resolveData); - } - - std::string path = (type == RenderEngine::RenderProgramType::Post) ? PostRenderFsPath : RenderFsPath; - std::unique_ptr program = ghoul::opengl::ProgramObject::Build( name, vsPath, - path, + RenderFsPath, dict); if (program) { @@ -596,27 +622,20 @@ std::unique_ptr RenderEngine::buildRenderProgram( std::string vsPath, std::string fsPath, std::string csPath, - const ghoul::Dictionary& data, - RenderEngine::RenderProgramType type) { + const ghoul::Dictionary& data) { ghoul::Dictionary dict = data; dict.setValue("rendererData", _rendererData); - if (type == RenderEngine::RenderProgramType::Post) { - dict.setValue("resolveData", _resolveData); - } - // parameterize the main fragment shader program with specific contents. // fsPath should point to a shader file defining a Fragment getFragment() function // instead of a void main() setting glFragColor, glFragDepth, etc. dict.setValue("fragmentPath", fsPath); - std::string path = (type == RenderEngine::RenderProgramType::Post) ? PostRenderFsPath : RenderFsPath; - std::unique_ptr program = ghoul::opengl::ProgramObject::Build( name, vsPath, - path, + RenderFsPath, csPath, dict); @@ -691,14 +710,12 @@ void RenderEngine::postRaycast(ghoul::opengl::ProgramObject& programObject) { * Set renderer */ void RenderEngine::setRenderer(std::unique_ptr renderer) { - glm::ivec2 res = OsEng.windowWrapper().currentDrawBufferResolution(); - if (_renderer) { _renderer->deinitialize(); } _renderer = std::move(renderer); - _renderer->setResolution(res); + _renderer->setResolution(renderingResolution()); _renderer->setNAaSamples(_nAaSamples); _renderer->initialize(); _renderer->setCamera(_mainCamera); @@ -743,39 +760,24 @@ scripting::LuaLibrary RenderEngine::luaLibrary() { "bool", "Toggles the showing of render information on-screen text" }, - { - "toggleFrametimeType", - &luascriptfunctions::toggleFrametimeType, - "int", - "Toggle showing FPS or Average Frametime in heads up info" - }, - { - "setPerformanceMeasurement", - &luascriptfunctions::setPerformanceMeasurement, - "bool", - "Sets the performance measurements" - }, { "toggleFade", &luascriptfunctions::toggleFade, "number", - "Toggles fading in or out", - true + "Toggles fading in or out" }, { "fadeIn", &luascriptfunctions::fadeIn, "number", - "", - true + "" }, //also temporary @JK { "fadeOut", &luascriptfunctions::fadeOut, "number", - "", - true + "" }, { "registerScreenSpaceRenderable", @@ -793,17 +795,6 @@ scripting::LuaLibrary RenderEngine::luaLibrary() { }; } -void RenderEngine::setPerformanceMeasurements(bool performanceMeasurements) { - if (performanceMeasurements) { - if (!_performanceManager) { - _performanceManager = std::make_unique(); - } - } - else { - _performanceManager = nullptr; - } -} - bool RenderEngine::doesPerformanceMeasurements() const { return _performanceManager != nullptr; } @@ -814,391 +805,391 @@ performance::PerformanceManager* RenderEngine::performanceManager() { // This method is temporary and will be removed once the scalegraph is in effect ---abock void RenderEngine::changeViewPoint(std::string origin) { - SceneGraphNode* solarSystemBarycenterNode = scene()->sceneGraphNode("SolarSystemBarycenter"); - SceneGraphNode* plutoBarycenterNode = scene()->sceneGraphNode("PlutoBarycenter"); - SceneGraphNode* newHorizonsNode = scene()->sceneGraphNode("NewHorizons"); - SceneGraphNode* newHorizonsPathNodeJ = scene()->sceneGraphNode("NewHorizonsPathJupiter"); - SceneGraphNode* newHorizonsPathNodeP = scene()->sceneGraphNode("NewHorizonsPathPluto"); -// SceneGraphNode* cg67pNode = scene()->sceneGraphNode("67P"); -// SceneGraphNode* rosettaNode = scene()->sceneGraphNode("Rosetta"); - - RenderablePath* nhPath; - - SceneGraphNode* jupiterBarycenterNode = scene()->sceneGraphNode("JupiterBarycenter"); - - //SceneGraphNode* newHorizonsGhostNode = scene()->sceneGraphNode("NewHorizonsGhost"); - //SceneGraphNode* dawnNode = scene()->sceneGraphNode("Dawn"); - //SceneGraphNode* vestaNode = scene()->sceneGraphNode("Vesta"); - - // if (solarSystemBarycenterNode == nullptr || plutoBarycenterNode == nullptr || - //jupiterBarycenterNode == nullptr) { - // LERROR("Necessary nodes does not exist"); - //return; - // } - - if (origin == "Pluto") { - if (newHorizonsPathNodeP) { - Renderable* R = newHorizonsPathNodeP->renderable(); - newHorizonsPathNodeP->setParent(plutoBarycenterNode); - nhPath = static_cast(R); - nhPath->calculatePath("PLUTO BARYCENTER"); - } - - plutoBarycenterNode->setParent(scene()->sceneGraphNode("SolarSystem")); - plutoBarycenterNode->setEphemeris(new StaticEphemeris); - - solarSystemBarycenterNode->setParent(plutoBarycenterNode); - newHorizonsNode->setParent(plutoBarycenterNode); - //newHorizonsGhostNode->setParent(plutoBarycenterNode); - - //dawnNode->setParent(plutoBarycenterNode); - //vestaNode->setParent(plutoBarycenterNode); - - //newHorizonsTrailNode->setParent(plutoBarycenterNode); - ghoul::Dictionary solarDictionary = - { - { std::string("Type"), std::string("Spice") }, - { std::string("Body"), std::string("SUN") }, - { std::string("Reference"), std::string("GALACTIC") }, - { std::string("Observer"), std::string("PLUTO BARYCENTER") }, - { std::string("Kernels"), ghoul::Dictionary() } - }; - - ghoul::Dictionary jupiterDictionary = - { - { std::string("Type"), std::string("Spice") }, - { std::string("Body"), std::string("JUPITER BARYCENTER") }, - { std::string("Reference"), std::string("GALACTIC") }, - { std::string("Observer"), std::string("PLUTO BARYCENTER") }, - { std::string("Kernels"), ghoul::Dictionary() } - }; - - ghoul::Dictionary newHorizonsDictionary = - { - { std::string("Type"), std::string("Spice") }, - { std::string("Body"), std::string("NEW HORIZONS") }, - { std::string("Reference"), std::string("GALACTIC") }, - { std::string("Observer"), std::string("PLUTO BARYCENTER") }, - { std::string("Kernels"), ghoul::Dictionary() } - }; - - solarSystemBarycenterNode->setEphemeris(new SpiceEphemeris(solarDictionary)); - jupiterBarycenterNode->setEphemeris(new SpiceEphemeris(jupiterDictionary)); - newHorizonsNode->setEphemeris(new SpiceEphemeris(newHorizonsDictionary)); - //newHorizonsTrailNode->setEphemeris(new SpiceEphemeris(newHorizonsDictionary)); - - - //ghoul::Dictionary dawnDictionary = - //{ - // { std::string("Type"), std::string("Spice") }, - // { std::string("Body"), std::string("DAWN") }, - // { std::string("Reference"), std::string("GALACTIC") }, - // { std::string("Observer"), std::string("PLUTO BARYCENTER") }, - // { std::string("Kernels"), ghoul::Dictionary() } - //}; - //dawnNode->setEphemeris(new SpiceEphemeris(dawnDictionary)); - // - //ghoul::Dictionary vestaDictionary = - //{ - // { std::string("Type"), std::string("Spice") }, - // { std::string("Body"), std::string("VESTA") }, - // { std::string("Reference"), std::string("GALACTIC") }, - // { std::string("Observer"), std::string("PLUTO BARYCENTER") }, - // { std::string("Kernels"), ghoul::Dictionary() } - //}; - //vestaNode->setEphemeris(new SpiceEphemeris(vestaDictionary)); - - - //ghoul::Dictionary newHorizonsGhostDictionary = - //{ - // { std::string("Type"), std::string("Spice") }, - // { std::string("Body"), std::string("NEW HORIZONS") }, - // { std::string("EphmerisGhosting"), std::string("TRUE") }, - // { std::string("Reference"), std::string("GALACTIC") }, - // { std::string("Observer"), std::string("PLUTO BARYCENTER") }, - // { std::string("Kernels"), ghoul::Dictionary() } - //}; - //newHorizonsGhostNode->setEphemeris(new SpiceEphemeris(newHorizonsGhostDictionary)); - - return; - } - if (origin == "Sun") { - solarSystemBarycenterNode->setParent(scene()->sceneGraphNode("SolarSystem")); - - if (plutoBarycenterNode) - plutoBarycenterNode->setParent(solarSystemBarycenterNode); - jupiterBarycenterNode->setParent(solarSystemBarycenterNode); - if (newHorizonsNode) - newHorizonsNode->setParent(solarSystemBarycenterNode); - //newHorizonsGhostNode->setParent(solarSystemBarycenterNode); - - //newHorizonsTrailNode->setParent(solarSystemBarycenterNode); - //dawnNode->setParent(solarSystemBarycenterNode); - //vestaNode->setParent(solarSystemBarycenterNode); - - ghoul::Dictionary plutoDictionary = - { - { std::string("Type"), std::string("Spice") }, - { std::string("Body"), std::string("PLUTO BARYCENTER") }, - { std::string("Reference"), std::string("GALACTIC") }, - { std::string("Observer"), std::string("SUN") }, - { std::string("Kernels"), ghoul::Dictionary() } - }; - ghoul::Dictionary jupiterDictionary = - { - { std::string("Type"), std::string("Spice") }, - { std::string("Body"), std::string("JUPITER BARYCENTER") }, - { std::string("Reference"), std::string("GALACTIC") }, - { std::string("Observer"), std::string("SUN") }, - { std::string("Kernels"), ghoul::Dictionary() } - }; - - solarSystemBarycenterNode->setEphemeris(new StaticEphemeris); - jupiterBarycenterNode->setEphemeris(new SpiceEphemeris(jupiterDictionary)); - if (plutoBarycenterNode) - plutoBarycenterNode->setEphemeris(new SpiceEphemeris(plutoDictionary)); - - ghoul::Dictionary newHorizonsDictionary = - { - { std::string("Type"), std::string("Spice") }, - { std::string("Body"), std::string("NEW HORIZONS") }, - { std::string("Reference"), std::string("GALACTIC") }, - { std::string("Observer"), std::string("SUN") }, - { std::string("Kernels"), ghoul::Dictionary() } - }; - if (newHorizonsNode) - newHorizonsNode->setEphemeris(new SpiceEphemeris(newHorizonsDictionary)); - //newHorizonsTrailNode->setEphemeris(new SpiceEphemeris(newHorizonsDictionary)); - - - //ghoul::Dictionary dawnDictionary = - //{ - // { std::string("Type"), std::string("Spice") }, - // { std::string("Body"), std::string("DAWN") }, - // { std::string("Reference"), std::string("GALACTIC") }, - // { std::string("Observer"), std::string("SUN") }, - // { std::string("Kernels"), ghoul::Dictionary() } - //}; - //dawnNode->setEphemeris(new SpiceEphemeris(dawnDictionary)); - // - //ghoul::Dictionary vestaDictionary = - //{ - // { std::string("Type"), std::string("Spice") }, - // { std::string("Body"), std::string("VESTA") }, - // { std::string("Reference"), std::string("GALACTIC") }, - // { std::string("Observer"), std::string("SUN") }, - // { std::string("Kernels"), ghoul::Dictionary() } - //}; - //vestaNode->setEphemeris(new SpiceEphemeris(vestaDictionary)); - - - //ghoul::Dictionary newHorizonsGhostDictionary = - //{ - // { std::string("Type"), std::string("Spice") }, - // { std::string("Body"), std::string("NEW HORIZONS") }, - // { std::string("EphmerisGhosting"), std::string("TRUE") }, - // { std::string("Reference"), std::string("GALACTIC") }, - // { std::string("Observer"), std::string("JUPITER BARYCENTER") }, - // { std::string("Kernels"), ghoul::Dictionary() } - //}; - //newHorizonsGhostNode->setEphemeris(new SpiceEphemeris(newHorizonsGhostDictionary)); - - return; - } - if (origin == "Jupiter") { - if (newHorizonsPathNodeJ) { - Renderable* R = newHorizonsPathNodeJ->renderable(); - newHorizonsPathNodeJ->setParent(jupiterBarycenterNode); - nhPath = static_cast(R); - nhPath->calculatePath("JUPITER BARYCENTER"); - } - - jupiterBarycenterNode->setParent(scene()->sceneGraphNode("SolarSystem")); - jupiterBarycenterNode->setEphemeris(new StaticEphemeris); - - solarSystemBarycenterNode->setParent(jupiterBarycenterNode); - if (newHorizonsNode) - newHorizonsNode->setParent(jupiterBarycenterNode); - //newHorizonsTrailNode->setParent(jupiterBarycenterNode); - - //dawnNode->setParent(jupiterBarycenterNode); - //vestaNode->setParent(jupiterBarycenterNode); - - - ghoul::Dictionary solarDictionary = - { - { std::string("Type"), std::string("Spice") }, - { std::string("Body"), std::string("SUN") }, - { std::string("Reference"), std::string("GALACTIC") }, - { std::string("Observer"), std::string("JUPITER BARYCENTER") }, - { std::string("Kernels"), ghoul::Dictionary() } - }; - - ghoul::Dictionary plutoDictionary = - { - { std::string("Type"), std::string("Spice") }, - { std::string("Body"), std::string("PlUTO BARYCENTER") }, - { std::string("Reference"), std::string("GALACTIC") }, - { std::string("Observer"), std::string("JUPITER BARYCENTER") }, - { std::string("Kernels"), ghoul::Dictionary() } - }; - - ghoul::Dictionary newHorizonsDictionary = - { - { std::string("Type"), std::string("Spice") }, - { std::string("Body"), std::string("NEW HORIZONS") }, - { std::string("Reference"), std::string("GALACTIC") }, - { std::string("Observer"), std::string("JUPITER BARYCENTER") }, - { std::string("Kernels"), ghoul::Dictionary() } - }; - solarSystemBarycenterNode->setEphemeris(new SpiceEphemeris(solarDictionary)); - if (plutoBarycenterNode) - plutoBarycenterNode->setEphemeris(new SpiceEphemeris(plutoDictionary)); - if (newHorizonsNode) - newHorizonsNode->setEphemeris(new SpiceEphemeris(newHorizonsDictionary)); - //newHorizonsGhostNode->setParent(jupiterBarycenterNode); - //newHorizonsTrailNode->setEphemeris(new SpiceEphemeris(newHorizonsDictionary)); - - - //ghoul::Dictionary dawnDictionary = - //{ - // { std::string("Type"), std::string("Spice") }, - // { std::string("Body"), std::string("DAWN") }, - // { std::string("Reference"), std::string("GALACTIC") }, - // { std::string("Observer"), std::string("JUPITER BARYCENTER") }, - // { std::string("Kernels"), ghoul::Dictionary() } - //}; - //dawnNode->setEphemeris(new SpiceEphemeris(dawnDictionary)); - // - //ghoul::Dictionary vestaDictionary = - //{ - // { std::string("Type"), std::string("Spice") }, - // { std::string("Body"), std::string("VESTA") }, - // { std::string("Reference"), std::string("GALACTIC") }, - // { std::string("Observer"), std::string("JUPITER BARYCENTER") }, - // { std::string("Kernels"), ghoul::Dictionary() } - //}; - //vestaNode->setEphemeris(new SpiceEphemeris(vestaDictionary)); - - - - //ghoul::Dictionary newHorizonsGhostDictionary = - //{ - // { std::string("Type"), std::string("Spice") }, - // { std::string("Body"), std::string("NEW HORIZONS") }, - // { std::string("EphmerisGhosting"), std::string("TRUE") }, - // { std::string("Reference"), std::string("GALACTIC") }, - // { std::string("Observer"), std::string("JUPITER BARYCENTER") }, - // { std::string("Kernels"), ghoul::Dictionary() } - //}; - //newHorizonsGhostNode->setEphemeris(new SpiceEphemeris(newHorizonsGhostDictionary)); - //newHorizonsGhostNode->setParent(jupiterBarycenterNode); - - - return; - } - //if (origin == "Vesta") { - // - // vestaNode->setParent(scene()->sceneGraphNode("SolarSystem")); - // vestaNode->setEphemeris(new StaticEphemeris); - // - // solarSystemBarycenterNode->setParent(vestaNode); - // newHorizonsNode->setParent(vestaNode); - // - // dawnNode->setParent(vestaNode); - // plutoBarycenterNode->setParent(vestaNode); - // - // - // ghoul::Dictionary plutoDictionary = - // { - // { std::string("Type"), std::string("Spice") }, - // { std::string("Body"), std::string("PLUTO BARYCENTER") }, - // { std::string("Reference"), std::string("GALACTIC") }, - // { std::string("Observer"), std::string("VESTA") }, - // { std::string("Kernels"), ghoul::Dictionary() } - // }; - // ghoul::Dictionary solarDictionary = - // { - // { std::string("Type"), std::string("Spice") }, - // { std::string("Body"), std::string("SUN") }, - // { std::string("Reference"), std::string("GALACTIC") }, - // { std::string("Observer"), std::string("VESTA") }, - // { std::string("Kernels"), ghoul::Dictionary() } - // }; - // - // ghoul::Dictionary jupiterDictionary = - // { - // { std::string("Type"), std::string("Spice") }, - // { std::string("Body"), std::string("JUPITER BARYCENTER") }, - // { std::string("Reference"), std::string("GALACTIC") }, - // { std::string("Observer"), std::string("VESTA") }, - // { std::string("Kernels"), ghoul::Dictionary() } - // }; - // - // solarSystemBarycenterNode->setEphemeris(new SpiceEphemeris(solarDictionary)); - // plutoBarycenterNode->setEphemeris(new SpiceEphemeris(plutoDictionary)); - // jupiterBarycenterNode->setEphemeris(new SpiceEphemeris(jupiterDictionary)); - // - // ghoul::Dictionary newHorizonsDictionary = - // { - // { std::string("Type"), std::string("Spice") }, - // { std::string("Body"), std::string("NEW HORIZONS") }, - // { std::string("Reference"), std::string("GALACTIC") }, - // { std::string("Observer"), std::string("VESTA") }, - // { std::string("Kernels"), ghoul::Dictionary() } - // }; - // newHorizonsNode->setEphemeris(new SpiceEphemeris(newHorizonsDictionary)); - // - // ghoul::Dictionary dawnDictionary = - // { - // { std::string("Type"), std::string("Spice") }, - // { std::string("Body"), std::string("DAWN") }, - // { std::string("Reference"), std::string("GALACTIC") }, - // { std::string("Observer"), std::string("VESTA") }, - // { std::string("Kernels"), ghoul::Dictionary() } - // }; - // dawnNode->setEphemeris(new SpiceEphemeris(dawnDictionary)); - // vestaNode->setEphemeris(new StaticEphemeris); - // - // return; - //} - - if (origin == "67P") { - SceneGraphNode* rosettaNode = scene()->sceneGraphNode("Rosetta"); - SceneGraphNode* cgNode = scene()->sceneGraphNode("67P"); - //jupiterBarycenterNode->setParent(solarSystemBarycenterNode); - //plutoBarycenterNode->setParent(solarSystemBarycenterNode); - solarSystemBarycenterNode->setParent(cgNode); - rosettaNode->setParent(cgNode); - - ghoul::Dictionary solarDictionary = - { - { std::string("Type"), std::string("Spice") }, - { std::string("Body"), std::string("SUN") }, - { std::string("Reference"), std::string("GALACTIC") }, - { std::string("Observer"), std::string("CHURYUMOV-GERASIMENKO") }, - { std::string("Kernels"), ghoul::Dictionary() } - }; - solarSystemBarycenterNode->setEphemeris(new SpiceEphemeris(solarDictionary)); - - ghoul::Dictionary rosettaDictionary = - { - { std::string("Type"), std::string("Spice") }, - { std::string("Body"), std::string("ROSETTA") }, - { std::string("Reference"), std::string("GALACTIC") }, - { std::string("Observer"), std::string("CHURYUMOV-GERASIMENKO") }, - { std::string("Kernels"), ghoul::Dictionary() } - }; - - cgNode->setParent(scene()->sceneGraphNode("SolarSystem")); - rosettaNode->setEphemeris(new SpiceEphemeris(rosettaDictionary)); - cgNode->setEphemeris(new StaticEphemeris); - - return; - - } - - LFATAL("This function is being misused with an argument of '" << origin << "'"); +// SceneGraphNode* solarSystemBarycenterNode = scene()->sceneGraphNode("SolarSystemBarycenter"); +// SceneGraphNode* plutoBarycenterNode = scene()->sceneGraphNode("PlutoBarycenter"); +// SceneGraphNode* newHorizonsNode = scene()->sceneGraphNode("NewHorizons"); +// SceneGraphNode* newHorizonsPathNodeJ = scene()->sceneGraphNode("NewHorizonsPathJupiter"); +// SceneGraphNode* newHorizonsPathNodeP = scene()->sceneGraphNode("NewHorizonsPathPluto"); +//// SceneGraphNode* cg67pNode = scene()->sceneGraphNode("67P"); +//// SceneGraphNode* rosettaNode = scene()->sceneGraphNode("Rosetta"); +// +// RenderablePath* nhPath; +// +// SceneGraphNode* jupiterBarycenterNode = scene()->sceneGraphNode("JupiterBarycenter"); +// +// //SceneGraphNode* newHorizonsGhostNode = scene()->sceneGraphNode("NewHorizonsGhost"); +// //SceneGraphNode* dawnNode = scene()->sceneGraphNode("Dawn"); +// //SceneGraphNode* vestaNode = scene()->sceneGraphNode("Vesta"); +// +// // if (solarSystemBarycenterNode == nullptr || plutoBarycenterNode == nullptr || +// //jupiterBarycenterNode == nullptr) { +// // LERROR("Necessary nodes does not exist"); +// //return; +// // } +// +// if (origin == "Pluto") { +// if (newHorizonsPathNodeP) { +// Renderable* R = newHorizonsPathNodeP->renderable(); +// newHorizonsPathNodeP->setParent(plutoBarycenterNode); +// nhPath = static_cast(R); +// nhPath->calculatePath("PLUTO BARYCENTER"); +// } +// +// plutoBarycenterNode->setParent(scene()->sceneGraphNode("SolarSystem")); +// plutoBarycenterNode->setEphemeris(new StaticEphemeris); +// +// solarSystemBarycenterNode->setParent(plutoBarycenterNode); +// newHorizonsNode->setParent(plutoBarycenterNode); +// //newHorizonsGhostNode->setParent(plutoBarycenterNode); +// +// //dawnNode->setParent(plutoBarycenterNode); +// //vestaNode->setParent(plutoBarycenterNode); +// +// //newHorizonsTrailNode->setParent(plutoBarycenterNode); +// ghoul::Dictionary solarDictionary = +// { +// { std::string("Type"), std::string("Spice") }, +// { std::string("Body"), std::string("SUN") }, +// { std::string("Reference"), std::string("GALACTIC") }, +// { std::string("Observer"), std::string("PLUTO BARYCENTER") }, +// { std::string("Kernels"), ghoul::Dictionary() } +// }; +// +// ghoul::Dictionary jupiterDictionary = +// { +// { std::string("Type"), std::string("Spice") }, +// { std::string("Body"), std::string("JUPITER BARYCENTER") }, +// { std::string("Reference"), std::string("GALACTIC") }, +// { std::string("Observer"), std::string("PLUTO BARYCENTER") }, +// { std::string("Kernels"), ghoul::Dictionary() } +// }; +// +// ghoul::Dictionary newHorizonsDictionary = +// { +// { std::string("Type"), std::string("Spice") }, +// { std::string("Body"), std::string("NEW HORIZONS") }, +// { std::string("Reference"), std::string("GALACTIC") }, +// { std::string("Observer"), std::string("PLUTO BARYCENTER") }, +// { std::string("Kernels"), ghoul::Dictionary() } +// }; +// +// solarSystemBarycenterNode->setEphemeris(new SpiceEphemeris(solarDictionary)); +// jupiterBarycenterNode->setEphemeris(new SpiceEphemeris(jupiterDictionary)); +// newHorizonsNode->setEphemeris(new SpiceEphemeris(newHorizonsDictionary)); +// //newHorizonsTrailNode->setEphemeris(new SpiceEphemeris(newHorizonsDictionary)); +// +// +// //ghoul::Dictionary dawnDictionary = +// //{ +// // { std::string("Type"), std::string("Spice") }, +// // { std::string("Body"), std::string("DAWN") }, +// // { std::string("Reference"), std::string("GALACTIC") }, +// // { std::string("Observer"), std::string("PLUTO BARYCENTER") }, +// // { std::string("Kernels"), ghoul::Dictionary() } +// //}; +// //dawnNode->setEphemeris(new SpiceEphemeris(dawnDictionary)); +// // +// //ghoul::Dictionary vestaDictionary = +// //{ +// // { std::string("Type"), std::string("Spice") }, +// // { std::string("Body"), std::string("VESTA") }, +// // { std::string("Reference"), std::string("GALACTIC") }, +// // { std::string("Observer"), std::string("PLUTO BARYCENTER") }, +// // { std::string("Kernels"), ghoul::Dictionary() } +// //}; +// //vestaNode->setEphemeris(new SpiceEphemeris(vestaDictionary)); +// +// +// //ghoul::Dictionary newHorizonsGhostDictionary = +// //{ +// // { std::string("Type"), std::string("Spice") }, +// // { std::string("Body"), std::string("NEW HORIZONS") }, +// // { std::string("EphmerisGhosting"), std::string("TRUE") }, +// // { std::string("Reference"), std::string("GALACTIC") }, +// // { std::string("Observer"), std::string("PLUTO BARYCENTER") }, +// // { std::string("Kernels"), ghoul::Dictionary() } +// //}; +// //newHorizonsGhostNode->setEphemeris(new SpiceEphemeris(newHorizonsGhostDictionary)); +// +// return; +// } +// if (origin == "Sun") { +// solarSystemBarycenterNode->setParent(scene()->sceneGraphNode("SolarSystem")); +// +// if (plutoBarycenterNode) +// plutoBarycenterNode->setParent(solarSystemBarycenterNode); +// jupiterBarycenterNode->setParent(solarSystemBarycenterNode); +// if (newHorizonsNode) +// newHorizonsNode->setParent(solarSystemBarycenterNode); +// //newHorizonsGhostNode->setParent(solarSystemBarycenterNode); +// +// //newHorizonsTrailNode->setParent(solarSystemBarycenterNode); +// //dawnNode->setParent(solarSystemBarycenterNode); +// //vestaNode->setParent(solarSystemBarycenterNode); +// +// ghoul::Dictionary plutoDictionary = +// { +// { std::string("Type"), std::string("Spice") }, +// { std::string("Body"), std::string("PLUTO BARYCENTER") }, +// { std::string("Reference"), std::string("GALACTIC") }, +// { std::string("Observer"), std::string("SUN") }, +// { std::string("Kernels"), ghoul::Dictionary() } +// }; +// ghoul::Dictionary jupiterDictionary = +// { +// { std::string("Type"), std::string("Spice") }, +// { std::string("Body"), std::string("JUPITER BARYCENTER") }, +// { std::string("Reference"), std::string("GALACTIC") }, +// { std::string("Observer"), std::string("SUN") }, +// { std::string("Kernels"), ghoul::Dictionary() } +// }; +// +// solarSystemBarycenterNode->setEphemeris(new StaticEphemeris); +// jupiterBarycenterNode->setEphemeris(new SpiceEphemeris(jupiterDictionary)); +// if (plutoBarycenterNode) +// plutoBarycenterNode->setEphemeris(new SpiceEphemeris(plutoDictionary)); +// +// ghoul::Dictionary newHorizonsDictionary = +// { +// { std::string("Type"), std::string("Spice") }, +// { std::string("Body"), std::string("NEW HORIZONS") }, +// { std::string("Reference"), std::string("GALACTIC") }, +// { std::string("Observer"), std::string("SUN") }, +// { std::string("Kernels"), ghoul::Dictionary() } +// }; +// if (newHorizonsNode) +// newHorizonsNode->setEphemeris(new SpiceEphemeris(newHorizonsDictionary)); +// //newHorizonsTrailNode->setEphemeris(new SpiceEphemeris(newHorizonsDictionary)); +// +// +// //ghoul::Dictionary dawnDictionary = +// //{ +// // { std::string("Type"), std::string("Spice") }, +// // { std::string("Body"), std::string("DAWN") }, +// // { std::string("Reference"), std::string("GALACTIC") }, +// // { std::string("Observer"), std::string("SUN") }, +// // { std::string("Kernels"), ghoul::Dictionary() } +// //}; +// //dawnNode->setEphemeris(new SpiceEphemeris(dawnDictionary)); +// // +// //ghoul::Dictionary vestaDictionary = +// //{ +// // { std::string("Type"), std::string("Spice") }, +// // { std::string("Body"), std::string("VESTA") }, +// // { std::string("Reference"), std::string("GALACTIC") }, +// // { std::string("Observer"), std::string("SUN") }, +// // { std::string("Kernels"), ghoul::Dictionary() } +// //}; +// //vestaNode->setEphemeris(new SpiceEphemeris(vestaDictionary)); +// +// +// //ghoul::Dictionary newHorizonsGhostDictionary = +// //{ +// // { std::string("Type"), std::string("Spice") }, +// // { std::string("Body"), std::string("NEW HORIZONS") }, +// // { std::string("EphmerisGhosting"), std::string("TRUE") }, +// // { std::string("Reference"), std::string("GALACTIC") }, +// // { std::string("Observer"), std::string("JUPITER BARYCENTER") }, +// // { std::string("Kernels"), ghoul::Dictionary() } +// //}; +// //newHorizonsGhostNode->setEphemeris(new SpiceEphemeris(newHorizonsGhostDictionary)); +// +// return; +// } +// if (origin == "Jupiter") { +// if (newHorizonsPathNodeJ) { +// Renderable* R = newHorizonsPathNodeJ->renderable(); +// newHorizonsPathNodeJ->setParent(jupiterBarycenterNode); +// nhPath = static_cast(R); +// nhPath->calculatePath("JUPITER BARYCENTER"); +// } +// +// jupiterBarycenterNode->setParent(scene()->sceneGraphNode("SolarSystem")); +// jupiterBarycenterNode->setEphemeris(new StaticEphemeris); +// +// solarSystemBarycenterNode->setParent(jupiterBarycenterNode); +// if (newHorizonsNode) +// newHorizonsNode->setParent(jupiterBarycenterNode); +// //newHorizonsTrailNode->setParent(jupiterBarycenterNode); +// +// //dawnNode->setParent(jupiterBarycenterNode); +// //vestaNode->setParent(jupiterBarycenterNode); +// +// +// ghoul::Dictionary solarDictionary = +// { +// { std::string("Type"), std::string("Spice") }, +// { std::string("Body"), std::string("SUN") }, +// { std::string("Reference"), std::string("GALACTIC") }, +// { std::string("Observer"), std::string("JUPITER BARYCENTER") }, +// { std::string("Kernels"), ghoul::Dictionary() } +// }; +// +// ghoul::Dictionary plutoDictionary = +// { +// { std::string("Type"), std::string("Spice") }, +// { std::string("Body"), std::string("PlUTO BARYCENTER") }, +// { std::string("Reference"), std::string("GALACTIC") }, +// { std::string("Observer"), std::string("JUPITER BARYCENTER") }, +// { std::string("Kernels"), ghoul::Dictionary() } +// }; +// +// ghoul::Dictionary newHorizonsDictionary = +// { +// { std::string("Type"), std::string("Spice") }, +// { std::string("Body"), std::string("NEW HORIZONS") }, +// { std::string("Reference"), std::string("GALACTIC") }, +// { std::string("Observer"), std::string("JUPITER BARYCENTER") }, +// { std::string("Kernels"), ghoul::Dictionary() } +// }; +// solarSystemBarycenterNode->setEphemeris(new SpiceEphemeris(solarDictionary)); +// if (plutoBarycenterNode) +// plutoBarycenterNode->setEphemeris(new SpiceEphemeris(plutoDictionary)); +// if (newHorizonsNode) +// newHorizonsNode->setEphemeris(new SpiceEphemeris(newHorizonsDictionary)); +// //newHorizonsGhostNode->setParent(jupiterBarycenterNode); +// //newHorizonsTrailNode->setEphemeris(new SpiceEphemeris(newHorizonsDictionary)); +// +// +// //ghoul::Dictionary dawnDictionary = +// //{ +// // { std::string("Type"), std::string("Spice") }, +// // { std::string("Body"), std::string("DAWN") }, +// // { std::string("Reference"), std::string("GALACTIC") }, +// // { std::string("Observer"), std::string("JUPITER BARYCENTER") }, +// // { std::string("Kernels"), ghoul::Dictionary() } +// //}; +// //dawnNode->setEphemeris(new SpiceEphemeris(dawnDictionary)); +// // +// //ghoul::Dictionary vestaDictionary = +// //{ +// // { std::string("Type"), std::string("Spice") }, +// // { std::string("Body"), std::string("VESTA") }, +// // { std::string("Reference"), std::string("GALACTIC") }, +// // { std::string("Observer"), std::string("JUPITER BARYCENTER") }, +// // { std::string("Kernels"), ghoul::Dictionary() } +// //}; +// //vestaNode->setEphemeris(new SpiceEphemeris(vestaDictionary)); +// +// +// +// //ghoul::Dictionary newHorizonsGhostDictionary = +// //{ +// // { std::string("Type"), std::string("Spice") }, +// // { std::string("Body"), std::string("NEW HORIZONS") }, +// // { std::string("EphmerisGhosting"), std::string("TRUE") }, +// // { std::string("Reference"), std::string("GALACTIC") }, +// // { std::string("Observer"), std::string("JUPITER BARYCENTER") }, +// // { std::string("Kernels"), ghoul::Dictionary() } +// //}; +// //newHorizonsGhostNode->setEphemeris(new SpiceEphemeris(newHorizonsGhostDictionary)); +// //newHorizonsGhostNode->setParent(jupiterBarycenterNode); +// +// +// return; +// } +// //if (origin == "Vesta") { +// // +// // vestaNode->setParent(scene()->sceneGraphNode("SolarSystem")); +// // vestaNode->setEphemeris(new StaticEphemeris); +// // +// // solarSystemBarycenterNode->setParent(vestaNode); +// // newHorizonsNode->setParent(vestaNode); +// // +// // dawnNode->setParent(vestaNode); +// // plutoBarycenterNode->setParent(vestaNode); +// // +// // +// // ghoul::Dictionary plutoDictionary = +// // { +// // { std::string("Type"), std::string("Spice") }, +// // { std::string("Body"), std::string("PLUTO BARYCENTER") }, +// // { std::string("Reference"), std::string("GALACTIC") }, +// // { std::string("Observer"), std::string("VESTA") }, +// // { std::string("Kernels"), ghoul::Dictionary() } +// // }; +// // ghoul::Dictionary solarDictionary = +// // { +// // { std::string("Type"), std::string("Spice") }, +// // { std::string("Body"), std::string("SUN") }, +// // { std::string("Reference"), std::string("GALACTIC") }, +// // { std::string("Observer"), std::string("VESTA") }, +// // { std::string("Kernels"), ghoul::Dictionary() } +// // }; +// // +// // ghoul::Dictionary jupiterDictionary = +// // { +// // { std::string("Type"), std::string("Spice") }, +// // { std::string("Body"), std::string("JUPITER BARYCENTER") }, +// // { std::string("Reference"), std::string("GALACTIC") }, +// // { std::string("Observer"), std::string("VESTA") }, +// // { std::string("Kernels"), ghoul::Dictionary() } +// // }; +// // +// // solarSystemBarycenterNode->setEphemeris(new SpiceEphemeris(solarDictionary)); +// // plutoBarycenterNode->setEphemeris(new SpiceEphemeris(plutoDictionary)); +// // jupiterBarycenterNode->setEphemeris(new SpiceEphemeris(jupiterDictionary)); +// // +// // ghoul::Dictionary newHorizonsDictionary = +// // { +// // { std::string("Type"), std::string("Spice") }, +// // { std::string("Body"), std::string("NEW HORIZONS") }, +// // { std::string("Reference"), std::string("GALACTIC") }, +// // { std::string("Observer"), std::string("VESTA") }, +// // { std::string("Kernels"), ghoul::Dictionary() } +// // }; +// // newHorizonsNode->setEphemeris(new SpiceEphemeris(newHorizonsDictionary)); +// // +// // ghoul::Dictionary dawnDictionary = +// // { +// // { std::string("Type"), std::string("Spice") }, +// // { std::string("Body"), std::string("DAWN") }, +// // { std::string("Reference"), std::string("GALACTIC") }, +// // { std::string("Observer"), std::string("VESTA") }, +// // { std::string("Kernels"), ghoul::Dictionary() } +// // }; +// // dawnNode->setEphemeris(new SpiceEphemeris(dawnDictionary)); +// // vestaNode->setEphemeris(new StaticEphemeris); +// // +// // return; +// //} +// +// if (origin == "67P") { +// SceneGraphNode* rosettaNode = scene()->sceneGraphNode("Rosetta"); +// SceneGraphNode* cgNode = scene()->sceneGraphNode("67P"); +// //jupiterBarycenterNode->setParent(solarSystemBarycenterNode); +// //plutoBarycenterNode->setParent(solarSystemBarycenterNode); +// solarSystemBarycenterNode->setParent(cgNode); +// rosettaNode->setParent(cgNode); +// +// ghoul::Dictionary solarDictionary = +// { +// { std::string("Type"), std::string("Spice") }, +// { std::string("Body"), std::string("SUN") }, +// { std::string("Reference"), std::string("GALACTIC") }, +// { std::string("Observer"), std::string("CHURYUMOV-GERASIMENKO") }, +// { std::string("Kernels"), ghoul::Dictionary() } +// }; +// solarSystemBarycenterNode->setEphemeris(new SpiceEphemeris(solarDictionary)); +// +// ghoul::Dictionary rosettaDictionary = +// { +// { std::string("Type"), std::string("Spice") }, +// { std::string("Body"), std::string("ROSETTA") }, +// { std::string("Reference"), std::string("GALACTIC") }, +// { std::string("Observer"), std::string("CHURYUMOV-GERASIMENKO") }, +// { std::string("Kernels"), ghoul::Dictionary() } +// }; +// +// cgNode->setParent(scene()->sceneGraphNode("SolarSystem")); +// rosettaNode->setEphemeris(new SpiceEphemeris(rosettaDictionary)); +// cgNode->setEphemeris(new StaticEphemeris); +// +// return; +// +// } +// +// LFATAL("This function is being misused with an argument of '" << origin << "'"); } void RenderEngine::setShowFrameNumber(bool enabled){ @@ -1287,16 +1278,18 @@ void RenderEngine::renderInformation() { if (_fontDate) { glm::vec2 penPosition = glm::vec2( 10.f, - OsEng.windowWrapper().viewportPixelCoordinates().w + fontResolution().y + //OsEng.windowWrapper().viewportPixelCoordinates().w ); penPosition.y -= _fontDate->height(); - RenderFontCr(*_fontDate, - penPosition, - "Date: %s", - Time::ref().UTC().c_str() + if (_showInfo && _fontDate) { + RenderFontCr(*_fontDate, + penPosition, + "Date: %s", + Time::ref().UTC().c_str() ); - + } if (_showInfo && _fontInfo) { RenderFontCr(*_fontInfo, penPosition, @@ -1304,7 +1297,8 @@ void RenderEngine::renderInformation() { Time::ref().deltaTime() ); - switch (_frametimeType) { + FrametimeType frametimeType = FrametimeType(_frametimeType.value()); + switch (frametimeType) { case FrametimeType::DtTimeAvg: RenderFontCr(*_fontInfo, penPosition, @@ -1335,6 +1329,46 @@ void RenderEngine::renderInformation() { break; } + ParallelConnection::Status status = OsEng.parallelConnection().status(); + size_t nConnections = OsEng.parallelConnection().nConnections(); + const std::string& hostName = OsEng.parallelConnection().hostName(); + + std::string connectionInfo = ""; + int nClients = nConnections; + if (status == ParallelConnection::Status::Host) { + nClients--; + if (nClients == 1) { + connectionInfo = "Hosting session with 1 client"; + } else { + connectionInfo = "Hosting session with " + std::to_string(nClients) + " clients"; + } + } else if (status == ParallelConnection::Status::ClientWithHost) { + nClients--; + connectionInfo = "Session hosted by '" + hostName + "'"; + } else if (status == ParallelConnection::Status::ClientWithoutHost) { + connectionInfo = "Host is disconnected"; + } + + if (status == ParallelConnection::Status::ClientWithHost || + status == ParallelConnection::Status::ClientWithoutHost) { + connectionInfo += "\n"; + if (nClients > 2) { + connectionInfo += "You and " + std::to_string(nClients - 1) + " more clients are tuned in"; + } else if (nClients == 2) { + connectionInfo += "You and " + std::to_string(nClients - 1) + " more client are tuned in"; + } else if (nClients == 1) { + connectionInfo += "You are the only client"; + } + } + + if (connectionInfo != "") { + RenderFontCr(*_fontInfo, + penPosition, + connectionInfo.c_str() + ); + } + + #ifdef OPENSPACE_MODULE_NEWHORIZONS_ENABLED //<<<<<<< HEAD bool hasNewHorizons = scene()->sceneGraphNode("NewHorizons"); @@ -1364,13 +1398,14 @@ void RenderEngine::renderInformation() { // Add spacing RenderFontCr(*_fontInfo, penPosition, nonCurrentMissionColor, " "); - std::vector phaseTrace = mission.phaseTrace(currentTime); + auto phaseTrace = mission.phaseTrace(currentTime); if (phaseTrace.size()) { - std::string title = "Current Mission Phase: " + phaseTrace.back()->name(); + const MissionPhase& phase = phaseTrace.back().get(); + std::string title = "Current Mission Phase: " + phase.name(); RenderFontCr(*_fontInfo, penPosition, missionProgressColor, title.c_str()); - double remaining = phaseTrace.back()->timeRange().end - currentTime; - float t = static_cast(1.0 - remaining / phaseTrace.back()->timeRange().duration()); + double remaining = phase.timeRange().end - currentTime; + float t = static_cast(1.0 - remaining / phase.timeRange().duration()); std::string progress = progressToStr(25, t); //RenderFontCr(*_fontInfo, penPosition, missionProgressColor, // "%.0f s %s %.1f %%", remaining, progress.c_str(), t * 100); @@ -1417,7 +1452,7 @@ void RenderEngine::renderInformation() { // last-in-first-out from the stack, so add them in reversed order. int indexLastPhase = phase->phases().size() - 1; for (int i = indexLastPhase; 0 <= i; --i) { - S.push({ &phase->phase(i), depth + 1 }); + S.push({ &phase->phases()[i], depth + 1 }); } } } @@ -1660,7 +1695,7 @@ void RenderEngine::renderScreenLog() { if (alpha <= 0.0) break; - const std::string lvl = "(" + ghoul::logging::LogManager::stringFromLevel(e->level) + ")"; + const std::string lvl = "(" + ghoul::logging::stringFromLevel(e->level) + ")"; const std::string& message = e->message.substr(0, msg_length); nr += std::count(message.begin(), message.end(), '\n'); @@ -1673,13 +1708,13 @@ void RenderEngine::renderScreenLog() { e->category.length() > 20 ? "..." : ""); // Pad category with "..." if exceeds category_length glm::vec4 color = white; - if (e->level == ghoul::logging::LogManager::LogLevel::Debug) + if (e->level == ghoul::logging::LogLevel::Debug) color = green; - if (e->level == ghoul::logging::LogManager::LogLevel::Warning) + if (e->level == ghoul::logging::LogLevel::Warning) color = yellow; - if (e->level == ghoul::logging::LogManager::LogLevel::Error) + if (e->level == ghoul::logging::LogLevel::Error) color = red; - if (e->level == ghoul::logging::LogManager::LogLevel::Fatal) + if (e->level == ghoul::logging::LogLevel::Fatal) color = blue; // const float font_with_light = 5; @@ -1699,9 +1734,7 @@ void RenderEngine::renderScreenLog() { } std::vector RenderEngine::getSyncables(){ - std::vector syncables = _mainCamera->getSyncables(); - syncables.push_back(&_onScreenInformation); - return syncables; + return _mainCamera->getSyncables(); } void RenderEngine::sortScreenspaceRenderables() { diff --git a/src/rendering/renderengine_lua.inl b/src/rendering/renderengine_lua.inl index de2aa3b519..4134ce44fc 100644 --- a/src/rendering/renderengine_lua.inl +++ b/src/rendering/renderengine_lua.inl @@ -105,40 +105,6 @@ int showRenderInformation(lua_State* L) { return 0; } -/** -* \ingroup LuaScripts -* toggleFramerateType(bool): -* Cycle through showing FPS or Average Frametime in heads up info -*/ -int toggleFrametimeType(lua_State* L) { - int nArguments = lua_gettop(L); - if (nArguments != 1) - return luaL_error(L, "Expected %i arguments, got %i", 1, nArguments); - - const int type = lua_type(L, -1); - if (type != LUA_TNUMBER) - return luaL_error(L, "Expected argument of type 'number'"); - int t = lua_tonumber(L, -1); - OsEng.renderEngine().toggleFrametimeType(t); - return 0; -} - -/** -* \ingroup LuaScripts -* visualizeABuffer(bool): -* Toggle the visualization of the ABuffer -*/ -int setPerformanceMeasurement(lua_State* L) { - int nArguments = lua_gettop(L); - if (nArguments != 1) { - return luaL_error(L, "Expected %i arguments, got %i", 1, nArguments); - } - - bool b = lua_toboolean(L, -1) != 0; - OsEng.renderEngine().setPerformanceMeasurements(b); - return 0; -} - /** * \ingroup LuaScripts * toggleFade(float): diff --git a/src/rendering/screenspacerenderable.cpp b/src/rendering/screenspacerenderable.cpp index c95734a2b9..a48ed62025 100644 --- a/src/rendering/screenspacerenderable.cpp +++ b/src/rendering/screenspacerenderable.cpp @@ -159,7 +159,7 @@ ScreenSpaceRenderable::ScreenSpaceRenderable(const ghoul::Dictionary& dictionary _delete.onChange([this](){ std::string script = "openspace.unregisterScreenSpaceRenderable('" + name() + "');"; - OsEng.scriptEngine().queueScript(script); + OsEng.scriptEngine().queueScript(script, scripting::ScriptEngine::RemoteScripting::Yes); }); } diff --git a/src/scene/rotation.cpp b/src/scene/rotation.cpp index a4d77d54ff..ac814c8ec2 100644 --- a/src/scene/rotation.cpp +++ b/src/scene/rotation.cpp @@ -69,7 +69,9 @@ Rotation* Rotation::createFromDictionary(const ghoul::Dictionary& dictionary) { return result; } -Rotation::Rotation() {} +Rotation::Rotation() { + setName("Rotation"); +} Rotation::Rotation(const ghoul::Dictionary& dictionary) {} @@ -79,6 +81,10 @@ bool Rotation::initialize() { return true; } +const glm::dmat3& Rotation::matrix() const { + return _matrix; +} + void Rotation::update(const UpdateData& data) {} } // namespace openspace \ No newline at end of file diff --git a/src/scene/scale.cpp b/src/scene/scale.cpp index c58c83ead6..ef43e0b4f6 100644 --- a/src/scene/scale.cpp +++ b/src/scene/scale.cpp @@ -64,6 +64,7 @@ Scale* Scale::createFromDictionary(const ghoul::Dictionary& dictionary) { auto factory = FactoryManager::ref().factory(); Scale* result = factory->create(scaleType, dictionary); + result->setName("Scale"); if (result == nullptr) { LERROR("Failed creating Scale object of type '" << scaleType << "'"); return nullptr; diff --git a/src/scene/scene.cpp b/src/scene/scene.cpp index 6b03045220..7b0185b8a6 100644 --- a/src/scene/scene.cpp +++ b/src/scene/scene.cpp @@ -24,6 +24,7 @@ #include +#include #include #include #include @@ -46,11 +47,12 @@ #include #include +#include #include #include +#include #include #include -#include #ifdef OPENSPACE_MODULE_ONSCREENGUI_ENABLED #include @@ -68,6 +70,14 @@ namespace { const std::string KeyFocusObject = "Focus"; const std::string KeyPositionObject = "Position"; const std::string KeyViewOffset = "Offset"; + + const std::string MainTemplateFilename = "${OPENSPACE_DATA}/web/properties/main.hbs"; + const std::string PropertyOwnerTemplateFilename = "${OPENSPACE_DATA}/web/properties/propertyowner.hbs"; + const std::string PropertyTemplateFilename = "${OPENSPACE_DATA}/web/properties/property.hbs"; + const std::string HandlebarsFilename = "${OPENSPACE_DATA}/web/common/handlebars-v4.0.5.js"; + const std::string JsFilename = "${OPENSPACE_DATA}/web/properties/script.js"; + const std::string BootstrapFilename = "${OPENSPACE_DATA}/web/common/bootstrap.min.css"; + const std::string CssFilename = "${OPENSPACE_DATA}/web/common/style.css"; } namespace openspace { @@ -96,7 +106,7 @@ void Scene::update(const UpdateData& data) { // Reset the InteractionManager to Orbital/default mode // TODO: Decide if it belongs in the scene and/or how it gets reloaded - OsEng.interactionHandler().setInteractionMode("Orbital"); + //OsEng.interactionHandler().setInteractionMode("Orbital"); // After loading the scene, the keyboard bindings have been set const std::string KeyboardShortcutsType = @@ -154,12 +164,6 @@ void Scene::render(const RenderData& data, RendererTasks& tasks) { } } -void Scene::postRender(const RenderData& data) { - for (SceneGraphNode* node : _graph.nodes()) { - node->postRender(data); - } -} - void Scene::scheduleLoadSceneFile(const std::string& sceneDescriptionFilePath) { _sceneGraphToLoad = sceneDescriptionFilePath; } @@ -268,7 +272,7 @@ bool Scene::loadSceneInternal(const std::string& sceneDescriptionFilePath) { OsEng.configurationManager().getValue(KeyPropertyDocumentationFile, propertyDocumentationFile); propertyDocumentationFile = absPath(propertyDocumentationFile); - writePropertyDocumentation(propertyDocumentationFile, propertyDocumentationType); + writePropertyDocumentation(propertyDocumentationFile, propertyDocumentationType, sceneDescriptionFilePath); } @@ -442,7 +446,7 @@ SceneGraph& Scene::sceneGraph() { return _graph; } -void Scene::writePropertyDocumentation(const std::string& filename, const std::string& type) { +void Scene::writePropertyDocumentation(const std::string& filename, const std::string& type, const std::string& sceneFilename) { LDEBUG("Writing documentation for properties"); if (type == "text") { std::ofstream file; @@ -469,7 +473,37 @@ void Scene::writePropertyDocumentation(const std::string& filename, const std::s file.exceptions(~std::ofstream::goodbit); file.open(filename); -#ifdef JSON + + std::ifstream handlebarsInput(absPath(HandlebarsFilename)); + std::ifstream jsInput(absPath(JsFilename)); + + std::string jsContent; + std::back_insert_iterator jsInserter(jsContent); + + std::copy(std::istreambuf_iterator{handlebarsInput}, std::istreambuf_iterator(), jsInserter); + std::copy(std::istreambuf_iterator{jsInput}, std::istreambuf_iterator(), jsInserter); + + std::ifstream bootstrapInput(absPath(BootstrapFilename)); + std::ifstream cssInput(absPath(CssFilename)); + + std::string cssContent; + std::back_insert_iterator cssInserter(cssContent); + + std::copy(std::istreambuf_iterator{bootstrapInput}, std::istreambuf_iterator(), cssInserter); + std::copy(std::istreambuf_iterator{cssInput}, std::istreambuf_iterator(), cssInserter); + + std::ifstream mainTemplateInput(absPath(MainTemplateFilename)); + std::string mainTemplateContent{ std::istreambuf_iterator{mainTemplateInput}, + std::istreambuf_iterator{} }; + + std::ifstream propertyOwnerTemplateInput(absPath(PropertyOwnerTemplateFilename)); + std::string propertyOwnerTemplateContent{ std::istreambuf_iterator{propertyOwnerTemplateInput}, + std::istreambuf_iterator{} }; + + std::ifstream propertyTemplateInput(absPath(PropertyTemplateFilename)); + std::string propertyTemplateContent{ std::istreambuf_iterator{propertyTemplateInput}, + std::istreambuf_iterator{} }; + // Create JSON std::function createJson = [&createJson](properties::PropertyOwner* owner) -> std::string @@ -479,22 +513,30 @@ void Scene::writePropertyDocumentation(const std::string& filename, const std::s json << "\"name\": \"" << owner->name() << "\","; json << "\"properties\": ["; - for (properties::Property* p : owner->properties()) { + auto properties = owner->properties(); + for (properties::Property* p : properties) { json << "{"; json << "\"id\": \"" << p->identifier() << "\","; json << "\"type\": \"" << p->className() << "\","; json << "\"fullyQualifiedId\": \"" << p->fullyQualifiedIdentifier() << "\","; - json << "\"guiName\": \"" << p->guiName() << "\","; - json << "},"; + json << "\"guiName\": \"" << p->guiName() << "\""; + json << "}"; + if (p != properties.back()) { + json << ","; + } } json << "],"; - json << "\"propertyOwner\": ["; - for (properties::PropertyOwner* o : owner->propertySubOwners()) { + json << "\"propertyOwners\": ["; + auto propertyOwners = owner->propertySubOwners(); + for (properties::PropertyOwner* o : propertyOwners) { json << createJson(o); + if (o != propertyOwners.back()) { + json << ","; + } } - json << "],"; - json << "},"; + json << "]"; + json << "}"; return json.str(); }; @@ -502,15 +544,60 @@ void Scene::writePropertyDocumentation(const std::string& filename, const std::s std::stringstream json; json << "["; - for (SceneGraphNode* node : _graph.nodes()) { - json << createJson(node); + std::vector nodes = _graph.nodes(); + if (!nodes.empty()) { + json << std::accumulate( + std::next(nodes.begin()), + nodes.end(), + createJson(*nodes.begin()), + [createJson](std::string a, SceneGraphNode* n) { + return a + "," + createJson(n); + } + ); } json << "]"; - std::string jsonText = json.str(); -#else + std::string jsonString = ""; + for (const char& c : json.str()) { + if (c == '\'') { + jsonString += "\\'"; + } else { + jsonString += c; + } + } + std::stringstream html; + html << "\n" + << "\n" + << "\t\n" + << "\t\t\n" + << "\t\t\n" + << "\t\t\n" + << "\t\n" + << "\t\n" + << "\t\tDocumentation\n" + << "\t\n" + << "\t\n" + << "\t\n" + << "\n"; + + /* + html << "\n" << "\t\n" << "\t\tProperties\n" @@ -546,9 +633,8 @@ void Scene::writePropertyDocumentation(const std::string& filename, const std::s << "
\n" << ";"; + */ file << html.str(); -#endif - } else LERROR("Undefined type '" << type << "' for Property documentation"); @@ -582,7 +668,6 @@ scripting::LuaLibrary Scene::luaLibrary() { "Sets a property identified by the URI in " "the first argument. The second argument can be any type, but it has to " "match the type that the property expects.", - true }, { "getPropertyValue", diff --git a/src/scene/scene_doc.inl b/src/scene/scene_doc.inl index 9b069572c1..5968782602 100644 --- a/src/scene/scene_doc.inl +++ b/src/scene/scene_doc.inl @@ -31,6 +31,7 @@ Documentation Scene::Documentation() { return { "Scene Description", + "core_scene", { { "ScenePath", diff --git a/src/scene/scene_lua.inl b/src/scene/scene_lua.inl index 4733a8f588..68d7b3bd4e 100644 --- a/src/scene/scene_lua.inl +++ b/src/scene/scene_lua.inl @@ -52,10 +52,10 @@ void applyRegularExpression(lua_State* L, std::regex regex, std::vectorgetStringValue(value); - OsEng.parallelConnection().scriptMessage( +/* OsEng.parallelConnection().scriptMessage( prop->fullyQualifiedIdentifier(), value - ); + );*/ } } @@ -101,7 +101,7 @@ int property_setValueSingle(lua_State* L) { //ensure properties are synced over parallel connection std::string value; prop->getStringValue(value); - OsEng.parallelConnection().scriptMessage(prop->fullyQualifiedIdentifier(), value); + //OsEng.parallelConnection().scriptMessage(prop->fullyQualifiedIdentifier(), value); } return 0; diff --git a/src/scene/scenegraphnode.cpp b/src/scene/scenegraphnode.cpp index e3334e178d..c7d58b84ea 100644 --- a/src/scene/scenegraphnode.cpp +++ b/src/scene/scenegraphnode.cpp @@ -22,7 +22,6 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -// open space includes #include #include @@ -31,7 +30,6 @@ #include #include -// ghoul includes #include #include #include @@ -39,7 +37,7 @@ #include #include -#include +#include #include #include @@ -77,13 +75,7 @@ SceneGraphNode* SceneGraphNode::createFromDictionary(const ghoul::Dictionary& di SceneGraphNode* result = new SceneGraphNode; - if (!dictionary.hasValue(KeyName)) { - LERROR("SceneGraphNode did not contain a '" << KeyName << "' key"); - delete result; - return nullptr; - } - std::string name; - dictionary.getValue(KeyName, name); + std::string name = dictionary.value(KeyName); result->setName(name); if (dictionary.hasValue(KeyRenderable)) { @@ -106,60 +98,48 @@ SceneGraphNode* SceneGraphNode::createFromDictionary(const ghoul::Dictionary& di if (dictionary.hasKey(keyTransformTranslation)) { ghoul::Dictionary translationDictionary; dictionary.getValue(keyTransformTranslation, translationDictionary); - result->_ephemeris = - (Ephemeris::createFromDictionary(translationDictionary)); - if (result->_ephemeris == nullptr) { + result->_transform.translation = + std::unique_ptr(Translation::createFromDictionary(translationDictionary)); + if (result->_transform.translation == nullptr) { LERROR("Failed to create ephemeris for SceneGraphNode '" << result->name() << "'"); delete result; return nullptr; } + result->addPropertySubOwner(result->_transform.translation.get()); LDEBUG("Successfully created ephemeris for '" << result->name() << "'"); } if (dictionary.hasKey(keyTransformRotation)) { ghoul::Dictionary rotationDictionary; dictionary.getValue(keyTransformRotation, rotationDictionary); - result->_rotation = - (Rotation::createFromDictionary(rotationDictionary)); - if (result->_rotation == nullptr) { + result->_transform.rotation = + std::unique_ptr(Rotation::createFromDictionary(rotationDictionary)); + if (result->_transform.rotation == nullptr) { LERROR("Failed to create rotation for SceneGraphNode '" << result->name() << "'"); delete result; return nullptr; } + result->addPropertySubOwner(result->_transform.rotation.get()); LDEBUG("Successfully created rotation for '" << result->name() << "'"); } if (dictionary.hasKey(keyTransformScale)) { ghoul::Dictionary scaleDictionary; dictionary.getValue(keyTransformScale, scaleDictionary); - result->_scale = - (Scale::createFromDictionary(scaleDictionary)); - if (result->_scale == nullptr) { + result->_transform.scale = + std::unique_ptr(Scale::createFromDictionary(scaleDictionary)); + if (result->_transform.scale == nullptr) { LERROR("Failed to create scale for SceneGraphNode '" << result->name() << "'"); delete result; return nullptr; } + result->addPropertySubOwner(result->_transform.scale.get()); LDEBUG("Successfully created scale for '" << result->name() << "'"); } - //std::string parentName; - //if (!dictionary.getValue(KeyParentName, parentName)) { - // LWARNING("Could not find '" << KeyParentName << "' key, using 'Root'."); - // parentName = "Root"; - //} - - //SceneGraphNode* parentNode = sceneGraphNode(parentName); - //if (parentNode == nullptr) { - // LFATAL("Could not find parent named '" - // << parentName << "' for '" << result->name() << "'." - // << " Check module definition order. Skipping module."); - //} - - //parentNode->addNode(result); - LDEBUG("Successfully created SceneGraphNode '" << result->name() << "'"); return result; @@ -167,9 +147,11 @@ SceneGraphNode* SceneGraphNode::createFromDictionary(const ghoul::Dictionary& di SceneGraphNode::SceneGraphNode() : _parent(nullptr) - , _ephemeris(new StaticEphemeris()) - , _rotation(new StaticRotation()) - , _scale(new StaticScale()) + , _transform { + std::make_unique(), + std::make_unique(), + std::make_unique() + } , _performanceRecord({0, 0, 0}) , _renderable(nullptr) , _renderableVisible(false) @@ -182,15 +164,20 @@ SceneGraphNode::~SceneGraphNode() { } bool SceneGraphNode::initialize() { - if (_renderable) + if (_renderable) { _renderable->initialize(); + } - if (_ephemeris) - _ephemeris->initialize(); - if (_rotation) - _rotation->initialize(); - if (_scale) - _scale->initialize(); + if (_transform.translation) { + _transform.translation->initialize(); + } + + if (_transform.rotation) { + _transform.rotation->initialize(); + } + if (_transform.scale) { + _transform.scale->initialize(); + } return true; } @@ -203,26 +190,6 @@ bool SceneGraphNode::deinitialize() { delete _renderable; _renderable = nullptr; } - if (_ephemeris) { - delete _ephemeris; - _ephemeris = nullptr; - } - if (_rotation) { - delete _rotation; - _rotation = nullptr; - } - if (_scale) { - delete _scale; - _scale = nullptr; - } - - //delete _ephemeris; - //_ephemeris = nullptr; - - // for (SceneGraphNode* child : _children) { - // child->deinitialize(); - // delete child; - //} _children.clear(); // reset variables @@ -235,49 +202,52 @@ bool SceneGraphNode::deinitialize() { } void SceneGraphNode::update(const UpdateData& data) { - if (_ephemeris) { + if (_transform.translation) { if (data.doPerformanceMeasurement) { glFinish(); auto start = std::chrono::high_resolution_clock::now(); - _ephemeris->update(data); + _transform.translation->update(data); glFinish(); auto end = std::chrono::high_resolution_clock::now(); - _performanceRecord.updateTimeEphemeris = (end - start).count(); + _performanceRecord.updateTimeTranslation = (end - start).count(); + } + else { + _transform.translation->update(data); } - else - _ephemeris->update(data); } - if (_rotation) { + if (_transform.rotation) { if (data.doPerformanceMeasurement) { glFinish(); auto start = std::chrono::high_resolution_clock::now(); - _rotation->update(data); + _transform.rotation->update(data); glFinish(); auto end = std::chrono::high_resolution_clock::now(); - _performanceRecord.updateTimeEphemeris = (end - start).count(); + _performanceRecord.updateTimeRotation = (end - start).count(); + } + else { + _transform.rotation->update(data); } - else - _rotation->update(data); } - if (_scale) { + if (_transform.scale) { if (data.doPerformanceMeasurement) { glFinish(); auto start = std::chrono::high_resolution_clock::now(); - _scale->update(data); + _transform.scale->update(data); glFinish(); auto end = std::chrono::high_resolution_clock::now(); - _performanceRecord.updateTimeEphemeris = (end - start).count(); + _performanceRecord.updateTimeScaling = (end - start).count(); + } + else { + _transform.scale->update(data); } - else - _scale->update(data); } UpdateData newUpdateData = data; @@ -358,7 +328,7 @@ void SceneGraphNode::render(const RenderData& data, RendererTasks& tasks) { _worldRotationCached, _worldScaleCached}; - _performanceRecord.renderTime = 0; + //_performanceRecord.renderTime = 0; bool visible = _renderableVisible && _renderable->isVisible() && @@ -387,18 +357,6 @@ void SceneGraphNode::render(const RenderData& data, RendererTasks& tasks) { // child->render(newData); } -void SceneGraphNode::postRender(const RenderData& data) { - const psc thisPosition = psc::CreatePowerScaledCoordinate(_worldPositionCached.x, _worldPositionCached.y, _worldPositionCached.z); - RenderData newData = { data.camera, thisPosition, data.doPerformanceMeasurement, data.renderBinMask, _worldPositionCached}; - - _performanceRecord.renderTime = 0; - if (_renderableVisible && _renderable->isVisible() && _renderable->isReady() && _renderable->isEnabled()) { - _renderable->postRender(newData); - } -} - - - // not used anymore @AA //void SceneGraphNode::addNode(SceneGraphNode* child) @@ -431,17 +389,17 @@ void SceneGraphNode::addChild(SceneGraphNode* child) { glm::dvec3 SceneGraphNode::position() const { - return _ephemeris->position(); + return _transform.translation->position(); } const glm::dmat3& SceneGraphNode::rotationMatrix() const { - return _rotation->matrix(); + return _transform.rotation->matrix(); } double SceneGraphNode::scale() const { - return _scale->scaleValue(); + return _transform.scale->scaleValue(); } glm::dvec3 SceneGraphNode::worldPosition() const diff --git a/src/scene/scenegraphnode_doc.inl b/src/scene/scenegraphnode_doc.inl index 5a491fb139..ba183dd42f 100644 --- a/src/scene/scenegraphnode_doc.inl +++ b/src/scene/scenegraphnode_doc.inl @@ -31,6 +31,7 @@ Documentation SceneGraphNode::Documentation() { return { "Scenegraph Node", + "core_scene_node", { { "Name", @@ -38,7 +39,8 @@ Documentation SceneGraphNode::Documentation() { "The name of this scenegraph node. This name must be unique among all scene " "graph nodes that are loaded in a specific scene. If a duplicate is detected " "the loading of the node will fail, as will all childing that depend on the " - "node." + "node.", + Optional::No }, { "Parent", @@ -48,7 +50,8 @@ Documentation SceneGraphNode::Documentation() { "This names the parent of the currently specified scenegraph node. The " "parent must not have been defined earlier, but must exist at loading time, " "or the scenegraph node creation will fail. A special parent 'Root' is " - "available that denotes the root of the scenegraph." + "available that denotes the root of the scenegraph.", + Optional::No }, { "Renderable", diff --git a/src/scene/ephemeris.cpp b/src/scene/translation.cpp similarity index 72% rename from src/scene/ephemeris.cpp rename to src/scene/translation.cpp index 9051d5a977..0f0c19fefd 100644 --- a/src/scene/ephemeris.cpp +++ b/src/scene/translation.cpp @@ -22,23 +22,24 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include +#include + #include #include #include namespace { - const std::string _loggerCat = "Ephemeris"; + const std::string _loggerCat = "Translation"; const std::string KeyType = "Type"; } namespace openspace { -Documentation Ephemeris::Documentation() { +Documentation Translation::Documentation() { using namespace openspace::documentation; - return{ + return { "Transformation Translation", "core_transform_translation", { @@ -56,31 +57,54 @@ Documentation Ephemeris::Documentation() { }; } -Ephemeris* Ephemeris::createFromDictionary(const ghoul::Dictionary& dictionary) { +Translation* Translation::createFromDictionary(const ghoul::Dictionary& dictionary) { if (!dictionary.hasValue(KeyType)) { - LERROR("Ephemeris did not have key '" << KeyType << "'"); + LERROR("Translation did not have key '" << KeyType << "'"); return nullptr; } - std::string ephemerisType; - dictionary.getValue(KeyType, ephemerisType); - ghoul::TemplateFactory* factory - = FactoryManager::ref().factory(); - Ephemeris* result = factory->create(ephemerisType, dictionary); + std::string translationType; + dictionary.getValue(KeyType, translationType); + ghoul::TemplateFactory* factory + = FactoryManager::ref().factory(); + Translation* result = factory->create(translationType, dictionary); + result->setName("Translation"); if (result == nullptr) { - LERROR("Failed creating Ephemeris object of type '" << ephemerisType << "'"); + LERROR("Failed creating Translation object of type '" << translationType << "'"); return nullptr; } return result; } -Ephemeris::~Ephemeris() {} +Translation::~Translation() {} -bool Ephemeris::initialize() { +bool Translation::initialize() { return true; } -void Ephemeris::update(const UpdateData& data) {} +void Translation::update(const UpdateData& data) {} + +glm::dvec3 Translation::position(double time) { + update({ + {}, + time, + 1.0, + false, + false + }); + + return position(); +} + +void Translation::notifyObservers() { + if (_onParameterChangeCallback) { + _onParameterChangeCallback(); + } +} + +void Translation::onParameterChange(std::function callback) { + _onParameterChangeCallback = std::move(callback); +} } // namespace openspace diff --git a/src/scripting/scriptengine.cpp b/src/scripting/scriptengine.cpp index 7ac37b5eb3..4bb3892a4a 100644 --- a/src/scripting/scriptengine.cpp +++ b/src/scripting/scriptengine.cpp @@ -23,6 +23,7 @@ ****************************************************************************************/ #include +#include #include #include @@ -39,6 +40,15 @@ #include "scriptengine_lua.inl" +namespace { + const std::string MainTemplateFilename = "${OPENSPACE_DATA}/web/luascripting/main.hbs"; + const std::string ScriptingTemplateFilename = "${OPENSPACE_DATA}/web/luascripting/scripting.hbs"; + const std::string HandlebarsFilename = "${OPENSPACE_DATA}/web/common/handlebars-v4.0.5.js"; + const std::string JsFilename = "${OPENSPACE_DATA}/web/luascripting/script.js"; + const std::string BootstrapFilename = "${OPENSPACE_DATA}/web/common/bootstrap.min.css"; + const std::string CssFilename = "${OPENSPACE_DATA}/web/common/style.css"; +} + namespace openspace { namespace scripting { @@ -156,16 +166,7 @@ bool ScriptEngine::runScript(const std::string& script) { LERRORC(e.component, e.message); return false; } - - // if we're currently hosting the parallel session, find out if script should be synchronized. - if (OsEng.parallelConnection().isHost()) { - std::string lib, func; - if (parseLibraryAndFunctionNames(lib, func, script) && shouldScriptBeSent(lib, func)){ -// OsEng.parallelConnection()->sendScript(script); -// cacheScript(lib, func, script); - } - } - + return true; } @@ -194,7 +195,7 @@ bool ScriptEngine::runScriptFile(const std::string& filename) { return true; } -bool ScriptEngine::shouldScriptBeSent(const std::string& library, const std::string& function) { +/*bool ScriptEngine::shouldScriptBeSent(const std::string& library, const std::string& function) { std::set::const_iterator libit; for (libit = _registeredLibraries.cbegin(); libit != _registeredLibraries.cend(); @@ -219,9 +220,9 @@ bool ScriptEngine::shouldScriptBeSent(const std::string& library, const std::str } return false; -} +}*/ -void ScriptEngine::cacheScript(const std::string &library, const std::string &function, const std::string &script){ +/*void ScriptEngine::cacheScript(const std::string &library, const std::string &function, const std::string &script){ _cachedScriptsMutex.lock(); _cachedScripts[library][function] = script; _cachedScriptsMutex.unlock(); @@ -246,8 +247,9 @@ std::vector ScriptEngine::cachedScripts(){ _cachedScriptsMutex.unlock(); return retVal; -} +}*/ +/* bool ScriptEngine::parseLibraryAndFunctionNames(std::string &library, std::string &function, const std::string &script){ //"deconstruct the script to find library and function name @@ -289,7 +291,7 @@ bool ScriptEngine::parseLibraryAndFunctionNames(std::string &library, std::strin //if we found a function all is good return !function.empty(); } - +*/ bool ScriptEngine::isLibraryNameAllowed(lua_State* state, const std::string& name) { bool result = false; lua_getglobal(state, _openspaceLibraryName.c_str()); @@ -562,18 +564,48 @@ void ScriptEngine::writeDocumentation(const std::string& filename, const std::st } } else if (type == "html") { + std::ifstream handlebarsInput(absPath(HandlebarsFilename)); + std::ifstream jsInput(absPath(JsFilename)); + + std::string jsContent; + std::back_insert_iterator jsInserter(jsContent); + + std::copy(std::istreambuf_iterator{handlebarsInput}, std::istreambuf_iterator(), jsInserter); + std::copy(std::istreambuf_iterator{jsInput}, std::istreambuf_iterator(), jsInserter); + + std::ifstream bootstrapInput(absPath(BootstrapFilename)); + std::ifstream cssInput(absPath(CssFilename)); + + std::string cssContent; + std::back_insert_iterator cssInserter(cssContent); + + std::copy(std::istreambuf_iterator{bootstrapInput}, std::istreambuf_iterator(), cssInserter); + std::copy(std::istreambuf_iterator{cssInput}, std::istreambuf_iterator(), cssInserter); + + std::ifstream mainTemplateInput(absPath(MainTemplateFilename)); + std::string mainTemplateContent{ std::istreambuf_iterator{mainTemplateInput}, + std::istreambuf_iterator{} }; + + std::ifstream scriptingTemplateInput(absPath(ScriptingTemplateFilename)); + std::string scriptingTemplateContent{ std::istreambuf_iterator{scriptingTemplateInput}, + std::istreambuf_iterator{} }; + std::ofstream file; file.exceptions(~std::ofstream::goodbit); file.open(filename); -#ifdef JSON // Create JSON std::stringstream json; json << "["; + bool first = true; for (const LuaLibrary& l : _registeredLibraries) { - json << "{"; + if (!first) { + json << ","; + } + first = false; + json << "{"; json << "\"library\": \"" << l.name << "\","; json << "\"functions\": ["; @@ -582,16 +614,53 @@ void ScriptEngine::writeDocumentation(const std::string& filename, const std::st json << "\"name\": \"" << f.name << "\", "; json << "\"arguments\": \"" << f.argumentText << "\", "; json << "\"help\": \"" << f.helpText << "\""; - json << "},"; + json << "}"; + if (&f != &l.functions.back()) { + json << ","; + } } - json << "]},"; + json << "]}"; + } json << "]"; + std::string jsonString = ""; + for (const char& c : json.str()) { + if (c == '\'') { + jsonString += "\\'"; + } + else { + jsonString += c; + } + } - std::string jsonText = json.str(); -#else std::stringstream html; + html << "\n" + << "\n" + << "\t\n" + << "\t\t\n" + << "\t\t\n" + << "\t\n" + << "\t\n" + << "\t\tDocumentation\n" + << "\t\n" + << "\t\n" + << "\t\n" + << "\n"; + + file << html.str(); + + /* html << "\n" << "\t\n" @@ -644,7 +713,7 @@ void ScriptEngine::writeDocumentation(const std::string& filename, const std::st << ""; file << html.str(); -#endif +*/ } else { throw ghoul::RuntimeError("Undefined type '" + type + "' for Lua documentation"); @@ -716,20 +785,27 @@ bool ScriptEngine::writeLog(const std::string& script) { } void ScriptEngine::presync(bool isMaster) { - if (isMaster) { - _mutex.lock(); + if (!isMaster) return; - if (!_queuedScripts.empty()) { - _currentSyncedScript = _queuedScripts.back(); - _queuedScripts.pop_back(); + _mutex.lock(); - //Not really a received script but the master also needs to run the script... - _receivedScripts.push_back(_currentSyncedScript); + if (!_queuedScripts.empty()) { + _currentSyncedScript = _queuedScripts.back().first; + bool remoteScripting = _queuedScripts.back().second; + + + //Not really a received script but the master also needs to run the script... + _receivedScripts.push_back(_currentSyncedScript); + _queuedScripts.pop_back(); + + if (OsEng.parallelConnection().isHost() && remoteScripting) { + OsEng.parallelConnection().sendScript(_currentSyncedScript); } - _mutex.unlock(); } + _mutex.unlock(); + } void ScriptEngine::encode(SyncBuffer* syncBuffer) { @@ -766,13 +842,13 @@ void ScriptEngine::postsync(bool isMaster) { } } -void ScriptEngine::queueScript(const std::string &script){ +void ScriptEngine::queueScript(const std::string &script, ScriptEngine::RemoteScripting remoteScripting){ if (script.empty()) return; _mutex.lock(); - _queuedScripts.insert(_queuedScripts.begin(), script); + _queuedScripts.insert(_queuedScripts.begin(), std::make_pair(script, remoteScripting)); _mutex.unlock(); } diff --git a/src/scripting/scriptengine_lua.inl b/src/scripting/scriptengine_lua.inl index 1d32ba1455..7f6e8865df 100644 --- a/src/scripting/scriptengine_lua.inl +++ b/src/scripting/scriptengine_lua.inl @@ -26,7 +26,7 @@ namespace openspace { namespace luascriptfunctions { - int printInternal(ghoul::logging::LogManager::LogLevel level, lua_State* L) { + int printInternal(ghoul::logging::LogLevel level, lua_State* L) { using ghoul::lua::luaTypeToString; const std::string _loggerCat = "print"; @@ -67,7 +67,7 @@ namespace luascriptfunctions { * types, the type is printed instead */ int printDebug(lua_State* L) { - return printInternal(ghoul::logging::LogManager::LogLevel::Debug, L); + return printInternal(ghoul::logging::LogLevel::Debug, L); } /** @@ -78,7 +78,7 @@ namespace luascriptfunctions { * types, the type is printed instead */ int printInfo(lua_State* L) { - return printInternal(ghoul::logging::LogManager::LogLevel::Info, L); + return printInternal(ghoul::logging::LogLevel::Info, L); } /** @@ -89,7 +89,7 @@ namespace luascriptfunctions { * types, the type is printed instead */ int printWarning(lua_State* L) { - return printInternal(ghoul::logging::LogManager::LogLevel::Warning, L); + return printInternal(ghoul::logging::LogLevel::Warning, L); } /** @@ -100,7 +100,7 @@ namespace luascriptfunctions { * types, the type is printed instead */ int printError(lua_State* L) { - return printInternal(ghoul::logging::LogManager::LogLevel::Error, L); + return printInternal(ghoul::logging::LogLevel::Error, L); } /** @@ -111,7 +111,7 @@ namespace luascriptfunctions { * types, the type is printed instead */ int printFatal(lua_State* L) { - return printInternal(ghoul::logging::LogManager::LogLevel::Fatal, L); + return printInternal(ghoul::logging::LogLevel::Fatal, L); } /** diff --git a/src/scripting/scriptscheduler.cpp b/src/scripting/scriptscheduler.cpp index a49f68dc03..05eb6fb76e 100644 --- a/src/scripting/scriptscheduler.cpp +++ b/src/scripting/scriptscheduler.cpp @@ -27,74 +27,154 @@ #include #include -#include // parse time +#include #include #include - -namespace openspace { -namespace scripting { +#include namespace { - const std::string _loggerCat = "ScriptScheduler"; - - const std::string KEY_TIME = "Time"; - const std::string KEY_FORWARD_SCRIPT = "ReversibleLuaScript.Forward"; - const std::string KEY_BACKWARD_SCRIPT = "ReversibleLuaScript.Backward"; + const char* KeyTime = "Time"; + const char* KeyForwardScript = "ForwardScript"; + const char* KeyBackwardScript = "BackwardScript"; + const char* KeyUniversalScript = "Script"; } +namespace openspace { -ScheduledScript::ScheduledScript(const ghoul::Dictionary& dict) - : ScheduledScript() // default init first +#include "scriptscheduler_lua.inl" + +namespace scripting { + +openspace::Documentation ScriptScheduler::Documentation() { + using namespace openspace::documentation; + + using TimeVerifier = StringVerifier; + using LuaScriptVerifier = StringVerifier; + + return{ + "Scheduled Scripts", + "core_scheduledscript", + { + { + "*", + new TableVerifier({ + { + KeyTime, + new TimeVerifier, + "The time at which, when the in game time passes it, the two " + "scripts will be executed. If the traversal is forwards (towards " + "+ infinity), the ForwardScript will be executed, otherwise the " + "BackwardScript will be executed instead.", + Optional::No + }, + { + KeyUniversalScript, + new LuaScriptVerifier, + "The Lua script that will be executed when the specified time is " + "passed independent of its direction. This script will be " + "executed before the specific scripts if both versions are " + "specified", + Optional::Yes + }, + { + KeyForwardScript, + new LuaScriptVerifier, + "The Lua script that is executed when OpenSpace passes the time " + "in a forward direction.", + Optional::Yes + }, + { + KeyBackwardScript, + new LuaScriptVerifier, + "The Lua script that is executed when OpenSpace passes the time " + "in a backward direction.", + Optional::Yes + } + }) + } + }, + Exhaustive::Yes + }; +} + +ScriptScheduler::ScheduledScript::ScheduledScript(const ghoul::Dictionary& dictionary) + : time(-std::numeric_limits::max()) { - std::string timeStr; - if (dict.getValue(KEY_TIME, timeStr)) { - time = SpiceManager::ref().ephemerisTimeFromDate(timeStr); + std::string timeStr = dictionary.value(KeyTime); + time = Time::ref().convertTime(timeStr); + + // If a universal script is specified, retrieve it and add a ; as a separator so that + // it can be added to the other scripts + std::string universal; + dictionary.getValue(KeyUniversalScript, universal); + if (!universal.empty()) { + universal += ";"; + } + + if (dictionary.hasKeyAndValue(KeyForwardScript)) { + forwardScript = + universal + dictionary.value(KeyForwardScript); + } + + if (dictionary.hasKeyAndValue(KeyBackwardScript)) { + backwardScript = + universal + dictionary.value(KeyBackwardScript); + } +} - if (!dict.getValue(KEY_FORWARD_SCRIPT, script.forwardScript)) { - LERROR("Unable to read " << KEY_FORWARD_SCRIPT); - } - if (!dict.getValue(KEY_BACKWARD_SCRIPT, script.backwardScript)) { - LERROR("Unable to read " << KEY_BACKWARD_SCRIPT); +void ScriptScheduler::loadScripts(const ghoul::Dictionary& dictionary) { + // Check if all of the scheduled scripts are formed correctly + documentation::testSpecificationAndThrow( + Documentation(), + dictionary, + "ScriptScheduler" + ); + + // Create all the scheduled script first + std::vector scheduledScripts; + for (size_t i = 1; i <= dictionary.size(); ++i) { + const ghoul::Dictionary& timedScriptDict = dictionary.value( + std::to_string(i) + ); + scheduledScripts.emplace_back(timedScriptDict); + } + + // Sort scripts by time; use a stable_sort as the user might have had an intention + // specifying multiple scripts for the same time in a specific order + std::stable_sort( + scheduledScripts.begin(), + scheduledScripts.end(), + [](const ScheduledScript& lhs, const ScheduledScript& rhs) { + return lhs.time < rhs.time; } + ); + + // Move the scheduled scripts into their SOA alignment + // For the forward scripts, this is the forwards direction + // For the backward scripts, we insert them in the opposite order so that we can still + // return forward iterators to them in the progressTo method + for (ScheduledScript& script : scheduledScripts) { + _timings.push_back(script.time); + + _forwardScripts.push_back(std::move(script.forwardScript)); + + _backwardScripts.insert( + _backwardScripts.begin(), + std::move(script.backwardScript) + ); } - else { - LERROR("Unable to read " << KEY_TIME); - } -} - -bool ScheduledScript::CompareByTime(const ScheduledScript& s1, const ScheduledScript& s2){ - return s1.time < s2.time; -} - - - -void ScriptScheduler::loadScripts(const std::string& filepath, lua_State* L) { - ghoul::Dictionary timedScriptsDict; - try { - ghoul::lua::loadDictionaryFromFile(absPath(filepath), timedScriptsDict, L); - } - catch (const ghoul::RuntimeError& e) { - LERROR(e.what()); - return; - } - loadScripts(timedScriptsDict); -} - -void ScriptScheduler::loadScripts(const ghoul::Dictionary& dict) { - for (size_t i = 0; i < dict.size(); ++i) { - std::string id = std::to_string(i + 1); - const ghoul::Dictionary& timedScriptDict = dict.value(id); - _scheduledScripts.push_back(ScheduledScript(timedScriptDict)); - } - - // Sort scripts by time - std::stable_sort(_scheduledScripts.begin(), _scheduledScripts.end(), &ScheduledScript::CompareByTime); // Ensure _currentIndex and _currentTime is accurate after new scripts was added double lastTime = _currentTime; rewind(); progressTo(lastTime); + + ghoul_assert( + (_timings.size() == _forwardScripts.size()) && + (_timings.size() == _backwardScripts.size()), + "The SOA data structure has been mistreated and has different number of values" + ); } void ScriptScheduler::rewind() { @@ -102,91 +182,113 @@ void ScriptScheduler::rewind() { _currentTime = -DBL_MAX; } - void ScriptScheduler::clearSchedule() { rewind(); - _scheduledScripts.clear(); + _timings.clear(); + _forwardScripts.clear(); + _backwardScripts.clear(); } -std::queue ScriptScheduler::progressTo(double newTime) { - std::queue triggeredScripts; +std::pair< + std::vector::const_iterator, std::vector::const_iterator +> +ScriptScheduler::progressTo(double newTime) +{ + if (newTime == _currentTime) { + return { _forwardScripts.end(), _forwardScripts.end() }; + } + if (newTime > _currentTime) { - while(_currentIndex < _scheduledScripts.size() && _scheduledScripts[_currentIndex].time <= newTime){ - triggeredScripts.push(_scheduledScripts[_currentIndex].script.forwardScript); - _currentIndex++; - } + // Moving forward in time; we need to find the highest entry in the timings + // vector that is still smaller than the newTime + size_t prevIndex = _currentIndex; + auto it = std::upper_bound( + _timings.begin() + prevIndex, // We only need to start at the previous time + _timings.end(), + newTime + ); + + // How many values did we pass over? + int n = std::distance(_timings.begin() + prevIndex, it); + _currentIndex = prevIndex + n; + + // Update the new time + _currentTime = newTime; + + return { + _forwardScripts.begin() + prevIndex, + _forwardScripts.begin() + _currentIndex + }; } else { - while (0 < _currentIndex && _scheduledScripts[_currentIndex - 1].time > newTime) { - triggeredScripts.push(_scheduledScripts[_currentIndex - 1].script.backwardScript); - _currentIndex--; - } + // Moving backward in time; the need to find the lowest entry that is still bigger + // than the newTime + size_t prevIndex = _currentIndex; + auto it = std::lower_bound( + _timings.begin(), + _timings.begin() + prevIndex, // We can stop at the previous time + newTime + ); + + // How many values did we pass over? + int n = std::distance(it, _timings.begin() + prevIndex); + _currentIndex = prevIndex - n; + + // Update the new time + _currentTime = newTime; + + int size = _timings.size(); + return { + _backwardScripts.begin() + (size - prevIndex), + _backwardScripts.begin() + (size - _currentIndex) + }; } - - _currentTime = newTime; - return triggeredScripts; } -std::queue ScriptScheduler::progressTo(const std::string& timeStr) { - return std::move(progressTo(SpiceManager::ref().ephemerisTimeFromDate(timeStr))); -} - -double ScriptScheduler::currentTime() const { +double ScriptScheduler::currentTime() const { return _currentTime; }; -const std::vector& ScriptScheduler::allScripts() const { - return _scheduledScripts; -}; - - - -///////////////////////////////////////////////////////////////////// -// Lua library functions // -///////////////////////////////////////////////////////////////////// - -namespace luascriptfunctions { - int loadTimedScripts(lua_State* L) { - using ghoul::lua::luaTypeToString; - int nArguments = lua_gettop(L); - if (nArguments != 1) - return luaL_error(L, "Expected %i arguments, got %i", 1, nArguments); - - std::string missionFileName = luaL_checkstring(L, -1); - if (missionFileName.empty()) { - return luaL_error(L, "filepath string is empty"); - } +std::vector ScriptScheduler::allScripts() const { + std::vector result; + for (size_t i = 0; i < _timings.size(); ++i) { + ScheduledScript script; + script.time = _timings[i]; + script.forwardScript = _forwardScripts[i]; + script.backwardScript = _backwardScripts[i]; - OsEng.scriptScheduler().loadScripts(missionFileName, L); + result.push_back(std::move(script)); } - - int clear(lua_State* L) { - using ghoul::lua::luaTypeToString; - int nArguments = lua_gettop(L); - if (nArguments != 0) - return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments); - - OsEng.scriptScheduler().clearSchedule(); - } -} // namespace luascriptfunction - - + return result; +}; LuaLibrary ScriptScheduler::luaLibrary() { return { "scriptScheduler", { { - "load", - &luascriptfunctions::loadTimedScripts, + "loadFile", + &luascriptfunctions::loadFile, "string", - "Load timed scripts from file" + "Load timed scripts from a Lua script file that returns a list of " + "scheduled scripts." + }, + { + "loadScheduledScript", + &luascriptfunctions::loadScheduledScript, + "string, string, (string, string)", + "Load a single scheduled script. The first argument is the time at which " + "the scheduled script is triggered, the second argument is the script " + "that is executed in the forward direction, the optional third argument " + "is the script executed in the backwards direction, and the optional " + "last argument is the universal script, executed in either direction." + }, { "clear", &luascriptfunctions::clear, "", - "clears all scheduled scripts" + "Clears all scheduled scripts." }, } }; diff --git a/src/scripting/scriptscheduler_lua.inl b/src/scripting/scriptscheduler_lua.inl new file mode 100644 index 0000000000..a041e8a172 --- /dev/null +++ b/src/scripting/scriptscheduler_lua.inl @@ -0,0 +1,101 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +namespace luascriptfunctions { + +int loadFile(lua_State* L) { + int nArguments = lua_gettop(L); + if (nArguments != 1) { + return luaL_error(L, "Expected %i arguments, got %i", 1, nArguments); + } + + std::string missionFileName = luaL_checkstring(L, -1); + if (missionFileName.empty()) { + return luaL_error(L, "filepath string is empty"); + } + + OsEng.scriptScheduler().loadScripts( + ghoul::lua::loadDictionaryFromFile(missionFileName, L) + ); + + return 0; +} + +int loadScheduledScript(lua_State* L) { + int nArguments = lua_gettop(L); + if (nArguments == 2) { + OsEng.scriptScheduler().loadScripts({ + { + "1", + ghoul::Dictionary { + { KeyTime, std::string(luaL_checkstring(L, -2)) }, + { KeyForwardScript, std::string(luaL_checkstring(L, -1)) } + } + } + }); + } + else if (nArguments == 3) { + OsEng.scriptScheduler().loadScripts({ + { + "1", + ghoul::Dictionary { + { KeyTime, std::string(luaL_checkstring(L, -3)) }, + { KeyForwardScript, std::string(luaL_checkstring(L, -2)) }, + { KeyBackwardScript, std::string(luaL_checkstring(L, -1)) } + } + } + }); + } + else if (nArguments == 4) { + OsEng.scriptScheduler().loadScripts({ + { + "1", + ghoul::Dictionary { + { KeyTime, std::string(luaL_checkstring(L, -4)) }, + { KeyForwardScript, std::string(luaL_checkstring(L, -3)) }, + { KeyBackwardScript, std::string(luaL_checkstring(L, -2)) }, + { KeyUniversalScript, std::string(luaL_checkstring(L, -1)) } + } + } + }); + } + else { + return luaL_error(L, "Expected %i-%i arguments, got %i", 2, 4, nArguments); + } + + return 0; +} + +int clear(lua_State* L) { + int nArguments = lua_gettop(L); + if (nArguments != 0) { + return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments); + } + + OsEng.scriptScheduler().clearSchedule(); + + return 0; +} + +} // namespace luascriptfunction diff --git a/src/util/factorymanager.cpp b/src/util/factorymanager.cpp index dd0f60cdce..4d979bbad6 100644 --- a/src/util/factorymanager.cpp +++ b/src/util/factorymanager.cpp @@ -23,11 +23,23 @@ ****************************************************************************************/ #include +#include +#include #include +#include #include +namespace { + const std::string MainTemplateFilename = "${OPENSPACE_DATA}/web/factories/main.hbs"; + const std::string FactoryTemplateFilename = "${OPENSPACE_DATA}/web/factories/factory.hbs"; + const std::string HandlebarsFilename = "${OPENSPACE_DATA}/web/common/handlebars-v4.0.5.js"; + const std::string JsFilename = "${OPENSPACE_DATA}/web/factories/script.js"; + const std::string BootstrapFilename = "${OPENSPACE_DATA}/web/common/bootstrap.min.css"; + const std::string CssFilename = "${OPENSPACE_DATA}/web/common/style.css"; +} + namespace openspace { FactoryManager* FactoryManager::_manager = nullptr; @@ -84,8 +96,32 @@ void FactoryManager::writeDocumentation(const std::string& file, const std::stri } else if (type == "html") { + std::ifstream handlebarsInput(absPath(HandlebarsFilename)); + std::ifstream jsInput(absPath(JsFilename)); + + std::string jsContent; + std::back_insert_iterator jsInserter(jsContent); + + std::copy(std::istreambuf_iterator{handlebarsInput}, std::istreambuf_iterator(), jsInserter); + std::copy(std::istreambuf_iterator{jsInput}, std::istreambuf_iterator(), jsInserter); + + std::ifstream bootstrapInput(absPath(BootstrapFilename)); + std::ifstream cssInput(absPath(CssFilename)); + + std::string cssContent; + std::back_insert_iterator cssInserter(cssContent); + + std::copy(std::istreambuf_iterator{bootstrapInput}, std::istreambuf_iterator(), cssInserter); + std::copy(std::istreambuf_iterator{cssInput}, std::istreambuf_iterator(), cssInserter); + + std::ifstream mainTemplateInput(absPath(MainTemplateFilename)); + std::string mainTemplateContent{ std::istreambuf_iterator{mainTemplateInput}, + std::istreambuf_iterator{} }; + + std::ifstream factoryTemplateInput(absPath(FactoryTemplateFilename)); + std::string factoryTemplateContent{ std::istreambuf_iterator{factoryTemplateInput}, + std::istreambuf_iterator{} }; -#ifdef JSON std::stringstream json; json << "["; @@ -95,23 +131,65 @@ void FactoryManager::writeDocumentation(const std::string& file, const std::stri json << "\"classes\": ["; ghoul::TemplateFactoryBase* factory = factoryInfo.factory.get(); - for (const std::string& c : factory->registeredClasses()) { - json << "\"" << c << "\","; + const std::vector& registeredClasses = factory->registeredClasses(); + for (const std::string& c : registeredClasses) { + json << "\"" << c << "\""; + if (&c != ®isteredClasses.back()) { + json << ","; + } } - json << "]},"; + json << "]}"; + if (&factoryInfo != &_factories.back()) { + json << ","; + } } json << "]"; // I did not check the output of this for correctness ---abock std::string jsonText = json.str(); -#else + std::ofstream f; f.exceptions(~std::ofstream::goodbit); f.open(file); + std::string jsonString = ""; + for (const char& c : json.str()) { + if (c == '\'') { + jsonString += "\\'"; + } else { + jsonString += c; + } + } + std::stringstream html; + html << "\n" + << "\n" + << "\t\n" + << "\t\t\n" + << "\t\t\n" + << "\t\n" + << "\t\n" + << "\t\tDocumentation\n" + << "\t\n" + << "\t\n" + << "\t\n" + << "\n"; + + f << html.str(); + + /* html << "\n" << "\t\n" << "\t\tFactories\n" @@ -142,10 +220,8 @@ void FactoryManager::writeDocumentation(const std::string& file, const std::stri html << "\t\n" << "\n" << ";"; - f << html.str(); -#endif - + */ } } diff --git a/shaders/framebuffer/postrenderframebuffer.frag b/src/util/gpudata.cpp similarity index 89% rename from shaders/framebuffer/postrenderframebuffer.frag rename to src/util/gpudata.cpp index 98905b9952..1aa901f8b3 100644 --- a/shaders/framebuffer/postrenderframebuffer.frag +++ b/src/util/gpudata.cpp @@ -22,13 +22,14 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include "PowerScaling/powerScalingMath.hglsl" -#include <#{fragmentPath}> +#include -out vec4 _out_color_; +#include -void main() { - Fragment f = getFragment(); - _out_color_ = f.color; - gl_FragDepth = normalizeFloat(f.depth); +namespace openspace { + +void UniformLocation::bind(ProgramObject* program, const std::string& name){ + _uniformLocation = program->uniformLocation(name); } + +} // namespace openspace diff --git a/src/util/openspacemodule.cpp b/src/util/openspacemodule.cpp index dc61f1c014..c326e3256c 100644 --- a/src/util/openspacemodule.cpp +++ b/src/util/openspacemodule.cpp @@ -67,6 +67,12 @@ std::vector OpenSpaceModule::documentations() const { return {}; } +ghoul::systemcapabilities::OpenGLCapabilitiesComponent::Version +OpenSpaceModule::requiredOpenGLVersion() const +{ + return { 3, 3 }; +} + std::string OpenSpaceModule::modulePath() const { std::string moduleName = name(); std::transform(moduleName.begin(), moduleName.end(), moduleName.begin(), tolower); diff --git a/src/util/spicemanager.cpp b/src/util/spicemanager.cpp index 2740c66e85..dbaf862d15 100644 --- a/src/util/spicemanager.cpp +++ b/src/util/spicemanager.cpp @@ -34,6 +34,9 @@ #include #include +#include "SpiceUsr.h" +#include "SpiceZpr.h" + namespace { const std::string _loggerCat = "SpiceManager"; @@ -44,15 +47,24 @@ namespace { // This method checks if one of the previous SPICE methods has failed. If it has, an // exception with the SPICE error message is thrown - void throwOnSpiceError(std::string errorMessage) { + // If an error occurred, true is returned, otherwise, false + bool throwOnSpiceError(std::string errorMessage) { SpiceBoolean failed = failed_c(); - if (failed) { - char buffer[SpiceErrorBufferSize]; - getmsg_c("LONG", SpiceErrorBufferSize, buffer); - reset_c(); - throw openspace::SpiceManager::SpiceException( - errorMessage + ": " + buffer - ); + if (openspace::SpiceManager::ref().exceptionHandling()) { + if (failed) { + char buffer[SpiceErrorBufferSize]; + getmsg_c("LONG", SpiceErrorBufferSize, buffer); + reset_c(); + throw openspace::SpiceManager::SpiceException( + errorMessage + ": " + buffer + ); + } + else { + return false; + } + } + else { + return failed; } } @@ -85,9 +97,12 @@ namespace openspace { SpiceManager::SpiceException::SpiceException(const string& msg) : ghoul::RuntimeError(msg, "Spice") -{} - - +{ + ghoul_assert( + SpiceManager::ref().exceptionHandling() == SpiceManager::UseException::Yes, + "No exceptions should be thrown when UseException is No" + ); +} SpiceManager::AberrationCorrection::AberrationCorrection(Type t, Direction d) : type(t) @@ -155,7 +170,9 @@ SpiceManager::TerminatorType SpiceManager::terminatorTypeFromString( const strin return Mapping.at(type); } -SpiceManager::SpiceManager() { +SpiceManager::SpiceManager() + : _useExceptions(UseException::Yes) +{ // Set the SPICE library to not exit the program if an error occurs erract_c("SET", 0, const_cast("REPORT")); // But we do not want SPICE to print the errors, we will fetch them ourselves @@ -163,15 +180,15 @@ SpiceManager::SpiceManager() { } SpiceManager::~SpiceManager() { - for (const KernelInformation& i : _loadedKernels) + for (const KernelInformation& i : _loadedKernels) { unload_c(i.path.c_str()); + } // Set values back to default erract_c("SET", 0, const_cast("DEFAULT")); errprt_c("SET", 0, const_cast("DEFAULT")); } - SpiceManager::KernelHandle SpiceManager::loadKernel(string filePath) { ghoul_assert(!filePath.empty(), "Empty file path"); ghoul_assert( @@ -227,10 +244,12 @@ SpiceManager::KernelHandle SpiceManager::loadKernel(string filePath) { throwOnSpiceError("Kernel loading"); string fileExtension = ghoul::filesystem::File(path, RawPath::Yes).fileExtension(); - if (fileExtension == "bc" || fileExtension == "BC") + if (fileExtension == "bc" || fileExtension == "BC") { findCkCoverage(path); // binary ck kernel - else if (fileExtension == "bsp" || fileExtension == "BSP") + } + else if (fileExtension == "bsp" || fileExtension == "BSP") { findSpkCoverage(path); // binary spk kernel + } KernelHandle kernelId = ++_lastAssignedKernel; ghoul_assert(kernelId != 0, fmt::format("Kernel Handle wrapped around to 0")); @@ -270,9 +289,14 @@ void SpiceManager::unloadKernel(std::string filePath) { [&path](const KernelInformation& info) { return info.path == path; }); if (it == _loadedKernels.end()) { - throw SpiceException( - format("'{}' did not correspond to a loaded kernel", path) - ); + if (_useExceptions) { + throw SpiceException( + format("'{}' did not correspond to a loaded kernel", path) + ); + } + else { + return; + } } else { // If there was only one part interested in the kernel, we can unload it @@ -297,8 +321,9 @@ bool SpiceManager::hasSpkCoverage(const string& target, double et) const { if (it != _spkIntervals.end()) { std::vector> intervalVector = it->second; for (const auto& vecElement : intervalVector) { - if (vecElement.first < et && vecElement.second > et) + if (vecElement.first < et && vecElement.second > et) { return true; + } } } return false; @@ -313,8 +338,9 @@ bool SpiceManager::hasCkCoverage(const string& frame, double et) const { if (it != _ckIntervals.end()) { std::vector> intervalVector = it->second; for (const auto& i : intervalVector) { - if (i.first < et && i.second > et) + if (i.first < et && i.second > et) { return true; + } } } return false; @@ -338,8 +364,9 @@ int SpiceManager::naifId(const std::string& body) const { SpiceBoolean success; SpiceInt id; bods2c_c(body.c_str(), &id, &success); - if (!success) + if (!success && _useExceptions) { throw SpiceException(format("Could not find NAIF ID of body '{}'", body)); + } return id; } @@ -358,8 +385,9 @@ int SpiceManager::frameId(const std::string& frame) const { SpiceInt id; namfrm_c(frame.c_str(), &id); - if (id == 0) + if (id == 0 && _useExceptions) { throw SpiceException(format("Could not find NAIF ID of frame '{}'", frame)); + } return id; } @@ -473,14 +501,19 @@ glm::dvec3 SpiceManager::targetPosition(const std::string& target, bool targetHasCoverage = hasSpkCoverage(target, ephemerisTime); bool observerHasCoverage = hasSpkCoverage(observer, ephemerisTime); - if (!targetHasCoverage && !observerHasCoverage){ - throw SpiceException( - format("Neither target '{}' nor observer '{}' has SPK coverage at time {}", - target, - observer, - ephemerisTime - ) - ); + if (!targetHasCoverage && !observerHasCoverage) { + if (_useExceptions) { + throw SpiceException( + format("Neither target '{}' nor observer '{}' has SPK coverage at time {}", + target, + observer, + ephemerisTime + ) + ); + } + else { + return glm::dvec3(); + } } else if (targetHasCoverage && observerHasCoverage) { glm::dvec3 position; @@ -768,13 +801,17 @@ SpiceManager::FieldOfViewResult SpiceManager::fieldOfView(int instrument) const boundsArr // the bounds ); - throwOnSpiceError(format( + bool failed = throwOnSpiceError(format( "Error getting field-of-view parameters for instrument '{}'", instrument )); + if (failed) { + return res; + } res.bounds.reserve(nrReturned); - for (int i = 0; i < nrReturned; ++i) + for (int i = 0; i < nrReturned; ++i) { res.bounds.emplace_back(boundsArr[i][0], boundsArr[i][1], boundsArr[i][2]); + } string shape = string(fovShapeBuffer); static const std::map Map = { @@ -946,8 +983,13 @@ glm::dvec3 SpiceManager::getEstimatedPosition(const std::string& target, } if (_spkCoverageTimes.find(targetId) == _spkCoverageTimes.end()) { - // no coverage - throw SpiceException(format("No position for '{}' at any time", target)); + if (_useExceptions) { + // no coverage + throw SpiceException(format("No position for '{}' at any time", target)); + } + else { + return glm::dvec3(); + } } const std::set& coveredTimes = _spkCoverageTimes.find(targetId)->second; @@ -1035,11 +1077,16 @@ glm::dmat3 SpiceManager::getEstimatedTransformMatrix(const std::string& fromFram int idFrame = frameId(fromFrame); if (_ckCoverageTimes.find(idFrame) == _ckCoverageTimes.end()) { - // no coverage - throw SpiceException(format( - "No data available for the transform matrix from '{}' to '{}' at any time", - fromFrame, toFrame - )); + if (_useExceptions) { + // no coverage + throw SpiceException(format( + "No data available for the transform matrix from '{}' to '{}' at any time", + fromFrame, toFrame + )); + } + else { + return glm::dmat3(); + } } std::set coveredTimes = _ckCoverageTimes.find(idFrame)->second; @@ -1107,6 +1154,14 @@ glm::dmat3 SpiceManager::getEstimatedTransformMatrix(const std::string& fromFram return result; } +void SpiceManager::setExceptionHandling(UseException useException) { + _useExceptions = useException; +} + +SpiceManager::UseException SpiceManager::exceptionHandling() const { + return _useExceptions; +} + scripting::LuaLibrary SpiceManager::luaLibrary() { return { "spice", diff --git a/src/util/time.cpp b/src/util/time.cpp index 62f5b66b0a..89204ab623 100644 --- a/src/util/time.cpp +++ b/src/util/time.cpp @@ -34,12 +34,15 @@ #include #include - - - namespace openspace { Time* Time::_instance = nullptr; + + +double Time::convertTime(const std::string& time) { + ghoul_assert(!time.empty(), "timeString must not be empty"); + return SpiceManager::ref().ephemerisTimeFromDate(time); +} Time::Time(double secondsJ2000) : _time(secondsJ2000) @@ -81,7 +84,6 @@ Time Time::now() { return now; } - bool Time::isInitialized() { return (_instance != nullptr); } @@ -179,8 +181,7 @@ scripting::LuaLibrary Time::luaLibrary() { &luascriptfunctions::time_setDeltaTime, "number", "Sets the amount of simulation time that happens " - "in one second of real time", - true + "in one second of real time" }, { "deltaTime", @@ -193,16 +194,14 @@ scripting::LuaLibrary Time::luaLibrary() { "setPause", &luascriptfunctions::time_setPause, "bool", - "Pauses the simulation time or restores the delta time", - true + "Pauses the simulation time or restores the delta time" }, { "togglePause", &luascriptfunctions::time_togglePause, "", "Toggles the pause function, i.e. temporarily setting the delta time to 0" - " and restoring it afterwards", - true + " and restoring it afterwards" }, { "setTime", @@ -211,8 +210,7 @@ scripting::LuaLibrary Time::luaLibrary() { "Sets the current simulation time to the " "specified value. If the parameter is a number, the value is the number " "of seconds past the J2000 epoch. If it is a string, it has to be a " - "valid ISO 8601 date string (YYYY-MM-DDTHH:MN:SS)", - true + "valid ISO 8601 date string (YYYY-MM-DDTHH:MN:SS)" }, { "currentTime", diff --git a/src/util/timemanager.cpp b/src/util/timemanager.cpp new file mode 100644 index 0000000000..c70ca0d934 --- /dev/null +++ b/src/util/timemanager.cpp @@ -0,0 +1,153 @@ +/***************************************************************************************** +* * +* OpenSpace * +* * +* Copyright (c) 2014-2016 * +* * +* Permission is hereby granted, free of charge, to any person obtaining a copy of this * +* software and associated documentation files (the "Software"), to deal in the Software * +* without restriction, including without limitation the rights to use, copy, modify, * +* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * +* permit persons to whom the Software is furnished to do so, subject to the following * +* conditions: * +* * +* The above copyright notice and this permission notice shall be included in all copies * +* or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * +* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * +* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * +* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * +* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * +* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * +****************************************************************************************/ + +#include +#include +#include + +namespace { + double SecondsOffTolerance = 0.1; +} + +namespace openspace { + +using datamessagestructures::TimeKeyframe; + +void TimeManager::preSynchronization(double dt) { + double now = OsEng.runTime(); + removeKeyframesBefore(_latestConsumedTimestamp); + if (_keyframes.size() == 0) { + Time::ref().advanceTime(dt); + } else { + consumeKeyframes(dt); + } +} + +void TimeManager::consumeKeyframes(double dt) { + double now = OsEng.runTime(); + TimeKeyframe kf; + kf._timestamp = now; + auto firstFutureKeyframe = std::lower_bound(_keyframes.begin(), _keyframes.end(), kf, &TimeManager::compareKeyframeTimes); + + bool consumingTimeJump = std::find_if(_keyframes.begin(), firstFutureKeyframe, [] (const TimeKeyframe& f) { + return f._requiresTimeJump; + }) != firstFutureKeyframe; + + Time& time = Time::ref(); + + if (firstFutureKeyframe == _keyframes.end()) { + // All keyframes are in the past. + // Consume the latest one. + TimeKeyframe& current = _keyframes.back(); + time.setTime(current._time, consumingTimeJump); + time.setDeltaTime(current._dt); + time.setPause(current._paused); + _latestConsumedTimestamp = current._timestamp; + } + else { + TimeKeyframe& next = *firstFutureKeyframe; + + if (firstFutureKeyframe != _keyframes.begin()) { + TimeKeyframe& latest = *(firstFutureKeyframe - 1); + // In case of unconsumed passed keyframes, let the last one + // determine whether the time should be paused or not. + // If there was a time jump or time is paused, apply it directly. + // Then consume the last keyframe. + + time.setPause(latest._paused); + time.setTimeJumped(consumingTimeJump); + time.setDeltaTime(latest._dt); + + if (consumingTimeJump || latest._paused) { + time.setTime(latest._time, consumingTimeJump); + } + _latestConsumedTimestamp = latest._timestamp; + } + + // Do not interpolate with time jumping keyframes. + // Instead, wait until their timestamp and apply them directly. + if (next._requiresTimeJump) { + Time::ref().advanceTime(dt); + return; + } + + if (time.paused()) { + return; + } + + double predictedTime = time.j2000Seconds() + time.deltaTime() * (next._timestamp - now); + bool withinTolerance = std::abs(predictedTime - next._time) < std::abs(next._dt * SecondsOffTolerance); + + if (next._dt == time.deltaTime() && withinTolerance) { + Time::ref().advanceTime(dt); + return; + } + + double t0 = now - dt; + double t1 = now; + double t2 = next._timestamp; + + double parameter = (t1 - t0) / (t2 - t0); + + double y0 = time.j2000Seconds(); + double yPrime0 = time.deltaTime(); + + double y2 = next._time; + double yPrime2 = next._dt; + + double y1 = (1 - parameter) * y0 + parameter * y2; + double y1Prime = (y1 - y0) / dt; + + time.setDeltaTime(y1Prime); + time.setTime(y1, false); + } +} + + +void TimeManager::addKeyframe(const TimeKeyframe& kf) { + if (kf._timestamp < OsEng.runTime()) { + return; + } + auto iter = std::upper_bound(_keyframes.begin(), _keyframes.end(), kf, &TimeManager::compareKeyframeTimes); + _keyframes.insert(iter, kf); +} + + +void TimeManager::removeKeyframesBefore(double timestamp) { + datamessagestructures::TimeKeyframe kf; + kf._timestamp = timestamp; + auto iter = std::upper_bound(_keyframes.begin(), _keyframes.end(), kf, &TimeManager::compareKeyframeTimes); + _keyframes.erase(_keyframes.begin(), iter); +} + +void TimeManager::clearKeyframes() { + _keyframes.clear(); +} + +bool TimeManager::compareKeyframeTimes(const TimeKeyframe& a, const TimeKeyframe& b) +{ + return a._timestamp < b._timestamp; +} + +} \ No newline at end of file diff --git a/support/cmake/module_common.cmake b/support/cmake/module_common.cmake index 522d892a7c..db2d954043 100644 --- a/support/cmake/module_common.cmake +++ b/support/cmake/module_common.cmake @@ -2,7 +2,7 @@ # # # OpenSpace # # # -# Copyright (c) 2014-2015 # +# Copyright (c) 2014-2016 # # # # Permission is hereby granted, free of charge, to any person obtaining a copy of this # # software and associated documentation files (the "Software"), to deal in the Software # diff --git a/support/cmake/module_definition.cmake b/support/cmake/module_definition.cmake index 0ce121737d..fc8da28aa2 100644 --- a/support/cmake/module_definition.cmake +++ b/support/cmake/module_definition.cmake @@ -2,7 +2,7 @@ # # # OpenSpace # # # -# Copyright (c) 2014-2015 # +# Copyright (c) 2014-2016 # # # # Permission is hereby granted, free of charge, to any person obtaining a copy of this # # software and associated documentation files (the "Software"), to deal in the Software # @@ -41,8 +41,14 @@ function (create_new_module module_name output_library_name) # Add the module files to the list of sources add_module_files() + set(library_mode STATIC) + if (${library_name}_LIBRARY_MODE) + set(library_mode ${${library_name}_LIBRARY_MODE}) + message(STATUS "\t Overwritten library mode: ${library_mode}") + endif () + # Create the library - add_library(${library_name} STATIC ${sources}) + add_library(${library_name} ${library_mode} ${sources}) # Set compile settings that are common to all modules set_common_compile_settings(${library_name}) @@ -154,6 +160,7 @@ function (handle_dependencies target_name module_name) # Handle OpenSpace dependencies foreach (dep ${OPENSPACE_DEPENDENCIES}) create_library_name(${dep} dep_library) + message(STATUS "Link: ${target_name} <- ${dep_library}") target_link_libraries(${target_name} ${dep_library}) get_property( @@ -171,6 +178,7 @@ function (handle_dependencies target_name module_name) target_include_directories(${target_name} PUBLIC ${${dep_upper}_INCLUDE_DIR} ${${dep_upper}_INCLUDE_DIRS} ) + message(STATUS "Link: ${target_name} <- ${${dep_upper}_LIBRARIES}") target_link_libraries(${target_name} ${${dep_upper}_LIBRARIES}) endforeach () endif () diff --git a/support/cmake/support_macros.cmake b/support/cmake/support_macros.cmake index e8d06c459b..ce84b0d9c8 100644 --- a/support/cmake/support_macros.cmake +++ b/support/cmake/support_macros.cmake @@ -2,7 +2,7 @@ # # # OpenSpace # # # -# Copyright (c) 2014-2015 # +# Copyright (c) 2014-2016 # # # # Permission is hereby granted, free of charge, to any person obtaining a copy of this # # software and associated documentation files (the "Software"), to deal in the Software # @@ -124,6 +124,7 @@ function (add_external_dependencies) set(SGCT_TEXT OFF CACHE BOOL "" FORCE) set(SGCT_BUILD_CSHARP_PROJECTS OFF CACHE BOOL "" FORCE) set(SGCT_LIGHT_ONLY ON CACHE BOOL "" FORCE) + set(SGCT_CUSTOMOUTPUTDIRS OFF CACHE BOOL "" FORCE) add_subdirectory(${OPENSPACE_EXT_DIR}/sgct) target_include_directories(libOpenSpace SYSTEM PUBLIC ${OPENSPACE_EXT_DIR}/sgct/include) @@ -301,6 +302,7 @@ function (handle_option_tests) add_subdirectory(${OPENSPACE_EXT_DIR}/ghoul/ext/googletest) # add_subdirectory(${OPENSPACE_EXT_DIR}/ghoul/ext/gtest) set_property(TARGET gtest PROPERTY FOLDER "External") + set_property(TARGET gtest_main PROPERTY FOLDER "External") endif () file(GLOB_RECURSE OPENSPACE_TEST_FILES ${OPENSPACE_BASE_DIR}/tests/*.inl) @@ -344,7 +346,7 @@ function (handle_internal_modules) file(GLOB moduleDirs RELATIVE ${OPENSPACE_MODULE_DIR} ${OPENSPACE_MODULE_DIR}/*) set(sortedModules ${moduleDirs}) foreach (dir ${moduleDirs}) - if(IS_DIRECTORY ${OPENSPACE_MODULE_DIR}/${dir}) + if (IS_DIRECTORY ${OPENSPACE_MODULE_DIR}/${dir}) set(defaultModule OFF) if (EXISTS "${OPENSPACE_MODULE_DIR}/${dir}/include.cmake") unset(OPENSPACE_DEPENDENCIES) @@ -436,7 +438,12 @@ function (handle_internal_modules) endif () endforeach() - target_link_libraries(libOpenSpace ${libraryName}) + # Only link libOpenSpace against the library if it has been set STATIC + get_target_property(libType ${libraryName} TYPE) + if (NOT ${libType} STREQUAL "SHARED_LIBRARY") + target_link_libraries(libOpenSpace ${libraryName}) + endif() + create_define_name(${module} defineName) target_compile_definitions(libOpenSpace PUBLIC "${defineName}") diff --git a/tests/main.cpp b/tests/main.cpp index 354d923c9c..a0c491f33b 100644 --- a/tests/main.cpp +++ b/tests/main.cpp @@ -58,12 +58,16 @@ //#include #endif +#include + #include #include #include #include + #include +#include #include #include @@ -88,7 +92,7 @@ int main(int argc, char** argv) { testing::internal::CaptureStdout(); testing::internal::CaptureStderr(); #endif - + openspace::SpiceManager::deinitialize(); bool b = RUN_ALL_TESTS(); diff --git a/tests/test_aabb.inl b/tests/test_aabb.inl index da83faa03a..8d49293335 100644 --- a/tests/test_aabb.inl +++ b/tests/test_aabb.inl @@ -30,14 +30,10 @@ #include #include -using namespace openspace; - class AABBTest : public testing::Test {}; - - TEST_F(AABBTest, Contains2) { - + using namespace openspace::globebrowsing; AABB2 a1; AABB2 a2; /* @@ -67,6 +63,7 @@ TEST_F(AABBTest, Contains2) { TEST_F(AABBTest, Intersects2) { + using namespace openspace::globebrowsing; AABB2 a1; AABB2 a2; @@ -98,9 +95,8 @@ TEST_F(AABBTest, Intersects2) { } - - TEST_F(AABBTest, Contains3) { + using namespace openspace::globebrowsing; AABB3 a1; AABB3 a2; @@ -122,6 +118,7 @@ TEST_F(AABBTest, Contains3) { TEST_F(AABBTest, Intersects3) { + using namespace openspace::globebrowsing; AABB3 a1; AABB3 a2; diff --git a/tests/test_angle.inl b/tests/test_angle.inl index 25b0794acc..9658982f89 100644 --- a/tests/test_angle.inl +++ b/tests/test_angle.inl @@ -30,90 +30,92 @@ #include #include -using namespace openspace; - class AngleTest : public testing::Test {}; TEST_F(AngleTest, DoubleConversions) { - - ASSERT_EQ(dAngle::fromRadians(0).asDegrees(), 0) << "from radians to degrees"; - ASSERT_EQ(dAngle::HALF.asDegrees(), 180) << "from radians to degrees"; - ASSERT_EQ(dAngle::fromDegrees(180).asRadians(), dAngle::PI) << "from degrees to radians"; + using namespace openspace::globebrowsing; + + ASSERT_EQ(dAngle::fromRadians(0).asDegrees(), 0) << "from radians to degrees"; + ASSERT_EQ(dAngle::HALF.asDegrees(), 180) << "from radians to degrees"; + ASSERT_EQ(dAngle::fromDegrees(180).asRadians(), dAngle::PI) << "from degrees to radians"; } TEST_F(AngleTest, FloatConversions) { + using namespace openspace::globebrowsing; - ASSERT_EQ(fAngle::ZERO.asDegrees(), 0.0) << "from radians to degrees"; - ASSERT_EQ(fAngle::HALF.asDegrees(), 180.0) << "from radians to degrees"; - ASSERT_EQ(fAngle::fromDegrees(180).asRadians(), fAngle::PI) << "from degrees to radians"; + ASSERT_EQ(fAngle::ZERO.asDegrees(), 0.0) << "from radians to degrees"; + ASSERT_EQ(fAngle::HALF.asDegrees(), 180.0) << "from radians to degrees"; + ASSERT_EQ(fAngle::fromDegrees(180).asRadians(), fAngle::PI) << "from degrees to radians"; } TEST_F(AngleTest, Normalize) { - - - ASSERT_NEAR( - dAngle::fromDegrees(390).normalize().asDegrees(), - 30.0, - dAngle::EPSILON - ) << "normalize to [0, 360]"; + using namespace openspace::globebrowsing; + + ASSERT_NEAR( + dAngle::fromDegrees(390).normalize().asDegrees(), + 30.0, + dAngle::EPSILON + ) << "normalize to [0, 360]"; - dAngle a = dAngle::fromDegrees(190); - a.normalizeAround(dAngle::ZERO); - ASSERT_NEAR( - a.asDegrees(), - -170, - dAngle::EPSILON - ) << "normalize to [-180,180]"; + dAngle a = dAngle::fromDegrees(190); + a.normalizeAround(dAngle::ZERO); + ASSERT_NEAR( + a.asDegrees(), + -170, + dAngle::EPSILON + ) << "normalize to [-180,180]"; - dAngle b = dAngle::fromDegrees(190); - b.normalizeAround(dAngle::fromDegrees(90)); - ASSERT_NEAR( - b.asDegrees(), - 190, - dAngle::EPSILON - ) << "normalize to [-90,270]"; + dAngle b = dAngle::fromDegrees(190); + b.normalizeAround(dAngle::fromDegrees(90)); + ASSERT_NEAR( + b.asDegrees(), + 190, + dAngle::EPSILON + ) << "normalize to [-90,270]"; - dAngle c = dAngle::fromDegrees(360); - c.normalizeAround(dAngle::fromDegrees(1083.2)); - ASSERT_NEAR( - c.asDegrees(), - 1080, - dAngle::EPSILON - ) << "normalize to [903.2, 1263.2]"; + dAngle c = dAngle::fromDegrees(360); + c.normalizeAround(dAngle::fromDegrees(1083.2)); + ASSERT_NEAR( + c.asDegrees(), + 1080, + dAngle::EPSILON + ) << "normalize to [903.2, 1263.2]"; } TEST_F(AngleTest, Clamp) { + using namespace openspace::globebrowsing; - ASSERT_EQ( - dAngle::fromDegrees(390).clamp(dAngle::ZERO, dAngle::HALF).asDegrees(), - 180 - ) << "clamp [0, 180]"; + ASSERT_EQ( + dAngle::fromDegrees(390).clamp(dAngle::ZERO, dAngle::HALF).asDegrees(), + 180 + ) << "clamp [0, 180]"; - ASSERT_EQ( - dAngle::fromDegrees(390).clamp(dAngle::ZERO, dAngle::FULL).asDegrees(), - 360 - ) << "clamp [0, 360]"; + ASSERT_EQ( + dAngle::fromDegrees(390).clamp(dAngle::ZERO, dAngle::FULL).asDegrees(), + 360 + ) << "clamp [0, 360]"; } TEST_F(AngleTest, ConstClamp) { - - const dAngle a = dAngle::fromDegrees(390); - ASSERT_EQ( - a.getClamped(dAngle::ZERO, dAngle::HALF).asDegrees(), - 180 - ) << "clamp [0, 180]"; + using namespace openspace::globebrowsing; - const dAngle b = dAngle::fromDegrees(390); - ASSERT_EQ( - b.getClamped(dAngle::ZERO, dAngle::FULL).asDegrees(), - 360 - ) << "clamp [0, 360]"; + const dAngle a = dAngle::fromDegrees(390); + ASSERT_EQ( + a.getClamped(dAngle::ZERO, dAngle::HALF).asDegrees(), + 180 + ) << "clamp [0, 180]"; + + const dAngle b = dAngle::fromDegrees(390); + ASSERT_EQ( + b.getClamped(dAngle::ZERO, dAngle::FULL).asDegrees(), + 360 + ) << "clamp [0, 360]"; } \ No newline at end of file diff --git a/tests/test_concurrentjobmanager.inl b/tests/test_concurrentjobmanager.inl index 520c960673..a84ab45fee 100644 --- a/tests/test_concurrentjobmanager.inl +++ b/tests/test_concurrentjobmanager.inl @@ -31,22 +31,12 @@ #include #include - - - class ConcurrentJobManagerTest : public testing::Test {}; - -using namespace openspace; -using namespace std::chrono_literals; - - - -struct TestJob : public Job { +struct TestJob : public openspace::globebrowsing::Job { TestJob(int jobExecutingTime) - : _jobExecutingTime(jobExecutingTime) { - - } + : _jobExecutingTime(jobExecutingTime) + {} virtual void execute() { std::cout << "Executing job ... " << std::endl; @@ -56,7 +46,7 @@ struct TestJob : public Job { std::cout << "Finished job" << std::endl; } - virtual std::shared_ptr product() { + virtual std::shared_ptr product() const { return std::make_shared(prod); } @@ -68,6 +58,7 @@ private: TEST_F(ConcurrentJobManagerTest, Basic) { + using namespace openspace::globebrowsing; std::shared_ptr pool = std::make_shared(1); ConcurrentJobManager jobManager(pool); @@ -95,12 +86,6 @@ TEST_F(ConcurrentJobManagerTest, Basic) { EXPECT_EQ(product, 1337) << "Expecting product to be 1337"; } - - - - - - struct VerboseProduct { VerboseProduct(int v) : val(v){ @@ -115,7 +100,7 @@ struct VerboseProduct { }; -struct VerboseJob : public Job{ +struct VerboseJob : public openspace::globebrowsing::Job{ VerboseJob(int jobExecutingTime) : _jobExecutingTime(jobExecutingTime) { std::cout << "VerboseTestJob constructor" << std::endl; @@ -132,7 +117,7 @@ struct VerboseJob : public Job{ std::cout << " ** Finished job" << std::endl; } - virtual std::shared_ptr product() { + virtual std::shared_ptr product() const { return _product; } @@ -141,12 +126,9 @@ struct VerboseJob : public Job{ }; - - - - - TEST_F(ConcurrentJobManagerTest, JobCreation) { + using namespace openspace::globebrowsing; + std::shared_ptr pool = std::make_shared(1); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); @@ -170,8 +152,6 @@ TEST_F(ConcurrentJobManagerTest, JobCreation) { auto product = finishedJob->product(); } - int a; - } diff --git a/tests/test_concurrentqueue.inl b/tests/test_concurrentqueue.inl index 3415a806fb..fda05e577d 100644 --- a/tests/test_concurrentqueue.inl +++ b/tests/test_concurrentqueue.inl @@ -30,17 +30,11 @@ #include #include - - - class ConcurrentQueueTest : public testing::Test {}; - -using namespace openspace; - - - TEST_F(ConcurrentQueueTest, Basic) { + using namespace openspace::globebrowsing; + ConcurrentQueue q1; q1.push(4); int val = q1.pop(); diff --git a/tests/test_configurationmanager.inl b/tests/test_configurationmanager.inl index 5256234e8a..a43cf73e9b 100644 --- a/tests/test_configurationmanager.inl +++ b/tests/test_configurationmanager.inl @@ -3,7 +3,7 @@ * GHOUL * * General Helpful Open Utility Library * * * - * Copyright (c) 2012-2015 * + * Copyright (c) 2012-2016 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * diff --git a/tests/test_convexhull.inl b/tests/test_convexhull.inl index d4cfdc4dc0..df6493ccb5 100644 --- a/tests/test_convexhull.inl +++ b/tests/test_convexhull.inl @@ -30,13 +30,10 @@ #include #include -using namespace openspace; - class ConvexHull2Test : public testing::Test {}; - - TEST_F(ConvexHull2Test, basic) { + using namespace openspace::globebrowsing; // points // 2 x @@ -44,7 +41,7 @@ TEST_F(ConvexHull2Test, basic) { // 0 x x // -1 0 1 - std::vector points = { + std::vector points = { { -1.0, 0.0 }, { 1.0, 0.0 }, { 0.0, 2.0 }, @@ -68,7 +65,8 @@ TEST_F(ConvexHull2Test, basic) { } TEST_F(ConvexHull2Test, intersection) { - std::vector points1 = { + using namespace openspace::globebrowsing; + std::vector points1 = { { -1.0, 0.0 }, { 1.0, 0.0 }, { 0.0, 2.0 }, @@ -76,7 +74,7 @@ TEST_F(ConvexHull2Test, intersection) { }; ConvexHull2 hull1 = ConvexHull2::grahamScan_NOT_THREAD_SAFE(points1); - std::vector points2 = { + std::vector points2 = { { 0.0, 0.0 }, { 2.0, 0.0 }, { 1.0, 2.0 }, @@ -97,14 +95,15 @@ TEST_F(ConvexHull2Test, intersection) { TEST_F(ConvexHull2Test, non_intersection) { - std::vector points1 = { + using namespace openspace::globebrowsing; + std::vector points1 = { { -2.0, 0.0 }, { 2.0, 0.0 }, { 0.0, 2.0 }, }; ConvexHull2 hull1 = ConvexHull2::grahamScan_NOT_THREAD_SAFE(points1); - std::vector points2 = { + std::vector points2 = { { 1.0, 2.0 }, { 3.0, 0.0 }, { 5.0, 2.0 } diff --git a/tests/test_documentation.inl b/tests/test_documentation.inl index da672ca414..c14af8d1df 100644 --- a/tests/test_documentation.inl +++ b/tests/test_documentation.inl @@ -336,6 +336,63 @@ TEST_F(DocumentationTest, TableVerifierType) { EXPECT_EQ(TestResult::Offense::Reason::MissingKey, negativeRes.offenses[0].reason); } +TEST_F(DocumentationTest, StringListVerifierType) { + using namespace openspace::documentation; + using namespace std::string_literals; + + Documentation doc { + { { "StringList", new StringListVerifier } } + }; + + ghoul::Dictionary positive { + { + "StringList", + ghoul::Dictionary { + { "1", "a"s }, + { "2", "b"s }, + { "3", "c"s } + } + } + }; + TestResult positiveRes = testSpecification(doc, positive); + EXPECT_TRUE(positiveRes.success); + EXPECT_EQ(0, positiveRes.offenses.size()); + + ghoul::Dictionary negative { + { "StringList", 0 } + }; + TestResult negativeRes = testSpecification(doc, negative); + EXPECT_FALSE(negativeRes.success); + ASSERT_EQ(1, negativeRes.offenses.size()); + EXPECT_EQ("StringList", negativeRes.offenses[0].offender); + EXPECT_EQ(TestResult::Offense::Reason::WrongType, negativeRes.offenses[0].reason); + + ghoul::Dictionary negative2 { + { + "StringList", + ghoul::Dictionary { + { "1", "a"s }, + { "2", "b"s }, + { "3", 2.0 } + } + } + }; + negativeRes = testSpecification(doc, negative2); + EXPECT_FALSE(negativeRes.success); + ASSERT_EQ(1, negativeRes.offenses.size()); + EXPECT_EQ("StringList.3", negativeRes.offenses[0].offender); + EXPECT_EQ(TestResult::Offense::Reason::WrongType, negativeRes.offenses[0].reason); + + ghoul::Dictionary negativeExist { + { "StringList2", ghoul::Dictionary{} } + }; + negativeRes = testSpecification(doc, negativeExist); + EXPECT_FALSE(negativeRes.success); + ASSERT_EQ(1, negativeRes.offenses.size()); + EXPECT_EQ("StringList", negativeRes.offenses[0].offender); + EXPECT_EQ(TestResult::Offense::Reason::MissingKey, negativeRes.offenses[0].reason); +} + TEST_F(DocumentationTest, MixedVerifiers) { using namespace openspace::documentation; using namespace std::string_literals; @@ -2308,6 +2365,303 @@ TEST_F(DocumentationTest, DoubleVector4Verifier) { EXPECT_EQ(TestResult::Offense::Reason::WrongType, negativeRes.offenses[0].reason); } +TEST_F(DocumentationTest, DoubleMatrix2x2Verifier) { + using namespace openspace::documentation; + + Documentation doc { + { { "a", new DoubleMatrix2x2Verifier } } + }; + + ghoul::Dictionary positive { + { "a", glm::dmat2x2(1.0) } + }; + TestResult positiveRes = testSpecification(doc, positive); + EXPECT_TRUE(positiveRes.success); + EXPECT_EQ(0, positiveRes.offenses.size()); + + ghoul::Dictionary negative { + { "a", ghoul::Dictionary { { "1", true },{ "2", 1.0 },{ "3", "s" } } } + }; + TestResult negativeRes = testSpecification(doc, negative); + EXPECT_FALSE(negativeRes.success); + ASSERT_EQ(1, negativeRes.offenses.size()); + EXPECT_EQ("a", negativeRes.offenses[0].offender); + EXPECT_EQ(TestResult::Offense::Reason::WrongType, negativeRes.offenses[0].reason); + + ghoul::Dictionary negative2 { + { "a", true } + }; + negativeRes = testSpecification(doc, negative2); + EXPECT_FALSE(negativeRes.success); + ASSERT_EQ(1, negativeRes.offenses.size()); + EXPECT_EQ("a", negativeRes.offenses[0].offender); + EXPECT_EQ(TestResult::Offense::Reason::WrongType, negativeRes.offenses[0].reason); +} + +TEST_F(DocumentationTest, DoubleMatrix2x3Verifier) { + using namespace openspace::documentation; + + Documentation doc { + { { "a", new DoubleMatrix2x3Verifier } } + }; + + ghoul::Dictionary positive { + { "a", glm::dmat2x3(1.0) } + }; + TestResult positiveRes = testSpecification(doc, positive); + EXPECT_TRUE(positiveRes.success); + EXPECT_EQ(0, positiveRes.offenses.size()); + + ghoul::Dictionary negative { + { "a", ghoul::Dictionary{ { "1", true },{ "2", 1.0 },{ "3", "s" } } } + }; + TestResult negativeRes = testSpecification(doc, negative); + EXPECT_FALSE(negativeRes.success); + ASSERT_EQ(1, negativeRes.offenses.size()); + EXPECT_EQ("a", negativeRes.offenses[0].offender); + EXPECT_EQ(TestResult::Offense::Reason::WrongType, negativeRes.offenses[0].reason); + + ghoul::Dictionary negative2 { + { "a", true } + }; + negativeRes = testSpecification(doc, negative2); + EXPECT_FALSE(negativeRes.success); + ASSERT_EQ(1, negativeRes.offenses.size()); + EXPECT_EQ("a", negativeRes.offenses[0].offender); + EXPECT_EQ(TestResult::Offense::Reason::WrongType, negativeRes.offenses[0].reason); +} + +TEST_F(DocumentationTest, DoubleMatrix2x4Verifier) { + using namespace openspace::documentation; + + Documentation doc { + { { "a", new DoubleMatrix2x4Verifier } } + }; + + ghoul::Dictionary positive { + { "a", glm::dmat2x4(1.0) } + }; + TestResult positiveRes = testSpecification(doc, positive); + EXPECT_TRUE(positiveRes.success); + EXPECT_EQ(0, positiveRes.offenses.size()); + + ghoul::Dictionary negative { + { "a", ghoul::Dictionary{ { "1", true },{ "2", 1.0 },{ "3", "s" } } } + }; + TestResult negativeRes = testSpecification(doc, negative); + EXPECT_FALSE(negativeRes.success); + ASSERT_EQ(1, negativeRes.offenses.size()); + EXPECT_EQ("a", negativeRes.offenses[0].offender); + EXPECT_EQ(TestResult::Offense::Reason::WrongType, negativeRes.offenses[0].reason); + + ghoul::Dictionary negative2 { + { "a", true } + }; + negativeRes = testSpecification(doc, negative2); + EXPECT_FALSE(negativeRes.success); + ASSERT_EQ(1, negativeRes.offenses.size()); + EXPECT_EQ("a", negativeRes.offenses[0].offender); + EXPECT_EQ(TestResult::Offense::Reason::WrongType, negativeRes.offenses[0].reason); +} + +TEST_F(DocumentationTest, DoubleMatrix3x2Verifier) { + using namespace openspace::documentation; + + Documentation doc { + { { "a", new DoubleMatrix3x2Verifier } } + }; + + ghoul::Dictionary positive { + { "a", glm::dmat3x2(1.0) } + }; + TestResult positiveRes = testSpecification(doc, positive); + EXPECT_TRUE(positiveRes.success); + EXPECT_EQ(0, positiveRes.offenses.size()); + + ghoul::Dictionary negative { + { "a", ghoul::Dictionary{ { "1", true },{ "2", 1.0 },{ "3", "s" } } } + }; + TestResult negativeRes = testSpecification(doc, negative); + EXPECT_FALSE(negativeRes.success); + ASSERT_EQ(1, negativeRes.offenses.size()); + EXPECT_EQ("a", negativeRes.offenses[0].offender); + EXPECT_EQ(TestResult::Offense::Reason::WrongType, negativeRes.offenses[0].reason); + + ghoul::Dictionary negative2 { + { "a", true } + }; + negativeRes = testSpecification(doc, negative2); + EXPECT_FALSE(negativeRes.success); + ASSERT_EQ(1, negativeRes.offenses.size()); + EXPECT_EQ("a", negativeRes.offenses[0].offender); + EXPECT_EQ(TestResult::Offense::Reason::WrongType, negativeRes.offenses[0].reason); +} + +TEST_F(DocumentationTest, DoubleMatrix3x3Verifier) { + using namespace openspace::documentation; + + Documentation doc { + { { "a", new DoubleMatrix3x3Verifier } } + }; + + ghoul::Dictionary positive { + { "a", glm::dmat3x3(1.0) } + }; + TestResult positiveRes = testSpecification(doc, positive); + EXPECT_TRUE(positiveRes.success); + EXPECT_EQ(0, positiveRes.offenses.size()); + + ghoul::Dictionary negative { + { "a", ghoul::Dictionary{ { "1", true },{ "2", 1.0 },{ "3", "s" } } } + }; + TestResult negativeRes = testSpecification(doc, negative); + EXPECT_FALSE(negativeRes.success); + ASSERT_EQ(1, negativeRes.offenses.size()); + EXPECT_EQ("a", negativeRes.offenses[0].offender); + EXPECT_EQ(TestResult::Offense::Reason::WrongType, negativeRes.offenses[0].reason); + + ghoul::Dictionary negative2 { + { "a", true } + }; + negativeRes = testSpecification(doc, negative2); + EXPECT_FALSE(negativeRes.success); + ASSERT_EQ(1, negativeRes.offenses.size()); + EXPECT_EQ("a", negativeRes.offenses[0].offender); + EXPECT_EQ(TestResult::Offense::Reason::WrongType, negativeRes.offenses[0].reason); +} + +TEST_F(DocumentationTest, DoubleMatrix3x4Verifier) { + using namespace openspace::documentation; + + Documentation doc { + { { "a", new DoubleMatrix3x4Verifier } } + }; + + ghoul::Dictionary positive { + { "a", glm::dmat3x4(1.0) } + }; + TestResult positiveRes = testSpecification(doc, positive); + EXPECT_TRUE(positiveRes.success); + EXPECT_EQ(0, positiveRes.offenses.size()); + + ghoul::Dictionary negative { + { "a", ghoul::Dictionary{ { "1", true },{ "2", 1.0 },{ "3", "s" } } } + }; + TestResult negativeRes = testSpecification(doc, negative); + EXPECT_FALSE(negativeRes.success); + ASSERT_EQ(1, negativeRes.offenses.size()); + EXPECT_EQ("a", negativeRes.offenses[0].offender); + EXPECT_EQ(TestResult::Offense::Reason::WrongType, negativeRes.offenses[0].reason); + + ghoul::Dictionary negative2 { + { "a", true } + }; + negativeRes = testSpecification(doc, negative2); + EXPECT_FALSE(negativeRes.success); + ASSERT_EQ(1, negativeRes.offenses.size()); + EXPECT_EQ("a", negativeRes.offenses[0].offender); + EXPECT_EQ(TestResult::Offense::Reason::WrongType, negativeRes.offenses[0].reason); +} + +TEST_F(DocumentationTest, DoubleMatrix4x2Verifier) { + using namespace openspace::documentation; + + Documentation doc { + { { "a", new DoubleMatrix4x2Verifier } } + }; + + ghoul::Dictionary positive { + { "a", glm::dmat4x2(1.0) } + }; + TestResult positiveRes = testSpecification(doc, positive); + EXPECT_TRUE(positiveRes.success); + EXPECT_EQ(0, positiveRes.offenses.size()); + + ghoul::Dictionary negative { + { "a", ghoul::Dictionary{ { "1", true },{ "2", 1.0 },{ "3", "s" } } } + }; + TestResult negativeRes = testSpecification(doc, negative); + EXPECT_FALSE(negativeRes.success); + ASSERT_EQ(1, negativeRes.offenses.size()); + EXPECT_EQ("a", negativeRes.offenses[0].offender); + EXPECT_EQ(TestResult::Offense::Reason::WrongType, negativeRes.offenses[0].reason); + + ghoul::Dictionary negative2 { + { "a", true } + }; + negativeRes = testSpecification(doc, negative2); + EXPECT_FALSE(negativeRes.success); + ASSERT_EQ(1, negativeRes.offenses.size()); + EXPECT_EQ("a", negativeRes.offenses[0].offender); + EXPECT_EQ(TestResult::Offense::Reason::WrongType, negativeRes.offenses[0].reason); +} + +TEST_F(DocumentationTest, DoubleMatrix4x3Verifier) { + using namespace openspace::documentation; + + Documentation doc { + { { "a", new DoubleMatrix4x3Verifier } } + }; + + ghoul::Dictionary positive { + { "a", glm::dmat4x3(1.0) } + }; + TestResult positiveRes = testSpecification(doc, positive); + EXPECT_TRUE(positiveRes.success); + EXPECT_EQ(0, positiveRes.offenses.size()); + + ghoul::Dictionary negative { + { "a", ghoul::Dictionary{ { "1", true },{ "2", 1.0 },{ "3", "s" } } } + }; + TestResult negativeRes = testSpecification(doc, negative); + EXPECT_FALSE(negativeRes.success); + ASSERT_EQ(1, negativeRes.offenses.size()); + EXPECT_EQ("a", negativeRes.offenses[0].offender); + EXPECT_EQ(TestResult::Offense::Reason::WrongType, negativeRes.offenses[0].reason); + + ghoul::Dictionary negative2 { + { "a", true } + }; + negativeRes = testSpecification(doc, negative2); + EXPECT_FALSE(negativeRes.success); + ASSERT_EQ(1, negativeRes.offenses.size()); + EXPECT_EQ("a", negativeRes.offenses[0].offender); + EXPECT_EQ(TestResult::Offense::Reason::WrongType, negativeRes.offenses[0].reason); +} + +TEST_F(DocumentationTest, DoubleMatrix4x4Verifier) { + using namespace openspace::documentation; + + Documentation doc { + { { "a", new DoubleMatrix4x4Verifier } } + }; + + ghoul::Dictionary positive { + { "a", glm::dmat4x4(1.0) } + }; + TestResult positiveRes = testSpecification(doc, positive); + EXPECT_TRUE(positiveRes.success); + EXPECT_EQ(0, positiveRes.offenses.size()); + + ghoul::Dictionary negative { + { "a", ghoul::Dictionary{ { "1", true },{ "2", 1.0 },{ "3", "s" } } } + }; + TestResult negativeRes = testSpecification(doc, negative); + EXPECT_FALSE(negativeRes.success); + ASSERT_EQ(1, negativeRes.offenses.size()); + EXPECT_EQ("a", negativeRes.offenses[0].offender); + EXPECT_EQ(TestResult::Offense::Reason::WrongType, negativeRes.offenses[0].reason); + + ghoul::Dictionary negative2 { + { "a", true } + }; + negativeRes = testSpecification(doc, negative2); + EXPECT_FALSE(negativeRes.success); + ASSERT_EQ(1, negativeRes.offenses.size()); + EXPECT_EQ("a", negativeRes.offenses[0].offender); + EXPECT_EQ(TestResult::Offense::Reason::WrongType, negativeRes.offenses[0].reason); +} + TEST_F(DocumentationTest, DeprecatedVerifier) { using namespace openspace::documentation; using namespace std::string_literals; diff --git a/tests/test_lrucache.inl b/tests/test_lrucache.inl index 6420e1febf..53151b86ee 100644 --- a/tests/test_lrucache.inl +++ b/tests/test_lrucache.inl @@ -32,72 +32,65 @@ class LRUCacheTest : public testing::Test {}; -using namespace openspace; - TEST_F(LRUCacheTest, Get) { - LRUCache lru(4); - lru.put(1, "hej"); - lru.put(12, "san"); - ASSERT_STREQ(lru.get(1).c_str(), "hej") << "testing get"; + openspace::globebrowsing::LRUCache lru(4); + lru.put(1, "hej"); + lru.put(12, "san"); + ASSERT_STREQ(lru.get(1).c_str(), "hej") << "testing get"; } TEST_F(LRUCacheTest, CleaningCache) { - LRUCache lru(4); - lru.put(1, 1.2); - lru.put(12, 2.3); - lru.put(123, 33.4); - lru.put(1234, 4.5); - lru.put(12345, 6.7); - ASSERT_FALSE(lru.exist(1)) << "Element should have been cleaned out of cache"; - ASSERT_TRUE(lru.exist(12)) << "Element should remain in cache"; + openspace::globebrowsing::LRUCache lru(4); + lru.put(1, 1.2); + lru.put(12, 2.3); + lru.put(123, 33.4); + lru.put(1234, 4.5); + lru.put(12345, 6.7); + ASSERT_FALSE(lru.exist(1)) << "Element should have been cleaned out of cache"; + ASSERT_TRUE(lru.exist(12)) << "Element should remain in cache"; } - - - - struct MyKey { - int x, y; + int x, y; }; bool operator==(const MyKey& a, const MyKey& b) { - return a.x == b.x && a.y == b.y; + return a.x == b.x && a.y == b.y; } std::ostream& operator<<(std::ostream& o, const MyKey& key) { - return o << key.x << ", " << key.y; + return o << key.x << ", " << key.y; } // custom specialization of std::hash can be injected in namespace std namespace std { - template<> struct hash { - std::size_t operator()(MyKey const& s) const { - return s.x ^ (s.y << 1); - } - }; + template<> struct hash { + std::size_t operator()(MyKey const& s) const { + return s.x ^ (s.y << 1); + } + }; } TEST_F(LRUCacheTest, StructKey) { + openspace::globebrowsing::LRUCache lru(4); - LRUCache lru(4); + // These two custom keys should be treated as equal + MyKey key1 = { 2, 3 }; + MyKey key2 = { 2, 3 }; - // These two custom keys should be treated as equal - MyKey key1 = { 2, 3 }; - MyKey key2 = { 2, 3 }; - - std::string val1 = "value 1"; - std::string val2 = "value 2"; + std::string val1 = "value 1"; + std::string val2 = "value 2"; - lru.put(key1, val1); - ASSERT_TRUE(lru.exist(key1)); - ASSERT_EQ(lru.get(key1), val1); + lru.put(key1, val1); + ASSERT_TRUE(lru.exist(key1)); + ASSERT_EQ(lru.get(key1), val1); - // Putting key2 should replace key1 - lru.put(key2, val2); - ASSERT_EQ(key1, key2) << "key 1 and key2 should be considered equal"; - ASSERT_TRUE(lru.exist(key2)); - ASSERT_EQ(lru.get(key1), val2); - ASSERT_EQ(lru.get(key2), val2); - + // Putting key2 should replace key1 + lru.put(key2, val2); + ASSERT_EQ(key1, key2) << "key 1 and key2 should be considered equal"; + ASSERT_TRUE(lru.exist(key2)); + ASSERT_EQ(lru.get(key1), val2); + ASSERT_EQ(lru.get(key2), val2); + } \ No newline at end of file diff --git a/tests/test_scriptscheduler.inl b/tests/test_scriptscheduler.inl new file mode 100644 index 0000000000..1dee4d8cc8 --- /dev/null +++ b/tests/test_scriptscheduler.inl @@ -0,0 +1,806 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include "gtest/gtest.h" + +#include + +// This include should be removed after the time class is not dependent on +// Spice anymore +#include +#include +#include + +#include + +class ScriptSchedulerTest : public testing::Test { +protected: + void SetUp() override { + openspace::SpiceManager::initialize(); + openspace::SpiceManager::ref().loadKernel( + "${TESTDIR}/SpiceTest/spicekernels/naif0008.tls" + ); + } + + void TearDown() override { + openspace::SpiceManager::deinitialize(); + } +}; + +TEST_F(ScriptSchedulerTest, SimpleForward) { + using namespace openspace::scripting; + using namespace std::string_literals; + + ScriptScheduler scheduler; + + ghoul::Dictionary testDictionary = { + { "Time", "2000 JAN 03"s }, + { "ForwardScript", "ForwardScript1"s }, + { "BackwardScript", "BackwardScript1"s } + }; + + scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 01")); + scheduler.loadScripts({ + { "1", testDictionary } + }); + + auto res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 02")); + ASSERT_EQ(res.first, res.second); + + res = scheduler.progressTo( + openspace::Time::ref().convertTime("2000 JAN 03") + ); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("ForwardScript1", *(res.first)); +} + +TEST_F(ScriptSchedulerTest, MultipleForwardSingleJump) { + using namespace openspace::scripting; + using namespace std::string_literals; + + ghoul::Dictionary testDictionary1 = { + { "Time", "2000 JAN 03"s }, + { "ForwardScript", "ForwardScript1"s }, + { "BackwardScript", "BackwardScript1"s } + }; + + ghoul::Dictionary testDictionary2 = { + { "Time", "2000 JAN 05"s }, + { "ForwardScript", "ForwardScript2"s }, + { "BackwardScript", "BackwardScript2"s } + + }; + + ScriptScheduler scheduler; + + scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 01")); + scheduler.loadScripts({ + { "1", testDictionary1 }, + { "2", testDictionary2 } + }); + + auto res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 02")); + ASSERT_EQ(res.first, res.second); + + res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 04")); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("ForwardScript1", *(res.first)); + + res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 06")); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("ForwardScript2", *(res.first)); +} + +TEST_F(ScriptSchedulerTest, MultipleForwardOrdering) { + using namespace openspace::scripting; + using namespace std::string_literals; + + ghoul::Dictionary testDictionary1 = { + { "Time", "2000 JAN 03"s }, + { "ForwardScript", "ForwardScript1"s }, + { "BackwardScript", "BackwardScript1"s } + }; + + ghoul::Dictionary testDictionary2 = { + { "Time", "2000 JAN 05"s }, + { "ForwardScript", "ForwardScript2"s }, + { "BackwardScript", "BackwardScript2"s } + }; + + ScriptScheduler scheduler; + + scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 01")); + scheduler.loadScripts({ + { "1", testDictionary1 }, + { "2", testDictionary2 } + }); + + auto res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 02")); + ASSERT_EQ(res.first, res.second); + + res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 06")); + ASSERT_EQ(2, std::distance(res.first, res.second)); + EXPECT_EQ("ForwardScript1", *(res.first)); + EXPECT_EQ("ForwardScript2", *(std::next(res.first))); +} + +TEST_F(ScriptSchedulerTest, SimpleBackward) { + using namespace openspace::scripting; + using namespace std::string_literals; + + ScriptScheduler scheduler; + + ghoul::Dictionary testDictionary = { + { "Time", "2000 JAN 03"s }, + { "ForwardScript", "ForwardScript1"s }, + { "BackwardScript", "BackwardScript1"s } + }; + + scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 05")); + scheduler.loadScripts({ + { "1", testDictionary } + }); + + auto res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 04")); + ASSERT_EQ(res.first, res.second); + + res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 02")); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("BackwardScript1", *(res.first)); +} + +TEST_F(ScriptSchedulerTest, MultipleBackwardSingleJump) { + using namespace openspace::scripting; + using namespace std::string_literals; + + ScriptScheduler scheduler; + + ghoul::Dictionary testDictionary1 = { + { "Time", "2000 JAN 03"s }, + { "ForwardScript", "ForwardScript1"s }, + { "BackwardScript", "BackwardScript1"s } + }; + + ghoul::Dictionary testDictionary2 = { + { "Time", "2000 JAN 05"s }, + { "ForwardScript", "ForwardScript2"s }, + { "BackwardScript", "BackwardScript2"s } + }; + + scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 07")); + scheduler.loadScripts({ + { "1", testDictionary1 }, + { "2", testDictionary2 } + }); + + auto res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 06")); + ASSERT_EQ(res.first, res.second); + + res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 04")); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("BackwardScript2", *(res.first)); + + res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 01")); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("BackwardScript1", *(res.first)); +} + +TEST_F(ScriptSchedulerTest, MultipleBackwardOrdering) { + using namespace openspace::scripting; + using namespace std::string_literals; + + ScriptScheduler scheduler; + + ghoul::Dictionary testDictionary1 = { + { "Time", "2000 JAN 03"s }, + { "ForwardScript", "ForwardScript1"s }, + { "BackwardScript", "BackwardScript1"s } + }; + + ghoul::Dictionary testDictionary2 = { + { "Time", "2000 JAN 05"s }, + { "ForwardScript", "ForwardScript2"s }, + { "BackwardScript", "BackwardScript2"s } + }; + + scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 07")); + scheduler.loadScripts({ + { "1", testDictionary1 }, + { "2", testDictionary2 } + }); + + auto res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 06")); + ASSERT_EQ(res.first, res.second); + + res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 01")); + ASSERT_EQ(2, std::distance(res.first, res.second)); + EXPECT_EQ("BackwardScript2", *(res.first)); + EXPECT_EQ("BackwardScript1", *(std::next(res.first))); +} + +TEST_F(ScriptSchedulerTest, Empty) { + using namespace openspace::scripting; + + static const std::vector TestTimes = { + 0.0, 1.0, -1.0, std::numeric_limits::min(), + -std::numeric_limits::max(), std::numeric_limits::max() + }; + + // First test if a new ScriptScheduler will return an empty list + for (double t : TestTimes) { + ScriptScheduler scheduler; + auto res = scheduler.progressTo(t); + EXPECT_EQ(res.first, res.second); + } + + // Then test the same thing but keeping the same ScriptScheduler + ScriptScheduler scheduler; + for (double t : TestTimes) { + auto res = scheduler.progressTo(t); + EXPECT_EQ(res.first, res.second); + } +} + +TEST_F(ScriptSchedulerTest, ForwardBackwards) { + using namespace openspace::scripting; + using namespace std::string_literals; + + ScriptScheduler scheduler; + + ghoul::Dictionary testDictionary1 = { + { "Time", "2000 JAN 03"s }, + { "ForwardScript", "ForwardScript1"s }, + { "BackwardScript", "BackwardScript1"s } + }; + + ghoul::Dictionary testDictionary2 = { + { "Time", "2000 JAN 05"s }, + { "ForwardScript", "ForwardScript2"s }, + { "BackwardScript", "BackwardScript2"s } + }; + + scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 01")); + scheduler.loadScripts({ + { "1", testDictionary1 }, + { "2", testDictionary2 } + }); + + auto res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 04")); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("ForwardScript1", *(res.first)); + + res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 01")); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("BackwardScript1", *(res.first)); + + res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 07")); + ASSERT_EQ(2, std::distance(res.first, res.second)); + + res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 04")); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("BackwardScript2", *(res.first)); +} + +TEST_F(ScriptSchedulerTest, Rewind) { + using namespace openspace::scripting; + using namespace std::string_literals; + + ScriptScheduler scheduler; + + ghoul::Dictionary testDictionary1 = { + { "Time", "2000 JAN 03"s }, + { "ForwardScript", "ForwardScript1"s }, + { "BackwardScript", "BackwardScript1"s } + }; + + ghoul::Dictionary testDictionary2 = { + { "Time", "2000 JAN 05"s }, + { "ForwardScript", "ForwardScript2"s }, + { "BackwardScript", "BackwardScript2"s } + }; + + scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 01")); + scheduler.loadScripts({ + { "1", testDictionary1 }, + { "2", testDictionary2 } + }); + + auto res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 07")); + ASSERT_EQ(2, std::distance(res.first, res.second)); + + scheduler.rewind(); + + res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 04")); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("ForwardScript1", *(res.first)); +} + +TEST_F(ScriptSchedulerTest, CurrentTime) { + using namespace openspace::scripting; + + static const std::vector TestValues = { + 0.0, 1.0, 42.0, std::numeric_limits::min(), + -std::numeric_limits::max(), std::numeric_limits::max() + }; + + for (double t : TestValues) { + ScriptScheduler scheduler; + scheduler.progressTo(t); + EXPECT_EQ(t, scheduler.currentTime()); + } +} + +TEST_F(ScriptSchedulerTest, AllScripts) { + using namespace openspace::scripting; + using namespace std::string_literals; + + ScriptScheduler scheduler; + + + ghoul::Dictionary testDictionary1 = { + { "Time", "2000 JAN 03"s }, + { "ForwardScript", "ForwardScript1"s }, + { "BackwardScript", "BackwardScript1"s } + }; + + ghoul::Dictionary testDictionary2 = { + { "Time", "2000 JAN 05"s }, + { "ForwardScript", "ForwardScript2"s }, + { "BackwardScript", "BackwardScript2"s } + }; + + ghoul::Dictionary testDictionary3 = { + { "Time", "2000 JAN 10"s }, + { "ForwardScript", "ForwardScript3"s }, + { "BackwardScript", "BackwardScript3"s } + }; + + scheduler.loadScripts({ + { "1", testDictionary1 }, + { "2", testDictionary2 }, + { "3", testDictionary3 } + }); + + auto allScripts = scheduler.allScripts(); + ASSERT_EQ(3, allScripts.size()); + + EXPECT_LE(allScripts[0].time, allScripts[1].time); + EXPECT_LE(allScripts[1].time, allScripts[2].time); +} + +TEST_F(ScriptSchedulerTest, JumpEqual) { + using namespace openspace::scripting; + using namespace std::string_literals; + + ScriptScheduler scheduler; + + ghoul::Dictionary testDictionary1 = { + { "Time", "2000 JAN 03 12:00:00"s }, + { "ForwardScript", "ForwardScript1"s }, + { "BackwardScript", "BackwardScript1"s } + }; + + scheduler.loadScripts({ + { "1", testDictionary1 } + }); + + auto res = scheduler.progressTo( + openspace::Time::ref().convertTime("2000 JAN 03 11:00:00") + ); + ASSERT_EQ(res.first, res.second); + + res = scheduler.progressTo( + openspace::Time::ref().convertTime("2000 JAN 03 12:00:00") + ); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("ForwardScript1", *(res.first)); + + res = scheduler.progressTo( + openspace::Time::ref().convertTime("2000 JAN 03 12:01:00") + ); + ASSERT_EQ(res.first, res.second); + + res = scheduler.progressTo( + openspace::Time::ref().convertTime("2000 JAN 03 12:00:00") + ); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("BackwardScript1", *(res.first)); +} + +TEST_F(ScriptSchedulerTest, SameTime) { + using namespace openspace::scripting; + using namespace std::string_literals; + + ScriptScheduler scheduler; + + ghoul::Dictionary testDictionary1 = { + { "Time", "2000 JAN 03 12:00:00"s }, + { "ForwardScript", "ForwardScript1"s }, + { "BackwardScript", "BackwardScript1"s } + }; + + scheduler.loadScripts({ + { "1", testDictionary1 } + }); + + auto res = scheduler.progressTo( + openspace::Time::ref().convertTime("2000 JAN 03 12:00:00") + ); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("ForwardScript1", *(res.first)); + + res = scheduler.progressTo( + openspace::Time::ref().convertTime("2000 JAN 03 12:00:00") + ); + ASSERT_EQ(res.first, res.second); +} + +TEST_F(ScriptSchedulerTest, MultiInnerJump) { + using namespace openspace::scripting; + using namespace std::string_literals; + + ScriptScheduler scheduler; + + ghoul::Dictionary testDictionary1 = { + { "Time", "2000 JAN 03 12:00:00"s }, + { "ForwardScript", "ForwardScript1"s }, + { "BackwardScript", "BackwardScript1"s } + }; + + scheduler.loadScripts({ + { "1", testDictionary1 } + }); + + auto res = scheduler.progressTo( + openspace::Time::ref().convertTime("2000 JAN 03 10:00:00") + ); + ASSERT_EQ(res.first, res.second); + + res = scheduler.progressTo( + openspace::Time::ref().convertTime("2000 JAN 03 11:00:00") + ); + ASSERT_EQ(res.first, res.second); + + res = scheduler.progressTo( + openspace::Time::ref().convertTime("2000 JAN 03 13:00:00") + ); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("ForwardScript1", *(res.first)); + + res = scheduler.progressTo( + openspace::Time::ref().convertTime("2000 JAN 03 12:30:00") + ); + ASSERT_EQ(res.first, res.second); +} + +TEST_F(ScriptSchedulerTest, MultipleForwardSingleJumpMultipleLoad) { + using namespace openspace::scripting; + using namespace std::string_literals; + + ghoul::Dictionary testDictionary1 = { + { "Time", "2000 JAN 03"s }, + { "ForwardScript", "ForwardScript1"s }, + { "BackwardScript", "BackwardScript1"s } + }; + + ghoul::Dictionary testDictionary2 = { + { "Time", "2000 JAN 05"s }, + { "ForwardScript", "ForwardScript2"s }, + { "BackwardScript", "BackwardScript2"s } + + }; + + ScriptScheduler scheduler; + + scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 01")); + scheduler.loadScripts({ + { "1", testDictionary1 } + }); + + scheduler.loadScripts({ + { "1", testDictionary2 } + }); + + auto res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 02")); + ASSERT_EQ(res.first, res.second); + + res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 04")); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("ForwardScript1", *(res.first)); + + res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 06")); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("ForwardScript2", *(res.first)); +} + +TEST_F(ScriptSchedulerTest, MultipleForwardOrderingMultipleLoad) { + using namespace openspace::scripting; + using namespace std::string_literals; + + ghoul::Dictionary testDictionary1 = { + { "Time", "2000 JAN 03"s }, + { "ForwardScript", "ForwardScript1"s }, + { "BackwardScript", "BackwardScript1"s } + }; + + ghoul::Dictionary testDictionary2 = { + { "Time", "2000 JAN 05"s }, + { "ForwardScript", "ForwardScript2"s }, + { "BackwardScript", "BackwardScript2"s } + }; + + ScriptScheduler scheduler; + + scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 01")); + scheduler.loadScripts({ + { "1", testDictionary1 } + }); + scheduler.loadScripts({ + { "1", testDictionary2 } + }); + + auto res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 02")); + ASSERT_EQ(res.first, res.second); + + res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 06")); + ASSERT_EQ(2, std::distance(res.first, res.second)); + EXPECT_EQ("ForwardScript1", *(res.first)); + EXPECT_EQ("ForwardScript2", *(std::next(res.first))); +} + +TEST_F(ScriptSchedulerTest, MultipleBackwardSingleJumpMultipleLoad) { + using namespace openspace::scripting; + using namespace std::string_literals; + + ScriptScheduler scheduler; + + ghoul::Dictionary testDictionary1 = { + { "Time", "2000 JAN 03"s }, + { "ForwardScript", "ForwardScript1"s }, + { "BackwardScript", "BackwardScript1"s } + }; + + ghoul::Dictionary testDictionary2 = { + { "Time", "2000 JAN 05"s }, + { "ForwardScript", "ForwardScript2"s }, + { "BackwardScript", "BackwardScript2"s } + }; + + scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 07")); + scheduler.loadScripts({ + { "1", testDictionary1 } + }); + scheduler.loadScripts({ + { "1", testDictionary2 } + }); + + auto res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 06")); + ASSERT_EQ(res.first, res.second); + + res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 04")); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("BackwardScript2", *(res.first)); + + res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 01")); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("BackwardScript1", *(res.first)); +} + +TEST_F(ScriptSchedulerTest, MultipleBackwardOrderingMultipleLoad) { + using namespace openspace::scripting; + using namespace std::string_literals; + + ScriptScheduler scheduler; + + ghoul::Dictionary testDictionary1 = { + { "Time", "2000 JAN 03"s }, + { "ForwardScript", "ForwardScript1"s }, + { "BackwardScript", "BackwardScript1"s } + }; + + ghoul::Dictionary testDictionary2 = { + { "Time", "2000 JAN 05"s }, + { "ForwardScript", "ForwardScript2"s }, + { "BackwardScript", "BackwardScript2"s } + }; + + scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 07")); + scheduler.loadScripts({ + { "1", testDictionary1 } + }); + scheduler.loadScripts({ + { "1", testDictionary2 } + }); + + auto res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 06")); + ASSERT_EQ(res.first, res.second); + + res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 01")); + ASSERT_EQ(2, std::distance(res.first, res.second)); + EXPECT_EQ("BackwardScript2", *(res.first)); + EXPECT_EQ("BackwardScript1", *(std::next(res.first))); +} + +TEST_F(ScriptSchedulerTest, ForwardBackwardsMultipleLoad) { + using namespace openspace::scripting; + using namespace std::string_literals; + + ScriptScheduler scheduler; + + ghoul::Dictionary testDictionary1 = { + { "Time", "2000 JAN 03"s }, + { "ForwardScript", "ForwardScript1"s }, + { "BackwardScript", "BackwardScript1"s } + }; + + ghoul::Dictionary testDictionary2 = { + { "Time", "2000 JAN 05"s }, + { "ForwardScript", "ForwardScript2"s }, + { "BackwardScript", "BackwardScript2"s } + }; + + scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 01")); + scheduler.loadScripts({ + { "1", testDictionary1 } + }); + scheduler.loadScripts({ + { "1", testDictionary2 } + }); + + auto res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 04")); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("ForwardScript1", *(res.first)); + + res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 01")); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("BackwardScript1", *(res.first)); + + res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 07")); + ASSERT_EQ(2, std::distance(res.first, res.second)); + + res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 04")); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("BackwardScript2", *(res.first)); +} + +TEST_F(ScriptSchedulerTest, RewindMultipleLoad) { + using namespace openspace::scripting; + using namespace std::string_literals; + + ScriptScheduler scheduler; + + ghoul::Dictionary testDictionary1 = { + { "Time", "2000 JAN 03"s }, + { "ForwardScript", "ForwardScript1"s }, + { "BackwardScript", "BackwardScript1"s } + }; + + ghoul::Dictionary testDictionary2 = { + { "Time", "2000 JAN 05"s }, + { "ForwardScript", "ForwardScript2"s }, + { "BackwardScript", "BackwardScript2"s } + }; + + scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 01")); + scheduler.loadScripts({ + { "1", testDictionary1 } + }); + scheduler.loadScripts({ + { "1", testDictionary2 } + }); + + auto res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 07")); + ASSERT_EQ(2, std::distance(res.first, res.second)); + + scheduler.rewind(); + + res = scheduler.progressTo(openspace::Time::ref().convertTime("2000 JAN 04")); + ASSERT_EQ(1, std::distance(res.first, res.second)); + EXPECT_EQ("ForwardScript1", *(res.first)); +} + +TEST_F(ScriptSchedulerTest, AllScriptsMultipleLoad) { + using namespace openspace::scripting; + using namespace std::string_literals; + + ScriptScheduler scheduler; + + + ghoul::Dictionary testDictionary1 = { + { "Time", "2000 JAN 03"s }, + { "ForwardScript", "ForwardScript1"s }, + { "BackwardScript", "BackwardScript1"s } + }; + + ghoul::Dictionary testDictionary2 = { + { "Time", "2000 JAN 05"s }, + { "ForwardScript", "ForwardScript2"s }, + { "BackwardScript", "BackwardScript2"s } + }; + + ghoul::Dictionary testDictionary3 = { + { "Time", "2000 JAN 10"s }, + { "ForwardScript", "ForwardScript3"s }, + { "BackwardScript", "BackwardScript3"s } + }; + + scheduler.loadScripts({ + { "1", testDictionary1 } + }); + + scheduler.loadScripts({ + { "1", testDictionary2 } + }); + + scheduler.loadScripts({ + { "1", testDictionary3 } + }); + + auto allScripts = scheduler.allScripts(); + ASSERT_EQ(3, allScripts.size()); + + EXPECT_LE(allScripts[0].time, allScripts[1].time); + EXPECT_LE(allScripts[1].time, allScripts[2].time); +} + +TEST_F(ScriptSchedulerTest, AllScriptsMixedLoad) { + using namespace openspace::scripting; + using namespace std::string_literals; + + ScriptScheduler scheduler; + + + ghoul::Dictionary testDictionary1 = { + { "Time", "2000 JAN 03"s }, + { "ForwardScript", "ForwardScript1"s }, + { "BackwardScript", "BackwardScript1"s } + }; + + ghoul::Dictionary testDictionary2 = { + { "Time", "2000 JAN 05"s }, + { "ForwardScript", "ForwardScript2"s }, + { "BackwardScript", "BackwardScript2"s } + }; + + ghoul::Dictionary testDictionary3 = { + { "Time", "2000 JAN 10"s }, + { "ForwardScript", "ForwardScript3"s }, + { "BackwardScript", "BackwardScript3"s } + }; + + scheduler.loadScripts({ + { "1", testDictionary1 } + }); + + scheduler.loadScripts({ + { "1", testDictionary2 }, + { "2", testDictionary3 } + }); + + auto allScripts = scheduler.allScripts(); + ASSERT_EQ(3, allScripts.size()); + + EXPECT_LE(allScripts[0].time, allScripts[1].time); + EXPECT_LE(allScripts[1].time, allScripts[2].time); +} diff --git a/tests/test_spicemanager.inl b/tests/test_spicemanager.inl index c488c0c51c..8fd60a96a8 100644 --- a/tests/test_spicemanager.inl +++ b/tests/test_spicemanager.inl @@ -22,10 +22,13 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include -#include "gtest/gtest.h" #include +#include + +#include "SpiceUsr.h" +#include "SpiceZpr.h" + class SpiceManagerTest : public testing::Test { protected: void SetUp() override {