diff --git a/.gitignore b/.gitignore index de6e60dba5..b3071d6cbe 100644 --- a/.gitignore +++ b/.gitignore @@ -132,3 +132,21 @@ data/scene/milkyway-eso/textures/eso0932a_blend.png data/scene/stars-denver/denver_colorbv.cmap data/scene/stars-denver/speck/stars.speck data/scene/stars-denver/textures/halo.png +data/scene/newhorizons/pluto/pluto/full_images/ +data/scene/rosetta/67P/rosettaimages/ +data/spice/RosettaKernels_New/ +data/scene/newhorizons/pluto/charon/utcEvents.txt +data/scene/rosetta/67P/obj/67P_HD_2015-05-09.obj +data/scene/rosetta/67P/obj/may9_map.jpg +data/scene/rosetta/67P/textures/may9_map.jpg +data/scene/newhorizons/pluto/charon/textures/cpdem-Mcolor2-MLorriCA-lr-5_ZMfs-cyl.jpg +data/scene/newhorizons/pluto/charon/textures/cpmap_cyl_HR_0e.jpg +data/scene/volumetricmilkyway/milkyway/ +ScriptLog.txt +data/scene/atmosphereearth/textures/ToastMapOfEarth.jpg +data/scene/atmosphereearth/textures/earth_bluemarble.jpg +data/scene/atmosphereearth/textures/earth_bluemarble_height.jpg +data/scene/atmosphereearth/textures/earth_clouds.jpg +data/scene/atmosphereearth/textures/earth_night.jpg +data/scene/atmosphereearth/textures/earth_reflectance.png +data/scene/atmosphereearth/textures/marker.png diff --git a/apps/Launcher/mainwindow.cpp b/apps/Launcher/mainwindow.cpp index 77d61a51d2..d0c8a5fab0 100644 --- a/apps/Launcher/mainwindow.cpp +++ b/apps/Launcher/mainwindow.cpp @@ -191,6 +191,7 @@ void MainWindow::initialize() { ghoul::logging::LogManager::initialize(ghoul::logging::LogManager::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) ); LogMgr.addLog( std::make_unique< QLog >() ); diff --git a/config/sgct/single.xml b/config/sgct/single.xml index b8fa4666b8..62aea727b1 100644 --- a/config/sgct/single.xml +++ b/config/sgct/single.xml @@ -6,14 +6,7 @@ - - - - - - - diff --git a/config/sgct/single_fisheye.xml b/config/sgct/single_fisheye.xml index 893a18a853..b72758eb6c 100644 --- a/config/sgct/single_fisheye.xml +++ b/config/sgct/single_fisheye.xml @@ -1,5 +1,10 @@ + @@ -20,7 +25,7 @@ - + diff --git a/config/sgct/single_gui.xml b/config/sgct/single_gui.xml new file mode 100644 index 0000000000..e0d1b6bfa8 --- /dev/null +++ b/config/sgct/single_gui.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/data/scene/atmosphereearth.scene b/data/scene/atmosphereearth.scene new file mode 100644 index 0000000000..0b501b21f2 --- /dev/null +++ b/data/scene/atmosphereearth.scene @@ -0,0 +1,51 @@ +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()) + 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", true) + openspace.setPropertyValue("EarthMarker.renderable.enabled", true) + openspace.setPropertyValue("Constellation Bounds.renderable.enabled", false) + + openspace.setPropertyValue("MilkyWay.renderable.transparency", 0.55) + openspace.setPropertyValue("MilkyWay.renderable.segments", 50) + + openspace.printInfo("Done setting default values") + + if openspace.modules.isLoaded("ISWA") then + openspace.iswa.addCdfFiles("${OPENSPACE_DATA}/cdflist.json"); + end +end + + +return { + ScenePath = ".", + CommonFolder = "common", + Camera = { + Focus = "Earth", + Position = {1, 0, 0, 2}, + }, + Modules = { + "sun", + "earth", + "stars", + --"stars-denver", + "milkyway", + -- "milkyway-eso", + } +} diff --git a/data/scene/atmosphereearth/atmosphereearth.data b/data/scene/atmosphereearth/atmosphereearth.data new file mode 100644 index 0000000000..e168d4c8be --- /dev/null +++ b/data/scene/atmosphereearth/atmosphereearth.data @@ -0,0 +1,5 @@ +return { + FileRequest = { + { Identifier = "earth_textures", Destination = "textures", Version = 2 } + }, +} diff --git a/data/scene/atmosphereearth/atmosphereearth.mod b/data/scene/atmosphereearth/atmosphereearth.mod new file mode 100644 index 0000000000..7ab2b2121e --- /dev/null +++ b/data/scene/atmosphereearth/atmosphereearth.mod @@ -0,0 +1,159 @@ +return { + -- Earth barycenter module + { + Name = "EarthBarycenter", + Parent = "SolarSystemBarycenter", + Static = true, + Ephemeris = { + Type = "Spice", + Body = "EARTH BARYCENTER", + Reference = "ECLIPJ2000", + Observer = "SUN", + Kernels = { + "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" + } + }, + }, + -- Earth module + { + Name = "Earth", + Parent = "EarthBarycenter", + Renderable = { + Type = "RenderablePlanet", + Frame = "IAU_EARTH", + Body = "EARTH", + Geometry = { + Type = "SimpleSphere", + Radius = { 6.371, 6 }, + Segments = 100 + }, + Shadow_Group = { + Source1 = { + Name = "Sun", + -- All radius in meters + Radius = {696.3, 6} + }, + --Source2 = { Name = "Monolith", Radius = {0.01, 6} }, + Caster1 = { + Name = "Moon", + -- All radius in meters + Radius = {1.737, 6} + }, + --Caster2 = { Name = "Independency Day Ship", Radius = {0.0, 0.0} } + }, + Textures = { + Type = "simple", + Color = "textures/earth_bluemarble.jpg", + Night = "textures/earth_night.jpg", + --Height = "textures/earth_bluemarble_height.jpg", + -- Depth = "textures/earth_depth.png", + Reflectance = "textures/earth_reflectance.png", + Clouds = "textures/earth_clouds.jpg" + }, + Atmosphere = { + -- Atmosphere radius in Km + AtmoshereRadius = 6420, + --AtmoshereRadius = 6390, + --PlanetRadius = 6371, + PlanetRadius = 6360, + PlanetAverageGroundReflectance = 0.1, + Rayleigh = { + Coefficients = { + -- Wavelengths are given in 10^-9m + Wavelengths = {680, 550, 440}, + -- Reflection coefficients are given in km^-1 + Scattering = {5.8e-3, 1.35e-2, 3.31e-2}, + -- In Rayleigh scattering, the coefficients of absorption and scattering are the same. + }, + -- Thichkness of atmosphere if its density were uniform, in Km + H_R = 8.0, + }, + -- Default + Mie = { + Coefficients = { + -- Reflection coefficients are given in km^-1 + Scattering = {4e-3, 4e-3, 4e-3}, + --Scattering = {2e-5, 2e-5, 2e-5}, + -- Extinction coefficients are a fraction of the Scattering coefficients + Extinction = {4e-3/0.9, 4e-3/0.9, 4e-3/0.9} + -- Height scale (atmosphere thickness for constant density) in Km + }, + H_M = 1.2, + -- Mie Phase Function Value (G e [-1.0, 1.0]. If G = 1.0, Mie phase function = Rayleigh Phase Function) + G = 1.0, + }, + -- Clear Sky + -- Mie = { + -- Coefficients = { + -- Scattering = {20e-3, 20e-3, 20e-3}, + -- Extinction = 1.0/0.9, + -- } + -- H_M = 1.2, + -- G = 0.76, + -- }, + -- Cloudy + -- Mie = { + -- Coefficients = { + -- Scattering = {3e-3, 3e-3, 3e-3}, + -- Extinction = 1.0/0.9, + -- } + -- H_M = 3.0, + -- G = 0.65, + -- }, + } + }, + + GuiName = "/Solar/Planets/Earth" + }, + -- 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" + }, + { + Name = "EarthMarker", + Parent = "Earth", + Renderable = { + Type = "RenderablePlane", + Size = {3.0, 11.0}, + Origin = "Center", + Billboard = true, + Texture = "textures/marker.png" + }, + Ephemeris = { + Type = "Static", + Position = {0, 0, 0, 5} + } + } + -- Plane + -- { + -- Name = "EarthPlane", + -- Parent = "Earth", + -- Renderable = { + -- Type = "RenderablePlane", + -- Billboard = true, + -- Size = { 6.371, 6 }, + -- Texture = "textures/graph.jpg", + -- Atmosphere = { + -- Type = "Nishita", -- for example, values missing etc etc + -- MieFactor = 1.0, + -- MieColor = {1.0, 1.0, 1.0} + -- } + -- }, + -- Ephemeris = { + -- Type = "Static", + -- Position = { 6.371*2, 0, 0, 6}, + -- }, + -- } +} diff --git a/data/scene/default.scene b/data/scene/default.scene index ba53abbbfa..0490fe0750 100644 --- a/data/scene/default.scene +++ b/data/scene/default.scene @@ -6,7 +6,8 @@ function preInitialization() critical objects. ]]-- - openspace.time.setTime(openspace.time.currentWallTime()) + --openspace.time.setTime(openspace.time.currentWallTime()) + openspace.time.setTime('2015-03-15T11:00:00.00') dofile(openspace.absPath('${SCRIPTS}/bind_keys.lua')) end @@ -17,18 +18,31 @@ function postInitialization() graphical settings for the renderables. ]]-- openspace.printInfo("Setting default values") - openspace.setPropertyValue("Sun.renderable.enabled", false) - openspace.setPropertyValue("SunMarker.renderable.enabled", true) - openspace.setPropertyValue("EarthMarker.renderable.enabled", true) + 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) openspace.setPropertyValue("MilkyWay.renderable.transparency", 0.55) openspace.setPropertyValue("MilkyWay.renderable.segments", 50) + 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 @@ -54,7 +68,7 @@ return { "stars", --"stars-denver", "milkyway", - -- "milkyway-eso", + --"milkyway-eso", "constellationbounds", } } diff --git a/data/scene/earth/earth.mod b/data/scene/earth/earth.mod index 7ab2b2121e..3b23d70ee5 100644 --- a/data/scene/earth/earth.mod +++ b/data/scene/earth/earth.mod @@ -27,20 +27,6 @@ return { Radius = { 6.371, 6 }, Segments = 100 }, - Shadow_Group = { - Source1 = { - Name = "Sun", - -- All radius in meters - Radius = {696.3, 6} - }, - --Source2 = { Name = "Monolith", Radius = {0.01, 6} }, - Caster1 = { - Name = "Moon", - -- All radius in meters - Radius = {1.737, 6} - }, - --Caster2 = { Name = "Independency Day Ship", Radius = {0.0, 0.0} } - }, Textures = { Type = "simple", Color = "textures/earth_bluemarble.jpg", @@ -49,57 +35,6 @@ return { -- Depth = "textures/earth_depth.png", Reflectance = "textures/earth_reflectance.png", Clouds = "textures/earth_clouds.jpg" - }, - Atmosphere = { - -- Atmosphere radius in Km - AtmoshereRadius = 6420, - --AtmoshereRadius = 6390, - --PlanetRadius = 6371, - PlanetRadius = 6360, - PlanetAverageGroundReflectance = 0.1, - Rayleigh = { - Coefficients = { - -- Wavelengths are given in 10^-9m - Wavelengths = {680, 550, 440}, - -- Reflection coefficients are given in km^-1 - Scattering = {5.8e-3, 1.35e-2, 3.31e-2}, - -- In Rayleigh scattering, the coefficients of absorption and scattering are the same. - }, - -- Thichkness of atmosphere if its density were uniform, in Km - H_R = 8.0, - }, - -- Default - Mie = { - Coefficients = { - -- Reflection coefficients are given in km^-1 - Scattering = {4e-3, 4e-3, 4e-3}, - --Scattering = {2e-5, 2e-5, 2e-5}, - -- Extinction coefficients are a fraction of the Scattering coefficients - Extinction = {4e-3/0.9, 4e-3/0.9, 4e-3/0.9} - -- Height scale (atmosphere thickness for constant density) in Km - }, - H_M = 1.2, - -- Mie Phase Function Value (G e [-1.0, 1.0]. If G = 1.0, Mie phase function = Rayleigh Phase Function) - G = 1.0, - }, - -- Clear Sky - -- Mie = { - -- Coefficients = { - -- Scattering = {20e-3, 20e-3, 20e-3}, - -- Extinction = 1.0/0.9, - -- } - -- H_M = 1.2, - -- G = 0.76, - -- }, - -- Cloudy - -- Mie = { - -- Coefficients = { - -- Scattering = {3e-3, 3e-3, 3e-3}, - -- Extinction = 1.0/0.9, - -- } - -- H_M = 3.0, - -- G = 0.65, - -- }, } }, diff --git a/data/scene/enlilnh/enlilnh.mod b/data/scene/enlilnh/enlilnh.mod index 0cfb1abbb5..78a1e2bd07 100644 --- a/data/scene/enlilnh/enlilnh.mod +++ b/data/scene/enlilnh/enlilnh.mod @@ -9,12 +9,13 @@ return { }, Renderable = { Type = "RenderableMultiresVolume", + ReferenceFrame = "HEEQ", Translation = {0, 0, 0}, Rotation = {2.1, 0, 0}, Scaling = {1.1, 1.1, 1.1}, ScalingExponent = 13, Source = "tsp/enlil_nh_128_128_16.tsp", - ErrorHistogramsSource = "tsp/enlil_nh_128_128_16.errorHistograms", + ErrorHistogramsSource = "tsp/enlil_nh_128_128_16_50.errorHistograms", TransferFunction = "transferfunctions/fire.txt", BrickSelector = "tf", }, diff --git a/data/scene/fieldlines.scene b/data/scene/fieldlines.scene new file mode 100644 index 0000000000..eb0711c7fe --- /dev/null +++ b/data/scene/fieldlines.scene @@ -0,0 +1,56 @@ +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("2015 JAN 01 12:00:00.000") + 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("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", + Position = {1, 0, 0, 5}, + }, + Modules = { + "sun", + "mercury", + "venus", + "earth", + "mars", + "jupiter", + "saturn", + "uranus", + "neptune", + "stars", + "fieldlines", + -- "stars-denver", + "milkyway", + -- "milkyway-eso", + "constellationbounds", + } +} diff --git a/data/scene/globebrowsing.scene b/data/scene/globebrowsing.scene index 7dde913e27..988b9ec2dc 100644 --- a/data/scene/globebrowsing.scene +++ b/data/scene/globebrowsing.scene @@ -19,6 +19,8 @@ function postInitialization() openspace.setPropertyValue("MilkyWay.renderable.transparency", 0.55) openspace.setPropertyValue("MilkyWay.renderable.segments", 50) + openspace.resetCameraDirection() + openspace.printInfo("Done setting default values") end diff --git a/data/scene/jupiter/callisto/callisto.mod b/data/scene/jupiter/callisto/callisto.mod index 3d95a18559..ba4bc2a0ef 100644 --- a/data/scene/jupiter/callisto/callisto.mod +++ b/data/scene/jupiter/callisto/callisto.mod @@ -16,11 +16,6 @@ return { Type = "simple", Color = "textures/callisto.jpg", }, - Atmosphere = { - Type = "Nishita", -- for example, values missing etc etc - MieFactor = 1.0, - MieColor = {1.0, 1.0, 1.0} - } }, Ephemeris = { Type = "Spice", diff --git a/data/scene/jupiter/europa/europa.mod b/data/scene/jupiter/europa/europa.mod index 4ddba87974..74e5a43093 100644 --- a/data/scene/jupiter/europa/europa.mod +++ b/data/scene/jupiter/europa/europa.mod @@ -16,11 +16,6 @@ return { Type = "simple", Color = "textures/europa.jpg", }, - Atmosphere = { - Type = "Nishita", -- for example, values missing etc etc - MieFactor = 1.0, - MieColor = {1.0, 1.0, 1.0} - } }, Ephemeris = { Type = "Spice", diff --git a/data/scene/jupiter/ganymede/ganymede.mod b/data/scene/jupiter/ganymede/ganymede.mod index 64c91a5dd6..ea92a8f750 100644 --- a/data/scene/jupiter/ganymede/ganymede.mod +++ b/data/scene/jupiter/ganymede/ganymede.mod @@ -16,11 +16,6 @@ return { Type = "simple", Color = "textures/ganymede.jpg", }, - Atmosphere = { - Type = "Nishita", -- for example, values missing etc etc - MieFactor = 1.0, - MieColor = {1.0, 1.0, 1.0} - } }, Ephemeris = { Type = "Spice", diff --git a/data/scene/jupiter/io/io.mod b/data/scene/jupiter/io/io.mod index 293e5d2ac4..f86f070a24 100644 --- a/data/scene/jupiter/io/io.mod +++ b/data/scene/jupiter/io/io.mod @@ -16,11 +16,6 @@ return { Type = "simple", Color = "textures/io.jpg", }, - Atmosphere = { - Type = "Nishita", -- for example, values missing etc etc - MieFactor = 1.0, - MieColor = {1.0, 1.0, 1.0} - } }, Ephemeris = { Type = "Spice", diff --git a/data/scene/jupiter/jupiter/jupiter.mod b/data/scene/jupiter/jupiter/jupiter.mod index 9c7ef970ac..00696e4dfe 100644 --- a/data/scene/jupiter/jupiter/jupiter.mod +++ b/data/scene/jupiter/jupiter/jupiter.mod @@ -30,11 +30,6 @@ return { Type = "simple", Color = "textures/jupiter.jpg", }, - Atmosphere = { - Type = "Nishita", -- for example, values missing etc etc - MieFactor = 1.0, - MieColor = {1.0, 1.0, 1.0} - } }, Ephemeris = { Type = "Static" -- jupiter is at its barycenter diff --git a/data/scene/newhorizons/jupiter/callisto/callisto.mod b/data/scene/newhorizons/jupiter/callisto/callisto.mod index 3f380d86fb..5bb6ed57f7 100644 --- a/data/scene/newhorizons/jupiter/callisto/callisto.mod +++ b/data/scene/newhorizons/jupiter/callisto/callisto.mod @@ -18,11 +18,6 @@ return { Project = "textures/defaultProj.png", Sequencing = "true", }, - Atmosphere = { - Type = "Nishita", -- for example, values missing etc etc - MieFactor = 1.0, - MieColor = {1.0, 1.0, 1.0} - }, Projection = { Observer = "NEW HORIZONS", Target = "CALLISTO", diff --git a/data/scene/newhorizons/jupiter/europa/europa.mod b/data/scene/newhorizons/jupiter/europa/europa.mod index 1d3715f6c7..ff14b3448c 100644 --- a/data/scene/newhorizons/jupiter/europa/europa.mod +++ b/data/scene/newhorizons/jupiter/europa/europa.mod @@ -18,11 +18,6 @@ return { Project = "textures/defaultProj.png", Sequencing = "true", }, - Atmosphere = { - Type = "Nishita", -- for example, values missing etc etc - MieFactor = 1.0, - MieColor = {1.0, 1.0, 1.0} - }, Projection = { Observer = "NEW HORIZONS", Target = "EUROPA", diff --git a/data/scene/newhorizons/jupiter/ganymede/ganymede.mod b/data/scene/newhorizons/jupiter/ganymede/ganymede.mod index abc0c2ecdc..5c92635c06 100644 --- a/data/scene/newhorizons/jupiter/ganymede/ganymede.mod +++ b/data/scene/newhorizons/jupiter/ganymede/ganymede.mod @@ -18,11 +18,6 @@ return { Project = "textures/defaultProj.png", Sequencing = "true", }, - Atmosphere = { - Type = "Nishita", -- for example, values missing etc etc - MieFactor = 1.0, - MieColor = {1.0, 1.0, 1.0} - }, Projection = { Observer = "NEW HORIZONS", Target = "GANYMEDE", diff --git a/data/scene/newhorizons/jupiter/io/io.mod b/data/scene/newhorizons/jupiter/io/io.mod index e956081077..75053e1904 100644 --- a/data/scene/newhorizons/jupiter/io/io.mod +++ b/data/scene/newhorizons/jupiter/io/io.mod @@ -18,11 +18,6 @@ return { Project = "textures/defaultProj.png", Sequencing = "true", }, - Atmosphere = { - Type = "Nishita", -- for example, values missing etc etc - MieFactor = 1.0, - MieColor = {1.0, 1.0, 1.0} - }, Projection = { Observer = "NEW HORIZONS", Target = "IO", diff --git a/data/scene/newhorizons/jupiter/jupiter/jupiter.mod b/data/scene/newhorizons/jupiter/jupiter/jupiter.mod index 03e8f46b12..542a2b1eac 100644 --- a/data/scene/newhorizons/jupiter/jupiter/jupiter.mod +++ b/data/scene/newhorizons/jupiter/jupiter/jupiter.mod @@ -32,11 +32,6 @@ return { Project = "textures/lorriTest1.jpg", Sequencing = "true", }, - Atmosphere = { - Type = "Nishita", -- for example, values missing etc etc - MieFactor = 1.0, - MieColor = {1.0, 1.0, 1.0} - }, Projection = { --Sequence = "F:/JupiterFullSequence", Sequence = "${OPENSPACE_DATA}/scene/newhorizons/jupiter/jupiter/ProjectionsOfInterest", diff --git a/data/scene/newhorizons/pluto/hydra/hydra.mod b/data/scene/newhorizons/pluto/hydra/hydra.mod index 46b4d774da..cae907eea9 100644 --- a/data/scene/newhorizons/pluto/hydra/hydra.mod +++ b/data/scene/newhorizons/pluto/hydra/hydra.mod @@ -25,11 +25,6 @@ return { Textures = { Type = "simple", Color = "textures/gray.jpg", - }, - Atmosphere = { - Type = "Nishita", -- for example, values missing etc etc - MieFactor = 1.0, - MieColor = {1.0, 1.0, 1.0} } }, Ephemeris = { diff --git a/data/scene/newhorizons/pluto/kerberos/kerberos.mod b/data/scene/newhorizons/pluto/kerberos/kerberos.mod index 382f67bcfd..fef4464573 100644 --- a/data/scene/newhorizons/pluto/kerberos/kerberos.mod +++ b/data/scene/newhorizons/pluto/kerberos/kerberos.mod @@ -25,11 +25,6 @@ return { Textures = { Type = "simple", Color = "textures/gray.jpg", - }, - Atmosphere = { - Type = "Nishita", -- for example, values missing etc etc - MieFactor = 1.0, - MieColor = {1.0, 1.0, 1.0} } }, Ephemeris = { diff --git a/data/scene/newhorizons/pluto/nix/nix.mod b/data/scene/newhorizons/pluto/nix/nix.mod index 38f3186226..3387e57867 100644 --- a/data/scene/newhorizons/pluto/nix/nix.mod +++ b/data/scene/newhorizons/pluto/nix/nix.mod @@ -25,11 +25,6 @@ return { Textures = { Type = "simple", Color = "textures/gray.jpg", - }, - Atmosphere = { - Type = "Nishita", -- for example, values missing etc etc - MieFactor = 1.0, - MieColor = {1.0, 1.0, 1.0} } }, Ephemeris = { diff --git a/data/scene/newhorizons/pluto/pluto/pluto.mod b/data/scene/newhorizons/pluto/pluto/pluto.mod index 4f71b1c04c..e5447cc48e 100644 --- a/data/scene/newhorizons/pluto/pluto/pluto.mod +++ b/data/scene/newhorizons/pluto/pluto/pluto.mod @@ -50,7 +50,7 @@ return { Sequencing = "true" }, Projection = { - Sequence = "${OPENSPACE_DATA}/scene/newhorizons/pluto/pluto/full_images", + 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", diff --git a/data/scene/newhorizons/pluto/styx/styx.mod b/data/scene/newhorizons/pluto/styx/styx.mod index 5b49230388..02d6ad7a30 100644 --- a/data/scene/newhorizons/pluto/styx/styx.mod +++ b/data/scene/newhorizons/pluto/styx/styx.mod @@ -25,11 +25,6 @@ return { Textures = { Type = "simple", Color = "textures/gray.jpg", - }, - Atmosphere = { - Type = "Nishita", -- for example, values missing etc etc - MieFactor = 1.0, - MieColor = {1.0, 1.0, 1.0} } }, Ephemeris = { diff --git a/data/scene/rosetta/rosetta/rosetta.mod b/data/scene/rosetta/rosetta/rosetta.mod index 9dd867355b..8b87f58ea7 100644 --- a/data/scene/rosetta/rosetta/rosetta.mod +++ b/data/scene/rosetta/rosetta/rosetta.mod @@ -216,24 +216,5 @@ return { Type = "Static", Position = {0, 0, 0, 1} }, - }, - -- NAVCAM FoV square - { - Name = "FovImagePlane", - Parent = "Rosetta", - Renderable = { - Type = "RenderablePlaneProjection", - Frame = "67P/C-G_CK", - DefaultTarget = "CHURYUMOV-GERASIMENKO", - Spacecraft = "ROSETTA", - Instrument = "ROS_NAVCAM-A", - Moving = true, - Texture = "textures/squarefov.png", - }, - Ephemeris = { - Type = "Static", - Position = {0, 0, 0, 1} - }, } - } diff --git a/data/scene/volumetricmilkyway.scene b/data/scene/volumetricmilkyway.scene new file mode 100644 index 0000000000..dd795dee0d --- /dev/null +++ b/data/scene/volumetricmilkyway.scene @@ -0,0 +1,42 @@ +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()) + 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", true) + -- openspace.setPropertyValue("EarthMarker.renderable.enabled", true) + -- openspace.setPropertyValue("Constellation Bounds.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 = "Volumetric Milky Way", + Position = {1, 0, 0, 5}, + }, + Modules = { + "volumetricmilkyway" + } +} diff --git a/data/scene/volumetricmilkyway/milkyway.torrent b/data/scene/volumetricmilkyway/milkyway.torrent new file mode 100644 index 0000000000..b1b4ee46ab Binary files /dev/null and b/data/scene/volumetricmilkyway/milkyway.torrent differ diff --git a/data/scene/volumetricmilkyway/volumetricmilkyway.data b/data/scene/volumetricmilkyway/volumetricmilkyway.data new file mode 100644 index 0000000000..2ce26165b2 --- /dev/null +++ b/data/scene/volumetricmilkyway/volumetricmilkyway.data @@ -0,0 +1,5 @@ +return { + TorrentFiles = { + { File = "milkyway.torrent", Destination = "." } + } +} \ No newline at end of file diff --git a/data/scene/volumetricmilkyway/volumetricmilkyway.mod b/data/scene/volumetricmilkyway/volumetricmilkyway.mod new file mode 100644 index 0000000000..44f857fa41 --- /dev/null +++ b/data/scene/volumetricmilkyway/volumetricmilkyway.mod @@ -0,0 +1,26 @@ +local kiloparsec = 3.086 * 10^19; + +return { + { + Name = "Volumetric Milky Way", + Parent = "Root", + Ephemeris = { + Type = "Static", + Position = {0, 0, 0, 0} + }, + Renderable = { + Type = "RenderableGalaxy", + Translation = {0, 0, 0}, + Volume = { + Filename = "${OPENSPACE_DATA}/scene/volumetricmilkyway/milkyway/milkyway_512_512_64_RGBA32F.volume", + Dimensions = {512, 512, 64}, + Size = {50 * kiloparsec, 50 * kiloparsec, 12.5 * kiloparsec}, + }, + Points = { + Filename = "${OPENSPACE_DATA}/scene/volumetricmilkyway/milkyway/milkyway_points.binary", + Scaling = {kiloparsec, kiloparsec, kiloparsec} + } + }, + GuiName = "/VolumetricMilkyWay" + } +} diff --git a/ext/ghoul b/ext/ghoul index 5cde645215..027ce0d585 160000 --- a/ext/ghoul +++ b/ext/ghoul @@ -1 +1 @@ -Subproject commit 5cde64521525f9094b95a73bca6ca1ccac1a5541 +Subproject commit 027ce0d585d6ff3aa2435cd962db231b3503d9bf diff --git a/include/openspace/engine/configurationmanager.h b/include/openspace/engine/configurationmanager.h index c82ecb07fa..da899ce3bb 100644 --- a/include/openspace/engine/configurationmanager.h +++ b/include/openspace/engine/configurationmanager.h @@ -53,6 +53,10 @@ public: static const std::string KeyLuaDocumentationType; /// The key that stores the save location of the Lua documentation static const std::string KeyLuaDocumentationFile; + /// The key that stores the type of scripting log that should be stored + static const std::string KeyScriptLogType; + /// The key that stores the save location of the scripting log + static const std::string KeyScriptLogFile; /// The key that stores the type of Property documentation that should be stored static const std::string KeyPropertyDocumentationType; /// The key that stores the save location of the Property documentation diff --git a/include/openspace/engine/downloadmanager.h b/include/openspace/engine/downloadmanager.h index ad9f6ec105..cabcf0a14b 100644 --- a/include/openspace/engine/downloadmanager.h +++ b/include/openspace/engine/downloadmanager.h @@ -25,8 +25,6 @@ #ifndef __DOWNLOADMANAGER_H__ #define __DOWNLOADMANAGER_H__ -#include - #include #include @@ -39,7 +37,7 @@ namespace openspace { // Multithreaded -class DownloadManager : public ghoul::Singleton { +class DownloadManager { public: struct FileFuture { // Since the FileFuture object will be used from multiple threads, we have to be @@ -119,8 +117,6 @@ private: bool _useMultithreadedDownload; }; -#define DlManager (openspace::DownloadManager::ref()) - } // namespace openspace #endif // __DOWNLOADMANAGER_H__ diff --git a/include/openspace/engine/openspaceengine.h b/include/openspace/engine/openspaceengine.h index ee36f2f0f8..2261ba879a 100644 --- a/include/openspace/engine/openspaceengine.h +++ b/include/openspace/engine/openspaceengine.h @@ -43,6 +43,7 @@ namespace fontrendering { class FontManager; } namespace openspace { class ConfigurationManager; +class DownloadManager; class LuaConsole; class NetworkEngine; class GUI; @@ -50,6 +51,7 @@ class RenderEngine; class SyncBuffer; class ModuleEngine; class WindowWrapper; +class SettingsEngine; namespace interaction { class InteractionHandler; } namespace gui { class GUI; } @@ -83,6 +85,7 @@ public: properties::PropertyOwner& globalPropertyOwner(); WindowWrapper& windowWrapper(); ghoul::fontrendering::FontManager& fontManager(); + DownloadManager& downloadManager(); #ifdef OPENSPACE_MODULE_ONSCREENGUI_ENABLED gui::GUI& gui(); @@ -130,13 +133,15 @@ private: std::unique_ptr _commandlineParser; std::unique_ptr _console; std::unique_ptr _moduleEngine; + std::unique_ptr _settingsEngine; + std::unique_ptr _downloadManager; #ifdef OPENSPACE_MODULE_ONSCREENGUI_ENABLED std::unique_ptr _gui; #endif std::unique_ptr _parallelConnection; std::unique_ptr _windowWrapper; std::unique_ptr _fontManager; - + // Others std::unique_ptr _globalPropertyNamespace; std::unique_ptr _syncBuffer; diff --git a/include/openspace/engine/settingsengine.h b/include/openspace/engine/settingsengine.h new file mode 100644 index 0000000000..583abba854 --- /dev/null +++ b/include/openspace/engine/settingsengine.h @@ -0,0 +1,44 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2016 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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 __SETTINGSENGINE_H__ +#define __SETTINGSENGINE_H__ + +#include +#include + +namespace openspace { + +class SettingsEngine : public properties::PropertyOwner { +public: + SettingsEngine(); + +private: + properties::FloatProperty _eyeSeparation; +}; + +} // namespace openspace + + +#endif //#ifndef __SETTINGSENGINE_H__ diff --git a/include/openspace/engine/wrapper/sgctwindowwrapper.h b/include/openspace/engine/wrapper/sgctwindowwrapper.h index 6a1c170dd0..62e9c728a3 100644 --- a/include/openspace/engine/wrapper/sgctwindowwrapper.h +++ b/include/openspace/engine/wrapper/sgctwindowwrapper.h @@ -49,9 +49,13 @@ public: int currentNumberOfAaSamples() const override; bool isRegularRendering() const override; + bool hasGuiWindow() const override; + bool isGuiWindow() const override; glm::mat4 viewProjectionMatrix() const override; + glm::mat4 modelMatrix() const override; void setNearFarClippingPlane(float near, float far) override; + void setEyeSeparationDistance(float distance) override; glm::ivec4 viewportPixelCoordinates() const override; diff --git a/include/openspace/engine/wrapper/windowwrapper.h b/include/openspace/engine/wrapper/windowwrapper.h index d20f5339db..f9b778e5a5 100644 --- a/include/openspace/engine/wrapper/windowwrapper.h +++ b/include/openspace/engine/wrapper/windowwrapper.h @@ -125,12 +125,35 @@ public: */ virtual bool isRegularRendering() const; + /** + * Returns true if there is a dedicated GUI window. In these cases, the + * GUI elements will not be drawn on the non-GUI windows but only on the dedicated + * windows. + * \return Whether there are dedicated GUI windows + */ + virtual bool hasGuiWindow() const; + + /** + * Returns true if the current rendering window is a GUI-only window. In + * these cases, the regular rendering is suppressed, but input is still possible in + * the window + * \return Whether the current rendering window is GUI-only + */ + virtual bool isGuiWindow() const; + /** * Returns the currently employed view-projection matrix. On default, this method will * return the identity matrix. * \return The currently employed view-projection matrix */ virtual glm::mat4 viewProjectionMatrix() const; + + /** + * Returns the currently employed model matrix. On default, this method will return + * the identity matrix. + * \return The currently employed model matrix + */ + virtual glm::mat4 modelMatrix() const; /** * Sets the near and far clipping planes of the rendering window. This method defaults @@ -140,6 +163,12 @@ public: */ virtual void setNearFarClippingPlane(float near, float far); + /** + * Sets the stereo eye separation distance for the render engine. + * \param distance The distance between eyes for stereo rendering. + */ + virtual void setEyeSeparationDistance(float distance); + /** * Returns the location and size of the current viewport (x, * width, y, and height). If there is only a diff --git a/include/openspace/interaction/interactionhandler.h b/include/openspace/interaction/interactionhandler.h index cdded0120a..ba3decca8f 100644 --- a/include/openspace/interaction/interactionhandler.h +++ b/include/openspace/interaction/interactionhandler.h @@ -36,6 +36,7 @@ #include +#include #include @@ -147,8 +148,6 @@ private: #else // USE_OLD_INTERACTIONHANDLER - - class InteractionHandler : public properties::PropertyOwner { public: @@ -158,14 +157,12 @@ public: // Mutators void setFocusNode(SceneGraphNode* node); void setCamera(Camera* camera); + void resetCameraDirection(); // Interaction mode setters void setCameraStateFromDictionary(const ghoul::Dictionary& cameraDict); void setInteractionModeToOrbital(); void setInteractionModeToGlobeBrowsing(); - void setInteractionFriction(double friction); - void setInteractionSensitivity(double sensitivity); - void setInteractionFollowScaleFactor(double scaleFactor); void resetKeyBindings(); @@ -221,6 +218,13 @@ private: // Properties properties::StringProperty _origin; properties::StringProperty _coordinateSystem; + + properties::FloatProperty _rotationalFriction; + properties::FloatProperty _horizontalFriction; + properties::FloatProperty _verticalFriction; + + properties::FloatProperty _sensitivity; + properties::FloatProperty _rapidness; }; #endif // USE_OLD_INTERACTIONHANDLER diff --git a/include/openspace/interaction/interactionmode.h b/include/openspace/interaction/interactionmode.h index 7d9ceba9bc..fb21a456d3 100644 --- a/include/openspace/interaction/interactionmode.h +++ b/include/openspace/interaction/interactionmode.h @@ -116,7 +116,7 @@ protected: } void decelerate(double dt) { _currentValue = _currentValue + (- _currentValue) * - min(_friction * dt, 1.0); // less or equal to 1.0 keeps it stable + min(_scaleFactor * _friction * dt, 1.0); // less or equal to 1.0 keeps it stable } void setHard(T value) { _targetValue = value; @@ -184,7 +184,9 @@ public: */ MouseStates(double sensitivity, double velocityScaleFactor); void updateMouseStatesFromInput(const InputState& inputState, double deltaTime); - void setFriction(double friction); + void setRotationalFriction(double friction); + void setHorizontalFriction(double friction); + void setVerticalFriction(double friction); void setSensitivity(double sensitivity); void setVelocityScaleFactor(double scaleFactor); private: diff --git a/include/openspace/network/parallelconnection.h b/include/openspace/network/parallelconnection.h index caa9b3bdfb..f377ab0457 100644 --- a/include/openspace/network/parallelconnection.h +++ b/include/openspace/network/parallelconnection.h @@ -47,8 +47,8 @@ #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif -#include #include +#include #include #endif diff --git a/include/openspace/performance/performancemanager.h b/include/openspace/performance/performancemanager.h index c99538358b..530a0c0e71 100644 --- a/include/openspace/performance/performancemanager.h +++ b/include/openspace/performance/performancemanager.h @@ -25,8 +25,10 @@ #ifndef __PERFORMANCEMANAGER_H__ #define __PERFORMANCEMANAGER_H__ -#include +#include + #include +#include #include namespace ghoul { @@ -58,7 +60,7 @@ private: std::map individualPerformanceLocations; - ghoul::SharedMemory* _performanceMemory; + std::unique_ptr _performanceMemory; }; } // namespace performance diff --git a/include/openspace/properties/numericalproperty.inl b/include/openspace/properties/numericalproperty.inl index 5366f2d6fd..964c29190d 100644 --- a/include/openspace/properties/numericalproperty.inl +++ b/include/openspace/properties/numericalproperty.inl @@ -48,9 +48,9 @@ namespace properties { template <> \ TYPE PropertyDelegate>::defaultMaximumValue(); \ \ - template <> \ - template <> \ - TYPE PropertyDelegate>::defaultSteppingValue(); \ + template <> \ + template <> \ + TYPE PropertyDelegate>::defaultSteppingValue(); \ \ template <> \ template <> \ @@ -133,12 +133,12 @@ namespace properties { return DEFAULT_MAX_VALUE; \ } \ \ - template <> \ - template <> \ + template <> \ + template <> \ TYPE PropertyDelegate>::defaultSteppingValue() \ - { \ + { \ return DEFAULT_STEPPING; \ - } \ + } \ \ template <> \ template <> \ @@ -283,16 +283,20 @@ template bool NumericalProperty::setLuaValue(lua_State* state) { bool success = false; - T value = PropertyDelegate>::template fromLuaValue(state, success); + T value = PropertyDelegate>::template fromLuaValue( + state, success + ); if (success) - TemplateProperty::setValue(value); + TemplateProperty::setValue(std::move(value)); return success; } template bool NumericalProperty::getLuaValue(lua_State* state) const { - bool success = PropertyDelegate>::template toLuaValue(state, TemplateProperty::_value); + bool success = PropertyDelegate>::template toLuaValue( + state, TemplateProperty::_value + ); return success; } @@ -303,16 +307,20 @@ int NumericalProperty::typeLua() const { template bool NumericalProperty::getStringValue(std::string& value) const { - bool success = PropertyDelegate>::template toString(value, TemplateProperty::_value); + bool success = PropertyDelegate>::template toString( + value, TemplateProperty::_value + ); return success; } template bool NumericalProperty::setStringValue(std::string value) { bool success = false; - T thisValue = PropertyDelegate>::template fromString(value, success); + T thisValue = PropertyDelegate>::template fromString( + value, success + ); if (success) - TemplateProperty::set(ghoul::any(thisValue)); + TemplateProperty::set(ghoul::any(std::move(thisValue))); return success; } diff --git a/include/openspace/properties/property.h b/include/openspace/properties/property.h index 900eb81dac..3ec235e341 100644 --- a/include/openspace/properties/property.h +++ b/include/openspace/properties/property.h @@ -262,6 +262,12 @@ public: */ void setVisible(bool state); + /** + * Returns whether this Property is visible or not. + * \return Whether this Property is visible or hidden + */ + bool isVisible() const; + /** * This method determines if this Property should be read-only in external * applications. This setting is only a hint and does not need to be followed by GUI diff --git a/include/openspace/properties/propertyowner.h b/include/openspace/properties/propertyowner.h index 55cc9bcb82..1c2de04952 100644 --- a/include/openspace/properties/propertyowner.h +++ b/include/openspace/properties/propertyowner.h @@ -82,7 +82,7 @@ public: * include Propertys owned by other sub-owners. * \return A list of all Propertys directly owned by this PropertyOwner */ - const std::vector& properties() const; + std::vector properties() const; /** * Returns a list of all Propertys directly or indirectly owned by this PropertyOwner. @@ -123,7 +123,7 @@ public: * this PropertyOwner. * \return A list of all sub-owners this PropertyOwner has */ - const std::vector& propertySubOwners() const; + std::vector propertySubOwners() const; /** * This method returns the direct sub-owner of this PropertyOwner with the provided @@ -160,7 +160,7 @@ public: * \return The human readable name for the Propertys identified by * groupID */ - const std::string& propertyGroupName(const std::string& groupID) const; + std::string propertyGroupName(const std::string& groupID) const; /** * Assigns the Property prop to this PropertyOwner. This method will diff --git a/include/openspace/properties/scalarproperty.h b/include/openspace/properties/scalarproperty.h index 18984b5aec..29cdb9100c 100644 --- a/include/openspace/properties/scalarproperty.h +++ b/include/openspace/properties/scalarproperty.h @@ -32,7 +32,7 @@ namespace properties { REGISTER_TEMPLATEPROPERTY_HEADER(BoolProperty, bool); REGISTER_NUMERICALPROPERTY_HEADER(CharProperty, char); -REGISTER_NUMERICALPROPERTY_HEADER(WCharProperty, wchar_t); +//REGISTER_NUMERICALPROPERTY_HEADER(WCharProperty, wchar_t); REGISTER_NUMERICALPROPERTY_HEADER(SignedCharProperty, signed char); REGISTER_NUMERICALPROPERTY_HEADER(UCharProperty, unsigned char); REGISTER_NUMERICALPROPERTY_HEADER(ShortProperty, short); diff --git a/include/openspace/rendering/renderable.h b/include/openspace/rendering/renderable.h index eda7d60812..7d618b1f3a 100644 --- a/include/openspace/rendering/renderable.h +++ b/include/openspace/rendering/renderable.h @@ -54,7 +54,7 @@ public: static Renderable* createFromDictionary(const ghoul::Dictionary& dictionary); // constructors & destructor - Renderable(); + Renderable(); Renderable(const ghoul::Dictionary& dictionary); virtual ~Renderable(); diff --git a/include/openspace/rendering/renderengine.h b/include/openspace/rendering/renderengine.h index 65e1359b9b..e94f7a320b 100644 --- a/include/openspace/rendering/renderengine.h +++ b/include/openspace/rendering/renderengine.h @@ -89,7 +89,7 @@ public: bool initializeGL(); void postSynchronizationPreDraw(); void preSynchronization(); - void render(const glm::mat4 &projectionMatrix, const glm::mat4 &viewMatrix); + void render(const glm::mat4& projectionMatrix, const glm::mat4& viewMatrix, bool showGui); void postDraw(); void takeScreenshot(); @@ -114,6 +114,7 @@ public: void unregisterScreenSpaceRenderable(std::shared_ptr s); void unregisterScreenSpaceRenderable(std::string name); std::shared_ptr screenSpaceRenderable(std::string name); + std::vector screenSpaceRenderables() const; std::unique_ptr buildRenderProgram( std::string name, diff --git a/include/openspace/rendering/screenspacerenderable.h b/include/openspace/rendering/screenspacerenderable.h index d435d6bf7d..9fa4c175c8 100644 --- a/include/openspace/rendering/screenspacerenderable.h +++ b/include/openspace/rendering/screenspacerenderable.h @@ -24,38 +24,33 @@ #ifndef __SCREENSPACERENDERABLE_H__ #define __SCREENSPACERENDERABLE_H__ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - #include -#ifdef WIN32 -#define _USE_MATH_DEFINES -#include -#endif +#include + +#include +#include +#include + +#include +#include +#include namespace openspace { + /** - * @brief The base class for screen scape images and screen space framebuffers - * @details This base class handles general functionality specific to planes that - * are rendered infront of the camera. It implements protected methods and properties for converting - * the planes from spherical to euclidean coordinates and back. It also specifies the interface - * that it's children needs to implement. + * The base class for screen space images and screen space framebuffers. + * This base class handles general functionality specific to planes that are rendered in + * front of the camera. It implements protected methods and properties for converting + * the planes from Spherical to Euclidean coordinates and back. It also specifies the + * interface that its children need to implement. */ class ScreenSpaceRenderable : public properties::PropertyOwner { public: - static ScreenSpaceRenderable* createFromDictionary(const ghoul::Dictionary& dictionary); + static ScreenSpaceRenderable* createFromDictionary( + const ghoul::Dictionary& dictionary); + ScreenSpaceRenderable(const ghoul::Dictionary& dictionary); - ~ScreenSpaceRenderable(); + virtual ~ScreenSpaceRenderable(); virtual void render() = 0; virtual bool initialize() = 0; @@ -64,33 +59,29 @@ public: virtual bool isReady() const = 0; bool isEnabled() const; - glm::vec2 euclideanPosition() const {return _euclideanPosition.value();}; - glm::vec2 sphericalPosition() const {return _sphericalPosition.value();}; - float depth() const {return _depth.value();}; + glm::vec3 euclideanPosition() const; + glm::vec3 sphericalPosition() const; + float depth() const; protected: void createPlane(); void useEuclideanCoordinates(bool b); /** - * @brief Converts vec2 polar coordinates to euclidean - * - * @param polar the coordinates theta and phi - * @param radius the radius position value of the plane - * - * @return glm::vec2 with the x and y position value of the plane + * Converts Spherical coordinates to Euclidean. + * \param spherical The coordinates theta and phi + * \param radius The radius position value of the plane + * \return The x and y position value of the plane */ - glm::vec2 toEuclidean(glm::vec2 polar, float radius); + glm::vec2 toEuclidean(const glm::vec2& spherical, float radius); /** - * @brief Converts vec2 euclidean coordinates to sperical - * - * @param euclidean the coordinates x and y - * @return glm::vec2 with the spherical coordinates theta and phi. + * Converts Euclidean coordinates to Spherical. + * \param euclidean The coordinates x and y + * \return The spherical coordinates theta and phi. */ - glm::vec2 toSpherical(glm::vec2 euclidean); - void registerProperties(); - void unregisterProperties(); + glm::vec2 toSpherical(const glm::vec2& euclidean); + void createShaders(); glm::mat4 scaleMatrix(); @@ -109,18 +100,15 @@ protected: GLuint _quad; GLuint _vertexPositionBuffer; - const std::string _rendererPath; - ghoul::Dictionary _rendererData; - const std::string _vertexPath; - const std::string _fragmentPath; std::unique_ptr _texture; std::unique_ptr _shader; bool _useEuclideanCoordinates; - const float _planeDepth = -2.0; glm::vec2 _originalViewportSize; float _radius; }; + } // namespace openspace -#endif // __SCREENSPACERENDERABLE_H__ \ No newline at end of file + +#endif // __SCREENSPACERENDERABLE_H__ diff --git a/include/openspace/scripting/scriptengine.h b/include/openspace/scripting/scriptengine.h index feab50c7e7..54242e7081 100644 --- a/include/openspace/scripting/scriptengine.h +++ b/include/openspace/scripting/scriptengine.h @@ -102,6 +102,8 @@ public: bool writeDocumentation(const std::string& filename, const std::string& type) const; + bool writeLog(const std::string& script); + void serialize(SyncBuffer* syncBuffer); void deserialize(SyncBuffer* syncBuffer); @@ -111,7 +113,9 @@ public: void preSynchronization(); void queueScript(const std::string &script); - + + void setLogFile(const std::string& filename, const std::string& type); + std::vector cachedScripts(); std::vector allLuaFunctions() const; @@ -122,6 +126,7 @@ public: void cacheScript(const std::string &library, const std::string &function, const std::string &script); private: + bool registerLuaLibrary(lua_State* state, const LuaLibrary& library); void addLibraryFunctions(lua_State* state, const LuaLibrary& library, bool replace); @@ -142,6 +147,14 @@ private: //parallel variables std::map> _cachedScripts; std::mutex _cachedScriptsMutex; + + //logging variables + bool _logFileExists = false; + bool _logScripts = true; + std::string _logType; + std::string _logFilename; + + }; } // namespace scripting diff --git a/include/openspace/util/camera.h b/include/openspace/util/camera.h index 89d17a67f0..a9d9f0a9c5 100644 --- a/include/openspace/util/camera.h +++ b/include/openspace/util/camera.h @@ -38,9 +38,9 @@ #include #include -#include - namespace openspace { + class SyncBuffer; + /** This class still needs some more love. Suggested improvements: - Remove psc from the camera class interface. diff --git a/include/openspace/util/histogram.h b/include/openspace/util/histogram.h index ed9435f883..bc8affbaf5 100644 --- a/include/openspace/util/histogram.h +++ b/include/openspace/util/histogram.h @@ -71,7 +71,7 @@ public: float equalize (float); float entropy(); - float highestBinValue(bool equalized); + float highestBinValue(bool equalized, int overBins=0); float binWidth(); void changeRange(float minValue, float maxValue); diff --git a/include/openspace/util/keys.h b/include/openspace/util/keys.h index 9490b37732..10317f4180 100644 --- a/include/openspace/util/keys.h +++ b/include/openspace/util/keys.h @@ -68,6 +68,8 @@ enum class KeyAction : int { Repeat = 2 }; +bool hasKeyAction(KeyAction lhs, KeyAction rhs); + KeyAction operator|(KeyAction lhs, KeyAction rhs); KeyAction operator|=(KeyAction& lhs, KeyAction rhs); @@ -79,6 +81,8 @@ enum class KeyModifier : int { Super = 0x0008 }; +bool hasKeyModifier(KeyModifier lhs, KeyModifier rhs); + KeyModifier operator|(KeyModifier lhs, KeyModifier rhs); KeyModifier operator|=(KeyModifier& lhs, KeyModifier rhs); diff --git a/include/openspace/util/powerscaledscalar.h b/include/openspace/util/powerscaledscalar.h index 531819b88c..106070a8a1 100644 --- a/include/openspace/util/powerscaledscalar.h +++ b/include/openspace/util/powerscaledscalar.h @@ -42,9 +42,9 @@ public: PowerScaledScalar(float f1, float f2); static PowerScaledScalar CreatePSS(double d1); - const glm::vec2& vec2() const; - float lengthf() const; - double lengthd() const; + const glm::vec2& vec2() const; + float lengthf() const; + double lengthd() const; // operator overloading diff --git a/include/openspace/util/syncbuffer.h b/include/openspace/util/syncbuffer.h index 6e9b0e6701..dcff2e7435 100644 --- a/include/openspace/util/syncbuffer.h +++ b/include/openspace/util/syncbuffer.h @@ -27,6 +27,7 @@ #include #include + #include #include diff --git a/include/openspace/util/transformationmanager.h b/include/openspace/util/transformationmanager.h index 0bbe37c459..61378c816a 100644 --- a/include/openspace/util/transformationmanager.h +++ b/include/openspace/util/transformationmanager.h @@ -50,6 +50,8 @@ public: glm::dmat3 frameTransformationMatrix(std::string from, std::string to, double ephemerisTime) const; private: + glm::dmat3 kameleonTransformationMatrix(std::string from, std::string to, double ephemerisTime) const; + #ifdef OPENSPACE_MODULE_KAMELEON_ENABLED std::shared_ptr _kameleon; #endif diff --git a/modules/base/CMakeLists.txt b/modules/base/CMakeLists.txt index 66a9bea9cc..42bc24c2a2 100644 --- a/modules/base/CMakeLists.txt +++ b/modules/base/CMakeLists.txt @@ -89,8 +89,8 @@ set(SHADER_FILES ${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/screnspace_fs.glsl - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/screnspace_vs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/screenspace_fs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/screenspace_vs.glsl ) source_group("Shader Files" FILES ${SHADER_FILES}) diff --git a/modules/base/rendering/renderableplane.cpp b/modules/base/rendering/renderableplane.cpp index 55017bafff..b16652745d 100644 --- a/modules/base/rendering/renderableplane.cpp +++ b/modules/base/rendering/renderableplane.cpp @@ -196,7 +196,7 @@ void RenderablePlane::render(const RenderData& data) { SceneGraphNode* textureNode = OsEng.renderEngine().scene()->sceneGraphNode(_nodeName)->parent(); if (textureNode != nullptr){ RenderablePlanetProjection* t = static_cast(textureNode->renderable()); - _texture = std::unique_ptr(t->baseTexture()); + _texture = std::unique_ptr(&(t->baseTexture())); float h = _texture->height(); float w = _texture->width(); float scale = h / w; diff --git a/modules/base/rendering/screenspaceframebuffer.cpp b/modules/base/rendering/screenspaceframebuffer.cpp index 5ceb89176b..e2a8fa1a9d 100644 --- a/modules/base/rendering/screenspaceframebuffer.cpp +++ b/modules/base/rendering/screenspaceframebuffer.cpp @@ -21,15 +21,16 @@ * 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 openspace { ScreenSpaceFramebuffer::ScreenSpaceFramebuffer(const ghoul::Dictionary& dictionary) @@ -39,11 +40,9 @@ ScreenSpaceFramebuffer::ScreenSpaceFramebuffer(const ghoul::Dictionary& dictiona { _id = id(); setName("ScreenSpaceFramebuffer" + std::to_string(_id)); - registerProperties(); glm::vec2 resolution = OsEng.windowWrapper().currentWindowResolution(); addProperty(_size); - OsEng.gui()._screenSpaceProperty.registerProperty(&_size); _size.set(glm::vec4(0, 0, resolution.x,resolution.y)); _scale.setValue(1.0f); @@ -62,8 +61,6 @@ bool ScreenSpaceFramebuffer::initialize(){ } bool ScreenSpaceFramebuffer::deinitialize(){ - unregisterProperties(); - glDeleteVertexArrays(1, &_quad); _quad = 0; diff --git a/modules/base/rendering/screenspaceimage.cpp b/modules/base/rendering/screenspaceimage.cpp index 001b579563..bf2dc21cbe 100644 --- a/modules/base/rendering/screenspaceimage.cpp +++ b/modules/base/rendering/screenspaceimage.cpp @@ -1,74 +1,76 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2016 * -* * -* Permission is hereby granted, free of charge, to any person obtaining a copy of this * -* software and associated documentation files (the "Software"), to deal in the Software * -* without restriction, including without limitation the rights to use, copy, modify, * -* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * -* permit persons to whom the Software is furnished to do so, subject to the following * -* conditions: * -* * -* The above copyright notice and this permission notice shall be included in all copies * -* or substantial portions of the Software. * -* * -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * -* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * -* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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 namespace { const std::string _loggerCat = "ScreenSpaceImage"; + + const std::string KeyName = "Name"; + const std::string KeyTexturePath = "TexturePath"; + const std::string KeyUrl = "URL"; } namespace openspace { + ScreenSpaceImage::ScreenSpaceImage(const ghoul::Dictionary& dictionary) - :ScreenSpaceRenderable(dictionary) - ,_texturePath("texturePath", "Texture path", "") - ,_downloadImage(false) + : ScreenSpaceRenderable(dictionary) + , _texturePath("texturePath", "Texture path", "") + , _downloadImage(false) { std::string name; - if(dictionary.getValue("Name", name)){ + if (dictionary.getValue(KeyName, name)) { setName(name); - }else{ - _id = id(); - setName("ScreenSpaceImage" + std::to_string(_id)); + } else { + static int id = 0; + setName("ScreenSpaceImage " + std::to_string(id)); + ++id; } addProperty(_texturePath); - registerProperties(); std::string texturePath; - bool texturesucces = (dictionary.getValue("TexturePath", texturePath)); - if(texturesucces){ - _texturePath.set(texturePath); - OsEng.gui()._screenSpaceProperty.registerProperty(&_texturePath); + if (dictionary.getValue(KeyTexturePath, texturePath)) { + _texturePath = texturePath; _texturePath.onChange([this](){ loadTexture(); }); } - bool urlsucces = dictionary.getValue("URL", _url); - if(urlsucces){ - _downloadImage =true; + if (dictionary.getValue(KeyUrl, _url)) { + _downloadImage = true; } - - //screenspaceCygnet does not have url or texturePath - // if(!texturesucces && !urlsucces){ - // LERROR("Must specify TexturePath or URL"); - // } - } -ScreenSpaceImage::~ScreenSpaceImage(){} +ScreenSpaceImage::~ScreenSpaceImage() {} -bool ScreenSpaceImage::initialize(){ +bool ScreenSpaceImage::initialize() { _originalViewportSize = OsEng.windowWrapper().currentWindowResolution(); createPlane(); @@ -78,8 +80,7 @@ bool ScreenSpaceImage::initialize(){ return isReady(); } -bool ScreenSpaceImage::deinitialize(){ - unregisterProperties(); +bool ScreenSpaceImage::deinitialize() { glDeleteVertexArrays(1, &_quad); _quad = 0; @@ -90,47 +91,32 @@ bool ScreenSpaceImage::deinitialize(){ _texturePath = ""; _texture = nullptr; - RenderEngine& renderEngine = OsEng.renderEngine(); if (_shader) { - renderEngine.removeRenderProgram(_shader); + OsEng.renderEngine().removeRenderProgram(_shader); _shader = nullptr; } return true; } -void ScreenSpaceImage::render(){ - if(!isReady()) return; - if(!_enabled) return; - - glm::mat4 rotation = rotationMatrix(); - glm::mat4 translation = translationMatrix(); - glm::mat4 scale = scaleMatrix(); - glm::mat4 modelTransform = rotation*translation*scale; - - draw(modelTransform); +void ScreenSpaceImage::render() { + draw(rotationMatrix() * translationMatrix() * scaleMatrix()); } - -void ScreenSpaceImage::update(){ - if(_downloadImage && _futureImage.valid() && DownloadManager::futureReady(_futureImage)){ +void ScreenSpaceImage::update() { + bool futureReady = DownloadManager::futureReady(_futureImage); + if (_downloadImage && _futureImage.valid() && futureReady) { loadTexture(); } } - -bool ScreenSpaceImage::isReady() const{ - bool ready = true; - if (!_shader) - ready &= false; - if(!_texture) - ready &= false; - return ready; +bool ScreenSpaceImage::isReady() const { + return _shader && _texture; } void ScreenSpaceImage::loadTexture() { std::unique_ptr texture = nullptr; - if(!_downloadImage) + if (!_downloadImage) texture = std::move(loadFromDisk()); else texture = std::move(loadFromMemory()); @@ -146,56 +132,54 @@ void ScreenSpaceImage::loadTexture() { } } -void ScreenSpaceImage::updateTexture(){ - if(!_downloadImage){ +void ScreenSpaceImage::updateTexture() { + if (!_downloadImage) { loadTexture(); } else { - if(_futureImage.valid()) + if (_futureImage.valid()) return; std::future future = downloadImageToMemory(_url); - if(future.valid()){ + if (future.valid()) { _futureImage = std::move(future); } } } - std::unique_ptr ScreenSpaceImage::loadFromDisk(){ + std::unique_ptr ScreenSpaceImage::loadFromDisk() { if (_texturePath.value() != "") return (ghoul::io::TextureReader::ref().loadTexture(absPath(_texturePath.value()))); return nullptr; } - std::unique_ptr ScreenSpaceImage::loadFromMemory(){ - - if(_futureImage.valid() && DownloadManager::futureReady(_futureImage) ){ + std::unique_ptr ScreenSpaceImage::loadFromMemory() { + if (_futureImage.valid() && DownloadManager::futureReady(_futureImage)) { DownloadManager::MemoryFile imageFile = _futureImage.get(); - if(imageFile.corrupted) + if (imageFile.corrupted) return nullptr; return (ghoul::io::TextureReader::ref().loadTexture( - (void*) imageFile.buffer, + reinterpret_cast(imageFile.buffer), imageFile.size, - imageFile.format)); + imageFile.format) + ); } } -std::future ScreenSpaceImage::downloadImageToMemory(std::string url){ - return std::move( DlManager.fetchFile( - url, - [url](const DownloadManager::MemoryFile& file){ - LDEBUG("Download to memory finished for screen space image"); - }, - [url](const std::string& err){ - LDEBUG("Download to memory failer for screen space image: " +err); - } - ) ); +std::future ScreenSpaceImage::downloadImageToMemory( + std::string url) +{ + return std::move(OsEng.downloadManager().fetchFile( + url, + [url](const DownloadManager::MemoryFile& file) { + LDEBUG("Download to memory finished for screen space image"); + }, + [url](const std::string& err) { + LDEBUG("Download to memory failer for screen space image: " +err); + } + )); } -int ScreenSpaceImage::id(){ - static int id = 0; - return id++; -} -} \ No newline at end of file +} // namespace openspace diff --git a/modules/base/rendering/screenspaceimage.h b/modules/base/rendering/screenspaceimage.h index 167911b12e..df66d02db7 100644 --- a/modules/base/rendering/screenspaceimage.h +++ b/modules/base/rendering/screenspaceimage.h @@ -21,55 +21,46 @@ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ + #ifndef __SCREENSPACEIMAGE_H__ #define __SCREENSPACEIMAGE_H__ #include -#include -#include +#include +#include + +#include namespace openspace { -/** - * @brief Creates a textured plane rendered in screenspace - * @details The plane gets the same ratio as the texture. Implements - * the interface that ScreenSpaceImage speciefies. - * - * @param texturePath Path to the image that should be used as texture - */ -class ScreenSpaceImage : public ScreenSpaceRenderable { +class ScreenSpaceImage : public ScreenSpaceRenderable { public: - ScreenSpaceImage(std::string texturePath); ScreenSpaceImage(const ghoul::Dictionary& dictionary); ~ScreenSpaceImage(); bool initialize() override; bool deinitialize() override; void render() override; - virtual void update() override; + void update() override; bool isReady() const override; protected: + void loadTexture(); + void updateTexture(); + std::string _url; bool _downloadImage; std::future _futureImage; - void loadTexture(); - void updateTexture(); private: - - static int id(); std::future downloadImageToMemory(std::string url); std::unique_ptr loadFromDisk(); std::unique_ptr loadFromMemory(); properties::StringProperty _texturePath; - //std::string _memorybuffer; - - - int _id; }; } //namespace openspace -#endif //__SCREENSPACEIMAGE_H__ \ No newline at end of file + +#endif //__SCREENSPACEIMAGE_H__ diff --git a/modules/base/shaders/screnspace_fs.glsl b/modules/base/shaders/screenspace_fs.glsl similarity index 97% rename from modules/base/shaders/screnspace_fs.glsl rename to modules/base/shaders/screenspace_fs.glsl index 80ab155593..bd72b4a47f 100644 --- a/modules/base/shaders/screnspace_fs.glsl +++ b/modules/base/shaders/screenspace_fs.glsl @@ -39,7 +39,7 @@ Fragment getFragment(){ // power scale coordinates for depth. w value is set to 1.0. float depth = (1.0 + log(abs(OcclusionDepth) + 1/pow(k, 1.0))/log(k)) / 27.0; - frag.color = texture(texture1, vec2(vs_st.s, 1-vs_st.t)); + frag.color = texture(texture1, vec2(vs_st.s, vs_st.t)); frag.color.a = (frag.color.a != 0.0f) ? Alpha : frag.color.a; if(frag.color.a == 0.0f){ discard; diff --git a/modules/base/shaders/screnspace_vs.glsl b/modules/base/shaders/screenspace_vs.glsl similarity index 100% rename from modules/base/shaders/screnspace_vs.glsl rename to modules/base/shaders/screenspace_vs.glsl diff --git a/modules/debugging/rendering/debugrenderer.cpp b/modules/debugging/rendering/debugrenderer.cpp index 13d4c34b7e..f889d29a43 100644 --- a/modules/debugging/rendering/debugrenderer.cpp +++ b/modules/debugging/rendering/debugrenderer.cpp @@ -41,33 +41,37 @@ namespace { namespace openspace { - std::shared_ptr DebugRenderer::_reference = nullptr; - + DebugRenderer* DebugRenderer::_reference = nullptr; DebugRenderer::DebugRenderer() { - _programObject = std::shared_ptr(OsEng.renderEngine().buildRenderProgram( + _programObject = OsEng.renderEngine().buildRenderProgram( "BasicDebugShader", "${MODULE_DEBUGGING}/rendering/debugshader_vs.glsl", "${MODULE_DEBUGGING}/rendering/debugshader_fs.glsl" - )); + ); } - DebugRenderer::DebugRenderer(std::shared_ptr programObject) - : _programObject(programObject) + DebugRenderer::DebugRenderer(std::unique_ptr programObject) + : _programObject(std::move(programObject)) { // nothing to do } - std::shared_ptr DebugRenderer::ref() { + DebugRenderer::~DebugRenderer() + { + + } + + const DebugRenderer& DebugRenderer::ref() { if (_reference == nullptr) { try { - _reference = std::make_shared(); + _reference = new DebugRenderer(); } catch (const ShaderObject::ShaderCompileError& e) { LERROR(e.what()); } } - return _reference; + return *_reference; } void DebugRenderer::renderVertices(const Vertices& clippingSpacePoints, GLenum mode, RGBA rgba) const { @@ -163,17 +167,17 @@ namespace openspace { 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); + 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); + DebugRenderer::ref().renderBoxEdges(clippingSpaceBoxCorners, rgba); glPointSize(10.0f); - DebugRenderer::ref()->renderVertices(clippingSpaceBoxCorners, GL_POINTS, rgba); + DebugRenderer::ref().renderVertices(clippingSpaceBoxCorners, GL_POINTS, rgba); } void DebugRenderer::renderCameraFrustum(const RenderData& data, const Camera& otherCamera, RGBA rgba) const { diff --git a/modules/debugging/rendering/debugrenderer.h b/modules/debugging/rendering/debugrenderer.h index 8699e828fa..82889f708f 100644 --- a/modules/debugging/rendering/debugrenderer.h +++ b/modules/debugging/rendering/debugrenderer.h @@ -43,7 +43,6 @@ namespace openspace { using namespace ghoul::opengl; - /** A helper class for quick rendering of vertices IN clipping space. @@ -54,11 +53,9 @@ namespace openspace { */ class DebugRenderer { public: - typedef std::vector Vertices; typedef glm::vec4 RGBA; - /** * Consider using ref() before creating a new default instance! */ @@ -67,15 +64,13 @@ namespace openspace { /** * Instantiate a new DebugRenderer with a custom shader program */ - DebugRenderer(std::shared_ptr programObject); + DebugRenderer(std::unique_ptr programObject); + ~DebugRenderer(); /** * Access the static reference */ - static std::shared_ptr ref(); - - - + static const DebugRenderer& ref(); /** * Render the vector of clipping space points in the specified mode and color. @@ -127,8 +122,6 @@ namespace openspace { */ 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 @@ -143,7 +136,6 @@ namespace openspace { */ void renderAABB2(const AABB2& screenSpaceAABB, RGBA rgba = { 1, 1, 1, 0.3 }) const; - /** * 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 @@ -151,17 +143,13 @@ namespace openspace { */ const Vertices verticesFor(const AABB3& screenSpaceAABB) const; - protected: + std::unique_ptr _programObject; - std::shared_ptr _programObject; - static std::shared_ptr _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__ diff --git a/modules/galaxy/include.cmake b/modules/galaxy/include.cmake index 163c5a64bf..1fbd4a3ae5 100644 --- a/modules/galaxy/include.cmake +++ b/modules/galaxy/include.cmake @@ -1,4 +1,3 @@ -set (DEFAULT_MODULE ON) set (OPENSPACE_DEPENDENCIES volume ) \ No newline at end of file diff --git a/modules/galaxy/rendering/galaxyraycaster.h b/modules/galaxy/rendering/galaxyraycaster.h index 34720a0868..f3f9641160 100644 --- a/modules/galaxy/rendering/galaxyraycaster.h +++ b/modules/galaxy/rendering/galaxyraycaster.h @@ -25,6 +25,8 @@ #ifndef __GALAXYRAYCASTER_H__ #define __GALAXYRAYCASTER_H__ +#include + #include #include #include diff --git a/modules/globebrowsing/CMakeLists.txt b/modules/globebrowsing/CMakeLists.txt index fb0a3bfc57..5a0b907e5f 100644 --- a/modules/globebrowsing/CMakeLists.txt +++ b/modules/globebrowsing/CMakeLists.txt @@ -138,13 +138,28 @@ create_new_module( ${HEADER_FILES} ${SOURCE_FILES} ${SHADER_FILES} ) -target_include_directories( - openspace-module-globebrowsing - SYSTEM PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/ext/gdal/include -) +if (WIN32) + target_include_directories( + openspace-module-globebrowsing + SYSTEM PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/ext/gdal/include + ) -target_link_libraries( - openspace-module-globebrowsing - ${CMAKE_CURRENT_SOURCE_DIR}/ext/gdal/lib/gdal_i.lib -) + target_link_libraries( + openspace-module-globebrowsing + ${CMAKE_CURRENT_SOURCE_DIR}/ext/gdal/lib/gdal_i.lib + ) +else (WIN32) + find_package(GDAL REQUIRED) + + target_include_directories( + openspace-module-globebrowsing + SYSTEM PUBLIC + ${GDAL_INCLUDE} + ) + + target_link_libraries( + openspace-module-globebrowsing + ${GDAL_LIBRARY} + ) +endif () diff --git a/modules/globebrowsing/chunk/chunkedlodglobe.cpp b/modules/globebrowsing/chunk/chunkedlodglobe.cpp index f94d5507f6..b4aa5b5843 100644 --- a/modules/globebrowsing/chunk/chunkedlodglobe.cpp +++ b/modules/globebrowsing/chunk/chunkedlodglobe.cpp @@ -202,7 +202,7 @@ namespace openspace { if (_savedCamera != nullptr) { - DebugRenderer::ref()->renderCameraFrustum(data, *_savedCamera); + DebugRenderer::ref().renderCameraFrustum(data, *_savedCamera); } @@ -234,12 +234,12 @@ namespace openspace { vec4 color = vec4(colorBits & 1, colorBits & 2, colorBits & 4, 0.3); if (debugOptions.showChunkBounds) { - DebugRenderer::ref()->renderNiceBox(clippingSpaceCorners, color); + DebugRenderer::ref().renderNiceBox(clippingSpaceCorners, color); } if (debugOptions.showChunkAABB) { - auto& screenSpacePoints = DebugRenderer::ref()->verticesFor(screenSpaceBounds); - DebugRenderer::ref()->renderNiceBox(screenSpacePoints, color); + auto& screenSpacePoints = DebugRenderer::ref().verticesFor(screenSpaceBounds); + DebugRenderer::ref().renderNiceBox(screenSpacePoints, color); } } } diff --git a/modules/globebrowsing/chunk/chunkedlodglobe.h b/modules/globebrowsing/chunk/chunkedlodglobe.h index 56e8d2e39c..a5f89c9112 100644 --- a/modules/globebrowsing/chunk/chunkedlodglobe.h +++ b/modules/globebrowsing/chunk/chunkedlodglobe.h @@ -37,7 +37,6 @@ #include #include - #include #include @@ -149,7 +148,6 @@ namespace openspace { std::shared_ptr _savedCamera; std::shared_ptr _tileProviderManager; - }; } // namespace openspace diff --git a/modules/globebrowsing/ext/gdal/include/cpl_atomic_ops.h b/modules/globebrowsing/ext/gdal/include/cpl_atomic_ops.h index ed3eadaec9..6a07d2ceca 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_atomic_ops.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_atomic_ops.h @@ -1,5 +1,5 @@ /********************************************************************** - * $Id$ + * $Id: cpl_atomic_ops.h 33666 2016-03-07 05:21:07Z goatbar $ * * Name: cpl_atomic_ops.h * Project: CPL - Common Portability Library diff --git a/modules/globebrowsing/ext/gdal/include/cpl_aws.h b/modules/globebrowsing/ext/gdal/include/cpl_aws.h index 3d968ba750..854ada656a 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_aws.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_aws.h @@ -1,5 +1,5 @@ /********************************************************************** - * $Id$ + * $Id: cpl_aws.h 33758 2016-03-21 09:06:22Z rouault $ * * Name: cpl_aws.h * Project: CPL - Common Portability Library diff --git a/modules/globebrowsing/ext/gdal/include/cpl_conv.h b/modules/globebrowsing/ext/gdal/include/cpl_conv.h index ace573f8e6..2e3d883ee4 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_conv.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_conv.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: cpl_conv.h 33666 2016-03-07 05:21:07Z goatbar $ * * Project: CPL - Common Portability Library * Purpose: Convenience functions declarations. diff --git a/modules/globebrowsing/ext/gdal/include/cpl_csv.h b/modules/globebrowsing/ext/gdal/include/cpl_csv.h index b1d2ebb903..6337431077 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_csv.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_csv.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: cpl_csv.h 33844 2016-04-01 08:42:13Z rouault $ * * Project: Common Portability Library * Purpose: Functions for reading and scanning CSV (comma separated, diff --git a/modules/globebrowsing/ext/gdal/include/cpl_error.h b/modules/globebrowsing/ext/gdal/include/cpl_error.h index a43f1a32e2..3ddad1aca7 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_error.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_error.h @@ -1,5 +1,5 @@ /********************************************************************** - * $Id$ + * $Id: cpl_error.h 33842 2016-04-01 08:37:32Z rouault $ * * Name: cpl_error.h * Project: CPL - Common Portability Library diff --git a/modules/globebrowsing/ext/gdal/include/cpl_hash_set.h b/modules/globebrowsing/ext/gdal/include/cpl_hash_set.h index a0d8e296e2..37b68d8d7c 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_hash_set.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_hash_set.h @@ -1,5 +1,5 @@ /********************************************************************** - * $Id$ + * $Id: cpl_hash_set.h 33666 2016-03-07 05:21:07Z goatbar $ * * Name: cpl_hash_set.h * Project: CPL - Common Portability Library diff --git a/modules/globebrowsing/ext/gdal/include/cpl_http.h b/modules/globebrowsing/ext/gdal/include/cpl_http.h index 44500d1a55..071ed11836 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_http.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_http.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: cpl_http.h 33666 2016-03-07 05:21:07Z goatbar $ * * Project: Common Portability Library * Purpose: Function wrapper for libcurl HTTP access. diff --git a/modules/globebrowsing/ext/gdal/include/cpl_list.h b/modules/globebrowsing/ext/gdal/include/cpl_list.h index a8a433458f..a6e64d8791 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_list.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_list.h @@ -1,5 +1,5 @@ /********************************************************************** - * $Id$ + * $Id: cpl_list.h 33671 2016-03-07 18:39:06Z goatbar $ * * Name: cpl_list.h * Project: CPL - Common Portability Library diff --git a/modules/globebrowsing/ext/gdal/include/cpl_minixml.h b/modules/globebrowsing/ext/gdal/include/cpl_minixml.h index fe199034e3..3b53e130fe 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_minixml.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_minixml.h @@ -1,5 +1,5 @@ /********************************************************************** - * $Id$ + * $Id: cpl_minixml.h 33666 2016-03-07 05:21:07Z goatbar $ * * Project: CPL - Common Portability Library * Purpose: Declarations for MiniXML Handler. diff --git a/modules/globebrowsing/ext/gdal/include/cpl_minizip_zip.h b/modules/globebrowsing/ext/gdal/include/cpl_minizip_zip.h index 93a652e2cf..b086990bcb 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_minizip_zip.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_minizip_zip.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: cpl_minizip_zip.h 31826 2015-11-29 15:39:57Z goatbar $ * * Project: CPL - Common Portability Library * Author: Frank Warmerdam, warmerdam@pobox.com diff --git a/modules/globebrowsing/ext/gdal/include/cpl_multiproc.h b/modules/globebrowsing/ext/gdal/include/cpl_multiproc.h index d07841dd49..0a3cfba05d 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_multiproc.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_multiproc.h @@ -1,5 +1,5 @@ /********************************************************************** - * $Id$ + * $Id: cpl_multiproc.h 33817 2016-03-30 17:35:37Z rouault $ * * Project: CPL - Common Portability Library * Purpose: CPL Multi-Threading, and process handling portability functions. diff --git a/modules/globebrowsing/ext/gdal/include/cpl_odbc.h b/modules/globebrowsing/ext/gdal/include/cpl_odbc.h index cf47b8687c..a97f0f11df 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_odbc.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_odbc.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: cpl_odbc.h 33666 2016-03-07 05:21:07Z goatbar $ * * Project: OGR ODBC Driver * Purpose: Declarations for ODBC Access Cover API. diff --git a/modules/globebrowsing/ext/gdal/include/cpl_port.h b/modules/globebrowsing/ext/gdal/include/cpl_port.h index 221a0f6de6..74c33d62e1 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_port.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_port.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: cpl_port.h 33907 2016-04-07 00:37:06Z goatbar $ * * Project: CPL - Common Portability Library * Author: Frank Warmerdam, warmerdam@pobox.com diff --git a/modules/globebrowsing/ext/gdal/include/cpl_quad_tree.h b/modules/globebrowsing/ext/gdal/include/cpl_quad_tree.h index 3d95f4f085..c02831aaaf 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_quad_tree.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_quad_tree.h @@ -1,5 +1,5 @@ /********************************************************************** - * $Id$ + * $Id: cpl_quad_tree.h 33666 2016-03-07 05:21:07Z goatbar $ * * Project: CPL - Common Portability Library * Purpose: Implementation of quadtree building and searching functions. diff --git a/modules/globebrowsing/ext/gdal/include/cpl_sha256.h b/modules/globebrowsing/ext/gdal/include/cpl_sha256.h index a2f3989b7a..0868cf905c 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_sha256.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_sha256.h @@ -1,4 +1,4 @@ -/* $Id$ */ +/* $Id: cpl_sha256.h 31777 2015-11-26 14:14:41Z rouault $ */ /* The MIT License diff --git a/modules/globebrowsing/ext/gdal/include/cpl_spawn.h b/modules/globebrowsing/ext/gdal/include/cpl_spawn.h index 84c28112fc..5d50eaccff 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_spawn.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_spawn.h @@ -1,5 +1,5 @@ /********************************************************************** - * $Id$ + * $Id: cpl_spawn.h 31287 2015-11-01 18:29:27Z goatbar $ * * Project: CPL - Common Portability Library * Purpose: Implement CPLSystem(). diff --git a/modules/globebrowsing/ext/gdal/include/cpl_string.h b/modules/globebrowsing/ext/gdal/include/cpl_string.h index 161a6204bd..c57b4679c6 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_string.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_string.h @@ -1,5 +1,5 @@ /********************************************************************** - * $Id$ + * $Id: cpl_string.h 33788 2016-03-26 00:45:58Z goatbar $ * * Name: cpl_string.h * Project: CPL - Common Portability Library diff --git a/modules/globebrowsing/ext/gdal/include/cpl_time.h b/modules/globebrowsing/ext/gdal/include/cpl_time.h index 4a60cb3f86..7b57f4ab67 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_time.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_time.h @@ -1,5 +1,5 @@ /********************************************************************** - * $Id$ + * $Id: cpl_time.h 33783 2016-03-24 13:45:22Z goatbar $ * * Name: cpl_time.h * Project: CPL - Common Portability Library diff --git a/modules/globebrowsing/ext/gdal/include/cpl_virtualmem.h b/modules/globebrowsing/ext/gdal/include/cpl_virtualmem.h index eaf42e3129..271c5835f3 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_virtualmem.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_virtualmem.h @@ -1,5 +1,5 @@ /********************************************************************** - * $Id$ + * $Id: cpl_virtualmem.h 33666 2016-03-07 05:21:07Z goatbar $ * * Name: cpl_virtualmem.h * Project: CPL - Common Portability Library diff --git a/modules/globebrowsing/ext/gdal/include/cpl_vsi.h b/modules/globebrowsing/ext/gdal/include/cpl_vsi.h index 405a8bc4f7..16768a21f8 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_vsi.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_vsi.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: cpl_vsi.h 33758 2016-03-21 09:06:22Z rouault $ * * Project: CPL - Common Portability Library * Author: Frank Warmerdam, warmerdam@pobox.com diff --git a/modules/globebrowsing/ext/gdal/include/cpl_vsi_error.h b/modules/globebrowsing/ext/gdal/include/cpl_vsi_error.h index 3a99b01ab6..85f880f687 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_vsi_error.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_vsi_error.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: cpl_vsi_error.h 33758 2016-03-21 09:06:22Z rouault $ * * Project: VSI Virtual File System * Purpose: Implement an error system for reporting file system errors. diff --git a/modules/globebrowsing/ext/gdal/include/cpl_vsi_virtual.h b/modules/globebrowsing/ext/gdal/include/cpl_vsi_virtual.h index 7029404441..66ccc6007a 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_vsi_virtual.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_vsi_virtual.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: cpl_vsi_virtual.h 33759 2016-03-21 09:33:06Z rouault $ * * Project: VSI Virtual File System * Purpose: Declarations for classes related to the virtual filesystem. diff --git a/modules/globebrowsing/ext/gdal/include/cpl_vsil_curl_priv.h b/modules/globebrowsing/ext/gdal/include/cpl_vsil_curl_priv.h index e0bc25fcdb..259dfac6d0 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_vsil_curl_priv.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_vsil_curl_priv.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: cpl_vsil_curl_priv.h 31749 2015-11-25 02:32:55Z goatbar $ * * Project: CPL - Common Portability Library * Purpose: Private API for VSICurl diff --git a/modules/globebrowsing/ext/gdal/include/cpl_worker_thread_pool.h b/modules/globebrowsing/ext/gdal/include/cpl_worker_thread_pool.h index 7f0c23ba8e..d9a4331d13 100644 --- a/modules/globebrowsing/ext/gdal/include/cpl_worker_thread_pool.h +++ b/modules/globebrowsing/ext/gdal/include/cpl_worker_thread_pool.h @@ -1,5 +1,5 @@ /********************************************************************** - * $Id$ + * $Id: cpl_worker_thread_pool.h 33666 2016-03-07 05:21:07Z goatbar $ * * Project: CPL - Common Portability Library * Purpose: CPL worker thread pool diff --git a/modules/globebrowsing/ext/gdal/include/cplkeywordparser.h b/modules/globebrowsing/ext/gdal/include/cplkeywordparser.h index ab627aa893..70f0013d36 100644 --- a/modules/globebrowsing/ext/gdal/include/cplkeywordparser.h +++ b/modules/globebrowsing/ext/gdal/include/cplkeywordparser.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: cplkeywordparser.h 33666 2016-03-07 05:21:07Z goatbar $ * * Project: Common Portability Library * Purpose: Implementation of CPLKeywordParser - a class for parsing diff --git a/modules/globebrowsing/ext/gdal/include/gdal.h b/modules/globebrowsing/ext/gdal/include/gdal.h index 43b44d21c2..65395f6955 100644 --- a/modules/globebrowsing/ext/gdal/include/gdal.h +++ b/modules/globebrowsing/ext/gdal/include/gdal.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdal.h 33852 2016-04-01 23:27:53Z goatbar $ * * Project: GDAL Core * Purpose: GDAL Core C/Public declarations. @@ -1102,9 +1102,9 @@ CPLVirtualMem CPL_DLL* GDALGetVirtualMemAuto( GDALRasterBandH hBand, typedef enum { - /*! TileAndTransform Interleaved by Pixel: tile (0,0) with internal band interleaved by pixel organization, tile (1, 0), ... */ + /*! Tile Interleaved by Pixel: tile (0,0) with internal band interleaved by pixel organization, tile (1, 0), ... */ GTO_TIP, - /*! Band Interleaved by TileAndTransform : tile (0,0) of first band, tile (0,0) of second band, ... tile (1,0) of first band, tile (1,0) of second band, ... */ + /*! Band Interleaved by Tile : tile (0,0) of first band, tile (0,0) of second band, ... tile (1,0) of first band, tile (1,0) of second band, ... */ GTO_BIT, /*! Band SeQuential : all the tiles of first band, all the tiles of following band... */ GTO_BSQ diff --git a/modules/globebrowsing/ext/gdal/include/gdal_alg.h b/modules/globebrowsing/ext/gdal/include/gdal_alg.h index a75633fbc6..0235012bbd 100644 --- a/modules/globebrowsing/ext/gdal/include/gdal_alg.h +++ b/modules/globebrowsing/ext/gdal/include/gdal_alg.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdal_alg.h 33715 2016-03-13 08:52:06Z goatbar $ * * Project: GDAL Image Processing Algorithms * Purpose: Prototypes, and definitions for various GDAL based algorithms. diff --git a/modules/globebrowsing/ext/gdal/include/gdal_alg_priv.h b/modules/globebrowsing/ext/gdal/include/gdal_alg_priv.h index 93b5a7fbec..88b0d1179b 100644 --- a/modules/globebrowsing/ext/gdal/include/gdal_alg_priv.h +++ b/modules/globebrowsing/ext/gdal/include/gdal_alg_priv.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdal_alg_priv.h 33757 2016-03-20 20:22:33Z goatbar $ * * Project: GDAL Image Processing Algorithms * Purpose: Prototypes and definitions for various GDAL based algorithms: diff --git a/modules/globebrowsing/ext/gdal/include/gdal_csv.h b/modules/globebrowsing/ext/gdal/include/gdal_csv.h index ea48f26dcf..ff782bb980 100644 --- a/modules/globebrowsing/ext/gdal/include/gdal_csv.h +++ b/modules/globebrowsing/ext/gdal/include/gdal_csv.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdal_csv.h 33844 2016-04-01 08:42:13Z rouault $ * * Project: Common Portability Library * Purpose: Functions for reading and scanning CSV (comma separated, diff --git a/modules/globebrowsing/ext/gdal/include/gdal_frmts.h b/modules/globebrowsing/ext/gdal/include/gdal_frmts.h index 8c9bafd96f..44d06f86c5 100644 --- a/modules/globebrowsing/ext/gdal/include/gdal_frmts.h +++ b/modules/globebrowsing/ext/gdal/include/gdal_frmts.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdal_frmts.h 33351 2016-02-03 15:52:38Z goatbar $ * * Project: GDAL * Purpose: Prototypes for all format specific driver initialization. diff --git a/modules/globebrowsing/ext/gdal/include/gdal_mdreader.h b/modules/globebrowsing/ext/gdal/include/gdal_mdreader.h index 926cf1281c..2c69a56a9b 100644 --- a/modules/globebrowsing/ext/gdal/include/gdal_mdreader.h +++ b/modules/globebrowsing/ext/gdal/include/gdal_mdreader.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdal_mdreader.h 33694 2016-03-10 17:54:30Z goatbar $ * * Project: GDAL Core * Purpose: Read metadata (mainly the remote sensing imagery) from files of diff --git a/modules/globebrowsing/ext/gdal/include/gdal_pam.h b/modules/globebrowsing/ext/gdal/include/gdal_pam.h index 8c342538f7..83a14a0f60 100644 --- a/modules/globebrowsing/ext/gdal/include/gdal_pam.h +++ b/modules/globebrowsing/ext/gdal/include/gdal_pam.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdal_pam.h 33694 2016-03-10 17:54:30Z goatbar $ * * Project: GDAL Core * Purpose: Declaration for Peristable Auxiliary Metadata classes. diff --git a/modules/globebrowsing/ext/gdal/include/gdal_priv.h b/modules/globebrowsing/ext/gdal/include/gdal_priv.h index 71b9ee6ff2..76ba9a6879 100644 --- a/modules/globebrowsing/ext/gdal/include/gdal_priv.h +++ b/modules/globebrowsing/ext/gdal/include/gdal_priv.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdal_priv.h 33808 2016-03-29 21:15:28Z goatbar $ * * Name: gdal_priv.h * Project: GDAL Core diff --git a/modules/globebrowsing/ext/gdal/include/gdal_proxy.h b/modules/globebrowsing/ext/gdal/include/gdal_proxy.h index 561902fc4e..8a17c35cad 100644 --- a/modules/globebrowsing/ext/gdal/include/gdal_proxy.h +++ b/modules/globebrowsing/ext/gdal/include/gdal_proxy.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdal_proxy.h 33694 2016-03-10 17:54:30Z goatbar $ * * Project: GDAL Core * Purpose: GDAL Core C++/Private declarations diff --git a/modules/globebrowsing/ext/gdal/include/gdal_rat.h b/modules/globebrowsing/ext/gdal/include/gdal_rat.h index 5ceafb9f36..4a7a4f33f9 100644 --- a/modules/globebrowsing/ext/gdal/include/gdal_rat.h +++ b/modules/globebrowsing/ext/gdal/include/gdal_rat.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdal_rat.h 33773 2016-03-23 18:39:47Z goatbar $ * * Project: GDAL Core * Purpose: GDALRasterAttributeTable class declarations. diff --git a/modules/globebrowsing/ext/gdal/include/gdal_version.h b/modules/globebrowsing/ext/gdal/include/gdal_version.h index 2995652ca6..83a38e73fe 100644 --- a/modules/globebrowsing/ext/gdal/include/gdal_version.h +++ b/modules/globebrowsing/ext/gdal/include/gdal_version.h @@ -22,8 +22,8 @@ #endif #ifndef GDAL_RELEASE_DATE -# define GDAL_RELEASE_DATE 20160401 +# define GDAL_RELEASE_DATE 20160425 #endif #ifndef GDAL_RELEASE_NAME -# define GDAL_RELEASE_NAME "2.1.0beta1" +# define GDAL_RELEASE_NAME "2.1.0" #endif diff --git a/modules/globebrowsing/ext/gdal/include/gdal_vrt.h b/modules/globebrowsing/ext/gdal/include/gdal_vrt.h index ca89715476..63f76ffbb8 100644 --- a/modules/globebrowsing/ext/gdal/include/gdal_vrt.h +++ b/modules/globebrowsing/ext/gdal/include/gdal_vrt.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdal_vrt.h 33720 2016-03-15 00:39:53Z goatbar $ * * Project: Virtual GDAL Datasets * Purpose: C/Public declarations of virtual GDAL dataset objects. @@ -37,9 +37,9 @@ */ #include "gdal.h" +#include "cpl_port.h" #include "cpl_error.h" #include "cpl_minixml.h" -#include "cpl_port.h" #define VRT_NODATA_UNSET -1234.56 @@ -54,22 +54,22 @@ typedef CPLErr /* -------------------------------------------------------------------- */ /* Define handle types related to various VRT dataset classes. */ /* -------------------------------------------------------------------- */ -typedef void *VRTAveragedSourceH; -typedef void *VRTAverageFilteredSourceH; -typedef void *VRTComplexSourceH; -typedef void *VRTDatasetH; -typedef void *VRTDerivedRasterBandH; typedef void *VRTDriverH; -typedef void *VRTFilteredSourceH; -typedef void *VRTFuncSourceH; -typedef void *VRTKernelFilteredSourceH; -typedef void *VRTRasterBandH; -typedef void *VRTRawRasterBandH; -typedef void *VRTSimpleSourceH; typedef void *VRTSourceH; -typedef void *VRTSourcedRasterBandH; +typedef void *VRTSimpleSourceH; +typedef void *VRTAveragedSourceH; +typedef void *VRTComplexSourceH; +typedef void *VRTFilteredSourceH; +typedef void *VRTKernelFilteredSourceH; +typedef void *VRTAverageFilteredSourceH; +typedef void *VRTFuncSourceH; +typedef void *VRTDatasetH; typedef void *VRTWarpedDatasetH; +typedef void *VRTRasterBandH; +typedef void *VRTSourcedRasterBandH; typedef void *VRTWarpedRasterBandH; +typedef void *VRTDerivedRasterBandH; +typedef void *VRTRawRasterBandH; /* ==================================================================== */ /* VRTDataset class. */ diff --git a/modules/globebrowsing/ext/gdal/include/gdalexif.h b/modules/globebrowsing/ext/gdal/include/gdalexif.h index 247abf6164..6ab1560534 100644 --- a/modules/globebrowsing/ext/gdal/include/gdalexif.h +++ b/modules/globebrowsing/ext/gdal/include/gdalexif.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdalexif.h 33175 2016-01-27 00:37:49Z goatbar $ * * Project: JPEG JFIF Driver * Purpose: Implement GDAL JPEG Support based on IJG libjpeg. diff --git a/modules/globebrowsing/ext/gdal/include/gdalgeorefpamdataset.h b/modules/globebrowsing/ext/gdal/include/gdalgeorefpamdataset.h index 749cdb89a1..326b2b37a1 100644 --- a/modules/globebrowsing/ext/gdal/include/gdalgeorefpamdataset.h +++ b/modules/globebrowsing/ext/gdal/include/gdalgeorefpamdataset.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdalgeorefpamdataset.h 33794 2016-03-26 13:19:07Z goatbar $ * * Project: GDAL * Purpose: GDALPamDataset with internal storage for georeferencing, with diff --git a/modules/globebrowsing/ext/gdal/include/gdalgrid.h b/modules/globebrowsing/ext/gdal/include/gdalgrid.h index 3f3c4c77c9..f111130f3b 100644 --- a/modules/globebrowsing/ext/gdal/include/gdalgrid.h +++ b/modules/globebrowsing/ext/gdal/include/gdalgrid.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdalgrid.h 29541 2015-07-20 14:03:42Z rouault $ * * Project: GDAL Gridding API. * Purpose: Prototypes, and definitions for of GDAL scattered data gridder. diff --git a/modules/globebrowsing/ext/gdal/include/gdalgrid_priv.h b/modules/globebrowsing/ext/gdal/include/gdalgrid_priv.h index d54ea41762..9fe4e13705 100644 --- a/modules/globebrowsing/ext/gdal/include/gdalgrid_priv.h +++ b/modules/globebrowsing/ext/gdal/include/gdalgrid_priv.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdalgrid_priv.h 33715 2016-03-13 08:52:06Z goatbar $ * * Project: GDAL Gridding API. * Purpose: Prototypes, and definitions for of GDAL scattered data gridder. diff --git a/modules/globebrowsing/ext/gdal/include/gdaljp2abstractdataset.h b/modules/globebrowsing/ext/gdal/include/gdaljp2abstractdataset.h index 2bd5562121..aea9600ce2 100644 --- a/modules/globebrowsing/ext/gdal/include/gdaljp2abstractdataset.h +++ b/modules/globebrowsing/ext/gdal/include/gdaljp2abstractdataset.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdaljp2abstractdataset.h 33794 2016-03-26 13:19:07Z goatbar $ * * Project: GDAL * Purpose: GDALGeorefPamDataset with helper to read georeferencing and other diff --git a/modules/globebrowsing/ext/gdal/include/gdaljp2metadata.h b/modules/globebrowsing/ext/gdal/include/gdaljp2metadata.h index 638bff3cef..8e80d90a37 100644 --- a/modules/globebrowsing/ext/gdal/include/gdaljp2metadata.h +++ b/modules/globebrowsing/ext/gdal/include/gdaljp2metadata.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdaljp2metadata.h 33694 2016-03-10 17:54:30Z goatbar $ * * Project: GDAL * Purpose: JP2 Box Reader (and GMLJP2 Interpreter) diff --git a/modules/globebrowsing/ext/gdal/include/gdaljp2metadatagenerator.h b/modules/globebrowsing/ext/gdal/include/gdaljp2metadatagenerator.h index 88de9b4c9e..bf7faf0129 100644 --- a/modules/globebrowsing/ext/gdal/include/gdaljp2metadatagenerator.h +++ b/modules/globebrowsing/ext/gdal/include/gdaljp2metadatagenerator.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdaljp2metadatagenerator.h 33694 2016-03-10 17:54:30Z goatbar $ * * Project: GDAL * Purpose: GDALJP2Metadata: metadata generator diff --git a/modules/globebrowsing/ext/gdal/include/gdalpansharpen.h b/modules/globebrowsing/ext/gdal/include/gdalpansharpen.h index f5ae8b74b1..97f60db577 100644 --- a/modules/globebrowsing/ext/gdal/include/gdalpansharpen.h +++ b/modules/globebrowsing/ext/gdal/include/gdalpansharpen.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdalpansharpen.h 33715 2016-03-13 08:52:06Z goatbar $ * * Project: GDAL Pansharpening module * Purpose: Prototypes, and definitions for pansharpening related work. diff --git a/modules/globebrowsing/ext/gdal/include/gdalsse_priv.h b/modules/globebrowsing/ext/gdal/include/gdalsse_priv.h index fb0d1b1019..ffc10ef36d 100644 --- a/modules/globebrowsing/ext/gdal/include/gdalsse_priv.h +++ b/modules/globebrowsing/ext/gdal/include/gdalsse_priv.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdalsse_priv.h 32173 2015-12-14 00:04:53Z goatbar $ * * Project: GDAL * Purpose: SSE2 helper diff --git a/modules/globebrowsing/ext/gdal/include/gdalwarper.h b/modules/globebrowsing/ext/gdal/include/gdalwarper.h index 9d88ff8a51..9cf35ef1b2 100644 --- a/modules/globebrowsing/ext/gdal/include/gdalwarper.h +++ b/modules/globebrowsing/ext/gdal/include/gdalwarper.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdalwarper.h 33717 2016-03-14 06:29:14Z goatbar $ * * Project: GDAL High Performance Warper * Purpose: Prototypes, and definitions for warping related work. diff --git a/modules/globebrowsing/ext/gdal/include/gdalwarpkernel_opencl.h b/modules/globebrowsing/ext/gdal/include/gdalwarpkernel_opencl.h index be3a1b32d7..003b0c1acf 100644 --- a/modules/globebrowsing/ext/gdal/include/gdalwarpkernel_opencl.h +++ b/modules/globebrowsing/ext/gdal/include/gdalwarpkernel_opencl.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: gdalwarpkernel_opencl.h 33715 2016-03-13 08:52:06Z goatbar $ * * Project: OpenCL Image Reprojector * Purpose: Implementation of the GDALWarpKernel reprojector in OpenCL. diff --git a/modules/globebrowsing/ext/gdal/include/memdataset.h b/modules/globebrowsing/ext/gdal/include/memdataset.h index 6a069f01bc..d11e7a701c 100644 --- a/modules/globebrowsing/ext/gdal/include/memdataset.h +++ b/modules/globebrowsing/ext/gdal/include/memdataset.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: memdataset.h 33838 2016-03-31 20:42:32Z goatbar $ * * Project: Memory Array Translator * Purpose: Declaration of MEMDataset, and MEMRasterBand. diff --git a/modules/globebrowsing/ext/gdal/include/ogr_api.h b/modules/globebrowsing/ext/gdal/include/ogr_api.h index 29538cf067..cd3704e703 100644 --- a/modules/globebrowsing/ext/gdal/include/ogr_api.h +++ b/modules/globebrowsing/ext/gdal/include/ogr_api.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: ogr_api.h 33631 2016-03-04 06:28:09Z goatbar $ * * Project: OpenGIS Simple Features Reference Implementation * Purpose: C API for OGR Geometry, Feature, Layers, DataSource and drivers. diff --git a/modules/globebrowsing/ext/gdal/include/ogr_attrind.h b/modules/globebrowsing/ext/gdal/include/ogr_attrind.h index 29a7c7a2f1..593b3434f7 100644 --- a/modules/globebrowsing/ext/gdal/include/ogr_attrind.h +++ b/modules/globebrowsing/ext/gdal/include/ogr_attrind.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: ogr_attrind.h 32177 2015-12-14 07:25:30Z goatbar $ * * Project: OpenGIS Simple Features Reference Implementation * Purpose: Classes related to generic implementation of attribute indexing. diff --git a/modules/globebrowsing/ext/gdal/include/ogr_core.h b/modules/globebrowsing/ext/gdal/include/ogr_core.h index ba206658f8..78181374fb 100644 --- a/modules/globebrowsing/ext/gdal/include/ogr_core.h +++ b/modules/globebrowsing/ext/gdal/include/ogr_core.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: ogr_core.h 33680 2016-03-08 09:59:03Z rouault $ * * Project: OpenGIS Simple Features Reference Implementation * Purpose: Define some core portability services for cross-platform OGR code. diff --git a/modules/globebrowsing/ext/gdal/include/ogr_expat.h b/modules/globebrowsing/ext/gdal/include/ogr_expat.h index bc19366191..c08ced04e2 100644 --- a/modules/globebrowsing/ext/gdal/include/ogr_expat.h +++ b/modules/globebrowsing/ext/gdal/include/ogr_expat.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: ogr_expat.h 27044 2014-03-16 23:41:27Z rouault $ * * Project: OGR * Purpose: Convenience function for parsing with Expat library diff --git a/modules/globebrowsing/ext/gdal/include/ogr_feature.h b/modules/globebrowsing/ext/gdal/include/ogr_feature.h index cd01ffb482..454756cd8e 100644 --- a/modules/globebrowsing/ext/gdal/include/ogr_feature.h +++ b/modules/globebrowsing/ext/gdal/include/ogr_feature.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: ogr_feature.h 33631 2016-03-04 06:28:09Z goatbar $ * * Project: OpenGIS Simple Features Reference Implementation * Purpose: Class for representing a whole feature, and layer schemas. diff --git a/modules/globebrowsing/ext/gdal/include/ogr_featurestyle.h b/modules/globebrowsing/ext/gdal/include/ogr_featurestyle.h index 6230ef1cce..b3ef9114bd 100644 --- a/modules/globebrowsing/ext/gdal/include/ogr_featurestyle.h +++ b/modules/globebrowsing/ext/gdal/include/ogr_featurestyle.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: ogr_featurestyle.h 33631 2016-03-04 06:28:09Z goatbar $ * * Project: OpenGIS Simple Features Reference Implementation * Purpose: Define of Feature Representation diff --git a/modules/globebrowsing/ext/gdal/include/ogr_geocoding.h b/modules/globebrowsing/ext/gdal/include/ogr_geocoding.h index 0817776768..6ed9d50a88 100644 --- a/modules/globebrowsing/ext/gdal/include/ogr_geocoding.h +++ b/modules/globebrowsing/ext/gdal/include/ogr_geocoding.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: ogr_geocoding.h 33631 2016-03-04 06:28:09Z goatbar $ * * Project: OpenGIS Simple Features Reference Implementation * Purpose: Client of geocoding service. diff --git a/modules/globebrowsing/ext/gdal/include/ogr_geometry.h b/modules/globebrowsing/ext/gdal/include/ogr_geometry.h index 4406051e80..0024396b3c 100644 --- a/modules/globebrowsing/ext/gdal/include/ogr_geometry.h +++ b/modules/globebrowsing/ext/gdal/include/ogr_geometry.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: ogr_geometry.h 33631 2016-03-04 06:28:09Z goatbar $ * * Project: OpenGIS Simple Features Reference Implementation * Purpose: Classes for manipulating simple features that is not specific diff --git a/modules/globebrowsing/ext/gdal/include/ogr_geos.h b/modules/globebrowsing/ext/gdal/include/ogr_geos.h index 079a9355a6..19e75e48b7 100644 --- a/modules/globebrowsing/ext/gdal/include/ogr_geos.h +++ b/modules/globebrowsing/ext/gdal/include/ogr_geos.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: ogr_geos.h 33631 2016-03-04 06:28:09Z goatbar $ * * Project: OpenGIS Simple Features Reference Implementation * Purpose: Definitions related to support for use of GEOS in OGR. diff --git a/modules/globebrowsing/ext/gdal/include/ogr_p.h b/modules/globebrowsing/ext/gdal/include/ogr_p.h index 7d11d26dbe..359df8b6c3 100644 --- a/modules/globebrowsing/ext/gdal/include/ogr_p.h +++ b/modules/globebrowsing/ext/gdal/include/ogr_p.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: ogr_p.h 33631 2016-03-04 06:28:09Z goatbar $ * * Project: OpenGIS Simple Features Reference Implementation * Purpose: Some private helper functions and stuff for OGR implementation. diff --git a/modules/globebrowsing/ext/gdal/include/ogr_spatialref.h b/modules/globebrowsing/ext/gdal/include/ogr_spatialref.h index 12c1a39dfd..f12ff22f14 100644 --- a/modules/globebrowsing/ext/gdal/include/ogr_spatialref.h +++ b/modules/globebrowsing/ext/gdal/include/ogr_spatialref.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: ogr_spatialref.h 33631 2016-03-04 06:28:09Z goatbar $ * * Project: OpenGIS Simple Features Reference Implementation * Purpose: Classes for manipulating spatial reference systems in a diff --git a/modules/globebrowsing/ext/gdal/include/ogr_srs_api.h b/modules/globebrowsing/ext/gdal/include/ogr_srs_api.h index abaa72184c..ca961ecdba 100644 --- a/modules/globebrowsing/ext/gdal/include/ogr_srs_api.h +++ b/modules/globebrowsing/ext/gdal/include/ogr_srs_api.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: ogr_srs_api.h 33631 2016-03-04 06:28:09Z goatbar $ * * Project: OpenGIS Simple Features Reference Implementation * Purpose: C API and constant declarations for OGR Spatial References. diff --git a/modules/globebrowsing/ext/gdal/include/ograpispy.h b/modules/globebrowsing/ext/gdal/include/ograpispy.h index b37340da72..d2d21e7e47 100644 --- a/modules/globebrowsing/ext/gdal/include/ograpispy.h +++ b/modules/globebrowsing/ext/gdal/include/ograpispy.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: ograpispy.h 33631 2016-03-04 06:28:09Z goatbar $ * * Project: OpenGIS Simple Features Reference Implementation * Purpose: OGR C API "Spy" diff --git a/modules/globebrowsing/ext/gdal/include/ogrgeomediageometry.h b/modules/globebrowsing/ext/gdal/include/ogrgeomediageometry.h index 9cfa417497..6de124fed3 100644 --- a/modules/globebrowsing/ext/gdal/include/ogrgeomediageometry.h +++ b/modules/globebrowsing/ext/gdal/include/ogrgeomediageometry.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: ogrgeomediageometry.h 31777 2015-11-26 14:14:41Z rouault $ * * Project: OpenGIS Simple Features Reference Implementation * Purpose: Implements decoder of geomedia geometry blobs diff --git a/modules/globebrowsing/ext/gdal/include/ogrpgeogeometry.h b/modules/globebrowsing/ext/gdal/include/ogrpgeogeometry.h index 60be647cc7..c883875430 100644 --- a/modules/globebrowsing/ext/gdal/include/ogrpgeogeometry.h +++ b/modules/globebrowsing/ext/gdal/include/ogrpgeogeometry.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: ogrpgeogeometry.h 33631 2016-03-04 06:28:09Z goatbar $ * * Project: OpenGIS Simple Features Reference Implementation * Purpose: Implements decoder of shapebin geometry for PGeo diff --git a/modules/globebrowsing/ext/gdal/include/ogrsf_frmts.h b/modules/globebrowsing/ext/gdal/include/ogrsf_frmts.h index 72578701bd..cff2944520 100644 --- a/modules/globebrowsing/ext/gdal/include/ogrsf_frmts.h +++ b/modules/globebrowsing/ext/gdal/include/ogrsf_frmts.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: ogrsf_frmts.h 33631 2016-03-04 06:28:09Z goatbar $ * * Project: OpenGIS Simple Features Reference Implementation * Purpose: Classes related to format registration, and file opening. diff --git a/modules/globebrowsing/ext/gdal/include/osr_cs_wkt.h b/modules/globebrowsing/ext/gdal/include/osr_cs_wkt.h index b08df31fc9..d895c3c920 100644 --- a/modules/globebrowsing/ext/gdal/include/osr_cs_wkt.h +++ b/modules/globebrowsing/ext/gdal/include/osr_cs_wkt.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: osr_cs_wkt.h 31777 2015-11-26 14:14:41Z rouault $ * * Project: OpenGIS Simple Features Reference Implementation * Purpose: CS WKT parser diff --git a/modules/globebrowsing/ext/gdal/include/rawdataset.h b/modules/globebrowsing/ext/gdal/include/rawdataset.h index 68b923ab1a..9a52b732aa 100644 --- a/modules/globebrowsing/ext/gdal/include/rawdataset.h +++ b/modules/globebrowsing/ext/gdal/include/rawdataset.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: rawdataset.h 33673 2016-03-07 20:40:54Z goatbar $ * * Project: Raw Translator * Purpose: Implementation of RawDataset class. Intended to be subclassed diff --git a/modules/globebrowsing/ext/gdal/include/thinplatespline.h b/modules/globebrowsing/ext/gdal/include/thinplatespline.h index a597c4f9c4..91ab0521b1 100644 --- a/modules/globebrowsing/ext/gdal/include/thinplatespline.h +++ b/modules/globebrowsing/ext/gdal/include/thinplatespline.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: thinplatespline.h 33715 2016-03-13 08:52:06Z goatbar $ * * Project: GDAL Warp API * Purpose: Declarations for 2D Thin Plate Spline transformer. diff --git a/modules/globebrowsing/ext/gdal/include/vrtdataset.h b/modules/globebrowsing/ext/gdal/include/vrtdataset.h index 44417ab94b..eea6f28854 100644 --- a/modules/globebrowsing/ext/gdal/include/vrtdataset.h +++ b/modules/globebrowsing/ext/gdal/include/vrtdataset.h @@ -1,5 +1,5 @@ /****************************************************************************** - * $Id$ + * $Id: vrtdataset.h 33794 2016-03-26 13:19:07Z goatbar $ * * Project: Virtual GDAL Datasets * Purpose: Declaration of virtual gdal dataset classes. @@ -66,7 +66,7 @@ public: if( poBand == NULL ) /* do nothing */; else if( poBand->GetDataset()->GetShared() ) - GDALClose( /* (GDALDatasetH) */ poBand->GetDataset() ); + GDALClose( (GDALDatasetH) poBand->GetDataset() ); else poBand->GetDataset()->Dereference(); } @@ -90,20 +90,17 @@ public: virtual double GetMinimum( int nXSize, int nYSize, int *pbSuccess ) = 0; virtual double GetMaximum( int nXSize, int nYSize, int *pbSuccess ) = 0; - virtual CPLErr ComputeRasterMinMax( int nXSize, int nYSize, int bApproxOK, - double* adfMinMax ) = 0; + virtual CPLErr ComputeRasterMinMax( int nXSize, int nYSize, int bApproxOK, double* adfMinMax ) = 0; virtual CPLErr ComputeStatistics( int nXSize, int nYSize, int bApproxOK, double *pdfMin, double *pdfMax, double *pdfMean, double *pdfStdDev, - GDALProgressFunc pfnProgress, - void *pProgressData ) = 0; + GDALProgressFunc pfnProgress, void *pProgressData ) = 0; virtual CPLErr GetHistogram( int nXSize, int nYSize, double dfMin, double dfMax, int nBuckets, GUIntBig * panHistogram, int bIncludeOutOfRange, int bApproxOK, - GDALProgressFunc pfnProgress, - void *pProgressData ) = 0; + GDALProgressFunc pfnProgress, void *pProgressData ) = 0; virtual CPLErr XMLInit( CPLXMLNode *psTree, const char * ) = 0; virtual CPLXMLNode *SerializeToXML( const char *pszVRTPath ) = 0; @@ -134,7 +131,7 @@ class CPL_DLL VRTDataset : public GDALDataset int m_bGeoTransformSet; double m_adfGeoTransform[6]; - int m_nGCPCount; + int m_nGCPCount; GDAL_GCP *m_pasGCPList; char *m_pszGCPProjection; @@ -210,8 +207,7 @@ class CPL_DLL VRTDataset : public GDALDataset static int Identify( GDALOpenInfo * ); static GDALDataset *Open( GDALOpenInfo * ); - static GDALDataset *OpenXML( const char *, const char * = NULL, - GDALAccess eAccess = GA_ReadOnly ); + static GDALDataset *OpenXML( const char *, const char * = NULL, GDALAccess eAccess = GA_ReadOnly ); static GDALDataset *Create( const char * pszName, int nXSize, int nYSize, int nBands, GDALDataType eType, char ** papszOptions ); @@ -290,8 +286,7 @@ class VRTPansharpenedDataset : public VRTDataset GDALPansharpenOperation* m_poPansharpener; VRTPansharpenedDataset* m_poMainDataset; std::vector m_apoOverviewDatasets; - // Map from absolute to relative. - std::map m_oMapToRelativeFilenames; + std::map m_oMapToRelativeFilenames; // map from absolute to relative int m_bLoadingOtherBands; @@ -312,15 +307,15 @@ class VRTPansharpenedDataset : public VRTDataset public: VRTPansharpenedDataset( int nXSize, int nYSize ); - virtual ~VRTPansharpenedDataset(); + ~VRTPansharpenedDataset(); virtual CPLErr XMLInit( CPLXMLNode *, const char * ); virtual CPLXMLNode * SerializeToXML( const char *pszVRTPath ); CPLErr XMLInit( CPLXMLNode *psTree, const char *pszVRTPath, - GDALRasterBandH hPanchroBandIn, - int nInputSpectralBandsIn, - GDALRasterBandH* pahInputSpectralBandsIn ); + GDALRasterBandH hPanchroBandIn, + int nInputSpectralBandsIn, + GDALRasterBandH* pahInputSpectralBandsIn ); virtual CPLErr AddBand( GDALDataType eType, char **papszOptions=NULL ); @@ -354,8 +349,7 @@ class CPL_DLL VRTRasterBand : public GDALRasterBand int m_bIsMaskBand; int m_bNoDataValueSet; - // If set to true, will not report the existence of nodata. - int m_bHideNoDataValue; + int m_bHideNoDataValue; // If set to true, will not report the existence of nodata double m_dfNoDataValue; GDALColorTable *m_poColorTable; @@ -413,9 +407,9 @@ class CPL_DLL VRTRasterBand : public GDALRasterBand virtual GDALRasterBand *GetOverview(int); virtual CPLErr GetHistogram( double dfMin, double dfMax, - int nBuckets, GUIntBig * panHistogram, - int bIncludeOutOfRange, int bApproxOK, - GDALProgressFunc, void *pProgressData ); + int nBuckets, GUIntBig * panHistogram, + int bIncludeOutOfRange, int bApproxOK, + GDALProgressFunc, void *pProgressData ); virtual CPLErr GetDefaultHistogram( double *pdfMin, double *pdfMax, int *pnBuckets, GUIntBig ** ppanHistogram, @@ -462,7 +456,9 @@ class CPL_DLL VRTSourcedRasterBand : public VRTRasterBand CPLString m_osLastLocationInfo; char **m_papszSourceList; - bool CanUseSourcesMinMaxImplementations(); + void Initialize( int nXSize, int nYSize ); + + int CanUseSourcesMinMaxImplementations(); public: int nSources; @@ -501,13 +497,11 @@ class CPL_DLL VRTSourcedRasterBand : public VRTRasterBand virtual CPLErr ComputeStatistics( int bApproxOK, double *pdfMin, double *pdfMax, double *pdfMean, double *pdfStdDev, - GDALProgressFunc pfnProgress, - void *pProgressData ); + GDALProgressFunc pfnProgress, void *pProgressData ); virtual CPLErr GetHistogram( double dfMin, double dfMax, int nBuckets, GUIntBig * panHistogram, int bIncludeOutOfRange, int bApproxOK, - GDALProgressFunc pfnProgress, - void *pProgressData ); + GDALProgressFunc pfnProgress, void *pProgressData ); CPLErr AddSource( VRTSource * ); CPLErr AddSimpleSource( GDALRasterBand *poSrcBand, @@ -529,22 +523,20 @@ class CPL_DLL VRTSourcedRasterBand : public VRTRasterBand CPLErr AddMaskBandSource( GDALRasterBand *poSrcBand, double dfSrcXOff=-1, double dfSrcYOff=-1, - double dfSrcXSize=-1, - double dfSrcYSize=-1, + double dfSrcXSize=-1, double dfSrcYSize=-1, double dfDstXOff=-1, double dfDstYOff=-1, - double dfDstXSize=-1, - double dfDstYSize=-1 ); + double dfDstXSize=-1, double dfDstYSize=-1 ); CPLErr AddFuncSource( VRTImageReadFunc pfnReadFunc, void *hCBData, double dfNoDataValue = VRT_NODATA_UNSET ); void ConfigureSource(VRTSimpleSource *poSimpleSource, - GDALRasterBand *poSrcBand, - int bAddAsMaskBand, - double dfSrcXOff, double dfSrcYOff, - double dfSrcXSize, double dfSrcYSize, - double dfDstXOff, double dfDstYOff, - double dfDstXSize, double dfDstYSize ); + GDALRasterBand *poSrcBand, + int bAddAsMaskBand, + double dfSrcXOff, double dfSrcYOff, + double dfSrcXSize, double dfSrcYSize, + double dfDstXOff, double dfDstYOff, + double dfDstXSize, double dfDstYSize); virtual CPLErr IReadBlock( int, int, void * ); @@ -564,7 +556,7 @@ class CPL_DLL VRTWarpedRasterBand : public VRTRasterBand { public: VRTWarpedRasterBand( GDALDataset *poDS, int nBand, - GDALDataType eType = GDT_Unknown ); + GDALDataType eType = GDT_Unknown ); virtual ~VRTWarpedRasterBand(); virtual CPLErr XMLInit( CPLXMLNode *, const char * ); @@ -585,9 +577,8 @@ class VRTPansharpenedRasterBand : public VRTRasterBand int m_nIndexAsPansharpenedBand; public: - VRTPansharpenedRasterBand( - GDALDataset *poDS, int nBand, - GDALDataType eDataType = GDT_Unknown ); + VRTPansharpenedRasterBand( GDALDataset *poDS, int nBand, + GDALDataType eDataType = GDT_Unknown ); virtual ~VRTPansharpenedRasterBand(); virtual CPLErr XMLInit( CPLXMLNode *, const char * ); @@ -607,10 +598,8 @@ class VRTPansharpenedRasterBand : public VRTRasterBand virtual int IsPansharpenRasterBand() { return TRUE; } - void SetIndexAsPansharpenedBand( int nIdx ) - { m_nIndexAsPansharpenedBand = nIdx; } - int GetIndexAsPansharpenedBand() const - { return m_nIndexAsPansharpenedBand; } + void SetIndexAsPansharpenedBand(int nIdx) { m_nIndexAsPansharpenedBand = nIdx; } + int GetIndexAsPansharpenedBand() const { return m_nIndexAsPansharpenedBand; } }; /************************************************************************/ @@ -619,13 +608,14 @@ class VRTPansharpenedRasterBand : public VRTRasterBand class CPL_DLL VRTDerivedRasterBand : public VRTSourcedRasterBand { + public: char *pszFuncName; GDALDataType eSourceTransferType; - VRTDerivedRasterBand( GDALDataset *poDS, int nBand ); - VRTDerivedRasterBand( GDALDataset *poDS, int nBand, - GDALDataType eType, int nXSize, int nYSize ); + VRTDerivedRasterBand(GDALDataset *poDS, int nBand); + VRTDerivedRasterBand(GDALDataset *poDS, int nBand, + GDALDataType eType, int nXSize, int nYSize); virtual ~VRTDerivedRasterBand(); virtual CPLErr IRasterIO( GDALRWFlag, int, int, int, int, @@ -633,12 +623,12 @@ class CPL_DLL VRTDerivedRasterBand : public VRTSourcedRasterBand GSpacing nPixelSpace, GSpacing nLineSpace, GDALRasterIOExtraArg* psExtraArg ); - static CPLErr AddPixelFunction( const char *pszFuncName, - GDALDerivedPixelFunc pfnPixelFunc ); - static GDALDerivedPixelFunc GetPixelFunction( const char *pszFuncName ); + static CPLErr AddPixelFunction + (const char *pszFuncName, GDALDerivedPixelFunc pfnPixelFunc); + static GDALDerivedPixelFunc GetPixelFunction(const char *pszFuncName); - void SetPixelFunctionName( const char *pszFuncName ); - void SetSourceTransferType( GDALDataType eDataType ); + void SetPixelFunctionName(const char *pszFuncName); + void SetSourceTransferType(GDALDataType eDataType); virtual CPLErr XMLInit( CPLXMLNode *, const char * ); virtual CPLXMLNode * SerializeToXML( const char *pszVRTPath ); @@ -683,8 +673,8 @@ class CPL_DLL VRTRawRasterBand : public VRTRasterBand void ClearRawLink(); - virtual void GetFileList( char*** ppapszFileList, int *pnSize, - int *pnMaxSize, CPLHashSet* hSetFiles ); + virtual void GetFileList(char*** ppapszFileList, int *pnSize, + int *pnMaxSize, CPLHashSet* hSetFiles); }; /************************************************************************/ @@ -693,9 +683,11 @@ class CPL_DLL VRTRawRasterBand : public VRTRasterBand class VRTDriver : public GDALDriver { + void *m_pDeserializerData; + public: VRTDriver(); - virtual ~VRTDriver(); + ~VRTDriver(); char **papszSourceParsers; @@ -718,8 +710,8 @@ class CPL_DLL VRTSimpleSource : public VRTSource protected: GDALRasterBand *m_poRasterBand; - // When poRasterBand is a mask band, poMaskBandMainBand is the band - // from which the mask band is taken. + /* when poRasterBand is a mask band, poMaskBandMainBand is the band */ + /* from which the mask band is taken */ GDALRasterBand *m_poMaskBandMainBand; double m_dfSrcXOff; @@ -745,8 +737,8 @@ protected: public: VRTSimpleSource(); - VRTSimpleSource( const VRTSimpleSource* poSrcSource, - double dfXDstRatio, double dfYDstRatio ); + VRTSimpleSource(const VRTSimpleSource* poSrcSource, + double dfXDstRatio, double dfYDstRatio); virtual ~VRTSimpleSource(); virtual CPLErr XMLInit( CPLXMLNode *psTree, const char * ); @@ -774,34 +766,31 @@ public: virtual double GetMinimum( int nXSize, int nYSize, int *pbSuccess ); virtual double GetMaximum( int nXSize, int nYSize, int *pbSuccess ); - virtual CPLErr ComputeRasterMinMax( int nXSize, int nYSize, int bApproxOK, - double* adfMinMax ); + virtual CPLErr ComputeRasterMinMax( int nXSize, int nYSize, int bApproxOK, double* adfMinMax ); virtual CPLErr ComputeStatistics( int nXSize, int nYSize, int bApproxOK, double *pdfMin, double *pdfMax, double *pdfMean, double *pdfStdDev, - GDALProgressFunc pfnProgress, - void *pProgressData ); + GDALProgressFunc pfnProgress, void *pProgressData ); virtual CPLErr GetHistogram( int nXSize, int nYSize, double dfMin, double dfMax, int nBuckets, GUIntBig * panHistogram, int bIncludeOutOfRange, int bApproxOK, - GDALProgressFunc pfnProgress, - void *pProgressData ); + GDALProgressFunc pfnProgress, void *pProgressData ); void DstToSrc( double dfX, double dfY, double &dfXOut, double &dfYOut ); void SrcToDst( double dfX, double dfY, double &dfXOut, double &dfYOut ); - virtual void GetFileList( char*** ppapszFileList, int *pnSize, - int *pnMaxSize, CPLHashSet* hSetFiles ); + virtual void GetFileList(char*** ppapszFileList, int *pnSize, + int *pnMaxSize, CPLHashSet* hSetFiles); virtual int IsSimpleSource() { return TRUE; } virtual const char* GetType() { return "SimpleSource"; } GDALRasterBand* GetBand(); - int IsSameExceptBandNumber( VRTSimpleSource* poOtherSource ); + int IsSameExceptBandNumber(VRTSimpleSource* poOtherSource); CPLErr DatasetRasterIO( int nXOff, int nYOff, int nXSize, int nYSize, void * pData, int nBufXSize, int nBufYSize, @@ -809,11 +798,11 @@ public: int nBandCount, int *panBandMap, GSpacing nPixelSpace, GSpacing nLineSpace, GSpacing nBandSpace, - GDALRasterIOExtraArg* psExtraArg ); + GDALRasterIOExtraArg* psExtraArg); void UnsetPreservedRelativeFilenames(); - void SetMaxValue( int nVal ) { m_nMaxValue = nVal; } + void SetMaxValue(int nVal) { m_nMaxValue = nVal; } }; /************************************************************************/ @@ -832,20 +821,17 @@ public: virtual double GetMinimum( int nXSize, int nYSize, int *pbSuccess ); virtual double GetMaximum( int nXSize, int nYSize, int *pbSuccess ); - virtual CPLErr ComputeRasterMinMax( int nXSize, int nYSize, int bApproxOK, - double* adfMinMax ); + virtual CPLErr ComputeRasterMinMax( int nXSize, int nYSize, int bApproxOK, double* adfMinMax ); virtual CPLErr ComputeStatistics( int nXSize, int nYSize, int bApproxOK, double *pdfMin, double *pdfMax, double *pdfMean, double *pdfStdDev, - GDALProgressFunc pfnProgress, - void *pProgressData ); + GDALProgressFunc pfnProgress, void *pProgressData ); virtual CPLErr GetHistogram( int nXSize, int nYSize, double dfMin, double dfMax, int nBuckets, GUIntBig * panHistogram, int bIncludeOutOfRange, int bApproxOK, - GDALProgressFunc pfnProgress, - void *pProgressData ); + GDALProgressFunc pfnProgress, void *pProgressData ); virtual CPLXMLNode *SerializeToXML( const char *pszVRTPath ); virtual const char* GetType() { return "AveragedSource"; } @@ -866,10 +852,10 @@ class CPL_DLL VRTComplexSource : public VRTSimpleSource { protected: VRTComplexSourceScaling m_eScalingType; - double m_dfScaleOff; // For linear scaling. - double m_dfScaleRatio; // For linear scaling. + double m_dfScaleOff; /* for linear scaling */ + double m_dfScaleRatio; /* for linear scaling */ - // For non-linear scaling with a power function. + /* For non-linear scaling with a power function. */ int m_bSrcMinMaxDefined; double m_dfSrcMin; double m_dfSrcMax; @@ -900,20 +886,17 @@ public: virtual double GetMinimum( int nXSize, int nYSize, int *pbSuccess ); virtual double GetMaximum( int nXSize, int nYSize, int *pbSuccess ); - virtual CPLErr ComputeRasterMinMax( int nXSize, int nYSize, int bApproxOK, - double* adfMinMax ); + virtual CPLErr ComputeRasterMinMax( int nXSize, int nYSize, int bApproxOK, double* adfMinMax ); virtual CPLErr ComputeStatistics( int nXSize, int nYSize, int bApproxOK, double *pdfMin, double *pdfMax, double *pdfMean, double *pdfStdDev, - GDALProgressFunc pfnProgress, - void *pProgressData ); + GDALProgressFunc pfnProgress, void *pProgressData ); virtual CPLErr GetHistogram( int nXSize, int nYSize, double dfMin, double dfMax, int nBuckets, GUIntBig * panHistogram, int bIncludeOutOfRange, int bApproxOK, - GDALProgressFunc pfnProgress, - void *pProgressData ); + GDALProgressFunc pfnProgress, void *pProgressData ); virtual CPLXMLNode *SerializeToXML( const char *pszVRTPath ); virtual CPLErr XMLInit( CPLXMLNode *, const char * ); @@ -921,17 +904,18 @@ public: double LookupValue( double dfInput ); - void SetLinearScaling( double dfOffset, double dfScale ); - void SetPowerScaling( double dfExponent, - double dfSrcMin, - double dfSrcMax, - double dfDstMin, - double dfDstMax ); - void SetColorTableComponent( int nComponent ); + void SetLinearScaling(double dfOffset, double dfScale); + void SetPowerScaling(double dfExponent, + double dfSrcMin, + double dfSrcMax, + double dfDstMin, + double dfDstMax); + void SetColorTableComponent(int nComponent); double *m_padfLUTInputs; double *m_padfLUTOutputs; int m_nLUTItemCount; + }; /************************************************************************/ @@ -1027,20 +1011,17 @@ public: virtual double GetMinimum( int nXSize, int nYSize, int *pbSuccess ); virtual double GetMaximum( int nXSize, int nYSize, int *pbSuccess ); - virtual CPLErr ComputeRasterMinMax( int nXSize, int nYSize, int bApproxOK, - double* adfMinMax ); + virtual CPLErr ComputeRasterMinMax( int nXSize, int nYSize, int bApproxOK, double* adfMinMax ); virtual CPLErr ComputeStatistics( int nXSize, int nYSize, int bApproxOK, double *pdfMin, double *pdfMax, double *pdfMean, double *pdfStdDev, - GDALProgressFunc pfnProgress, - void *pProgressData ); + GDALProgressFunc pfnProgress, void *pProgressData ); virtual CPLErr GetHistogram( int nXSize, int nYSize, double dfMin, double dfMax, int nBuckets, GUIntBig * panHistogram, int bIncludeOutOfRange, int bApproxOK, - GDALProgressFunc pfnProgress, - void *pProgressData ); + GDALProgressFunc pfnProgress, void *pProgressData ); VRTImageReadFunc pfnReadFunc; void *pCBData; diff --git a/modules/globebrowsing/ext/gdal/lib/gdal201.dll b/modules/globebrowsing/ext/gdal/lib/gdal201.dll index bad96c9e37..a1c37a50c2 100644 Binary files a/modules/globebrowsing/ext/gdal/lib/gdal201.dll and b/modules/globebrowsing/ext/gdal/lib/gdal201.dll differ diff --git a/modules/globebrowsing/ext/gdal/lib/gdal_i.lib b/modules/globebrowsing/ext/gdal/lib/gdal_i.lib index 0f5ee06fb0..f8fd99411d 100644 Binary files a/modules/globebrowsing/ext/gdal/lib/gdal_i.lib and b/modules/globebrowsing/ext/gdal/lib/gdal_i.lib differ diff --git a/modules/globebrowsing/include.cmake b/modules/globebrowsing/include.cmake index ffea0ac430..e69de29bb2 100644 --- a/modules/globebrowsing/include.cmake +++ b/modules/globebrowsing/include.cmake @@ -1 +0,0 @@ -set(DEFAULT_MODULE ON) diff --git a/modules/globebrowsing/tile/TileProviderManager.cpp b/modules/globebrowsing/tile/TileProviderManager.cpp index c03ad467ad..2aa188f811 100644 --- a/modules/globebrowsing/tile/TileProviderManager.cpp +++ b/modules/globebrowsing/tile/TileProviderManager.cpp @@ -154,8 +154,8 @@ namespace openspace { } void TileProviderManager::update() { - for each (auto layerCategory in _layerCategories) { - for each (auto tileProviderWithName in layerCategory) { + for (auto layerCategory : _layerCategories) { + for (auto tileProviderWithName : layerCategory) { if (tileProviderWithName.isActive) { tileProviderWithName.tileProvider->update(); } @@ -168,7 +168,7 @@ namespace openspace { LayeredTextures::TextureCategory textureCategory) { std::vector > tileProviders; - for each (auto tileProviderWithName in _layerCategories[textureCategory]) { + for (auto tileProviderWithName : _layerCategories[textureCategory]) { if (tileProviderWithName.isActive) { tileProviders.push_back(tileProviderWithName.tileProvider); } diff --git a/modules/iswa/CMakeLists.txt b/modules/iswa/CMakeLists.txt index a745fdb920..c97f1dd0c3 100644 --- a/modules/iswa/CMakeLists.txt +++ b/modules/iswa/CMakeLists.txt @@ -65,10 +65,10 @@ set(SOURCE_FILES source_group("Source Files" FILES ${SOURCE_FILES}) set(SHADER_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/cygnetplane_fs.glsl - ${CMAKE_CURRENT_SOURCE_DIR}/shaders/cygnetplane_vs.glsl ${CMAKE_CURRENT_SOURCE_DIR}/shaders/dataplane_fs.glsl ${CMAKE_CURRENT_SOURCE_DIR}/shaders/dataplane_vs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/textureplane_fs.glsl + ${CMAKE_CURRENT_SOURCE_DIR}/shaders/textureplane_vs.glsl ) source_group("Shader Files" FILES ${SHADER_FILES}) diff --git a/modules/iswa/include.cmake b/modules/iswa/include.cmake index 36d16a0e90..4569df0ac7 100644 --- a/modules/iswa/include.cmake +++ b/modules/iswa/include.cmake @@ -1,3 +1,3 @@ set (OPENSPACE_DEPENDENCIES - base + base kameleon ) \ No newline at end of file diff --git a/modules/iswa/rendering/datacygnet.cpp b/modules/iswa/rendering/datacygnet.cpp index 9641cd7c2a..9c765cde09 100644 --- a/modules/iswa/rendering/datacygnet.cpp +++ b/modules/iswa/rendering/datacygnet.cpp @@ -40,15 +40,29 @@ DataCygnet::DataCygnet(const ghoul::Dictionary& dictionary) :IswaCygnet(dictionary) ,_dataProcessor(nullptr) ,_dataOptions("dataOptions", "Data Options") + ,_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") + //FOR TESTING + ,_numOfBenchmarks(0) + ,_avgBenchmarkTime(0.0f) { addProperty(_dataOptions); + addProperty(_useLog); + addProperty(_useHistogram); + addProperty(_autoFilter); + addProperty(_normValues); + addProperty(_backgroundValues); + addProperty(_transferFunctionsFile); registerProperties(); } DataCygnet::~DataCygnet(){} bool DataCygnet::updateTexture(){ - std::vector data = textureData(); if(data.empty()) @@ -86,11 +100,11 @@ bool DataCygnet::updateTexture(){ return texturesReady; } -bool DataCygnet::downloadTextureResource(){ +bool DataCygnet::downloadTextureResource(double timestamp){ if(_futureObject.valid()) return false; - std::future future = IswaManager::ref().fetchDataCygnet(_data->id); + std::future future = IswaManager::ref().fetchDataCygnet(_data->id, timestamp); if(future.valid()){ _futureObject = std::move(future); @@ -202,7 +216,7 @@ void DataCygnet::readTransferFunctions(std::string tfPath){ } void DataCygnet::fillOptions(std::string& source){ - std::vector options = _dataProcessor->readMetadata(source); + std::vector options = _dataProcessor->readMetadata(source, _textureDimensions); for(int i=0; inormValues(_normValues.value()); + updateTexture(); + }); + + _useLog.onChange([this](){ + _dataProcessor->useLog(_useLog.value()); + updateTexture(); + }); + + _useHistogram.onChange([this](){ + _dataProcessor->useHistogram(_useHistogram.value()); + updateTexture(); + if(_autoFilter.value()) + _backgroundValues.setValue(_dataProcessor->filterValues()); + }); + + _dataOptions.onChange([this](){ + if(_dataOptions.value().size() > MAX_TEXTURES) + LWARNING("Too many options chosen, max is " + std::to_string(MAX_TEXTURES)); + updateTexture(); + }); + + _transferFunctionsFile.onChange([this](){ + readTransferFunctions(_transferFunctionsFile.value()); + }); +} + +void DataCygnet::subscribeToGroup(){ + auto groupEvent = _group->groupEvent(); + + groupEvent->subscribe(name(), "dataOptionsChanged", [&](ghoul::Dictionary dict){ + LDEBUG(name() + " Event dataOptionsChanged"); + std::vector values; + bool success = dict.getValue >("dataOptions", values); + if(success){ + _dataOptions.setValue(values); + } + }); + + groupEvent->subscribe(name(), "normValuesChanged", [&](ghoul::Dictionary dict){ + LDEBUG(name() + " Event normValuesChanged"); + glm::vec2 values; + bool success = dict.getValue("normValues", values); + if(success){ + _normValues.setValue(values); + } + }); + + groupEvent->subscribe(name(), "backgroundValuesChanged", [&](ghoul::Dictionary dict){ + LDEBUG(name() + " Event backgroundValuesChanged"); + glm::vec2 values; + bool success = dict.getValue("backgroundValues", values); + if(success){ + _backgroundValues.setValue(values); + } + }); + + groupEvent->subscribe(name(), "transferFunctionsChanged", [&](ghoul::Dictionary dict){ + LDEBUG(name() + " Event transferFunctionsChanged"); + _transferFunctionsFile.setValue(dict.value("transferFunctions")); + }); + + groupEvent->subscribe(name(), "useLogChanged", [&](const ghoul::Dictionary& dict){ + LDEBUG(name() + " Event useLogChanged"); + _useLog.setValue(dict.value("useLog")); + }); + + groupEvent->subscribe(name(), "useHistogramChanged", [&](ghoul::Dictionary dict){ + LDEBUG(name() + " Event useHistogramChanged"); + _useHistogram.setValue(dict.value("useHistogram")); + }); + + groupEvent->subscribe(name(), "autoFilterChanged", [&](ghoul::Dictionary dict){ + LDEBUG(name() + " Event autoFilterChanged"); + _autoFilter.setValue(dict.value("autoFilter")); + }); + + groupEvent->subscribe(name(), "updateGroup", [&](ghoul::Dictionary dict){ + LDEBUG(name() + " Event updateGroup"); + if(_autoFilter.value()) + _backgroundValues.setValue(_dataProcessor->filterValues()); + updateTexture(); + }); + +} } //namespace openspace \ No newline at end of file diff --git a/modules/iswa/rendering/datacygnet.h b/modules/iswa/rendering/datacygnet.h index 4926948a1f..48265635dc 100644 --- a/modules/iswa/rendering/datacygnet.h +++ b/modules/iswa/rendering/datacygnet.h @@ -60,6 +60,17 @@ protected: * shader program, this includes both the data and transferfunctions. */ void setTextureUniforms(); + + /** + * Sets and defines the on-change handlers for the gui properties. + */ + void setPropertyCallbacks(); + + /** + * Subscribes to the group events that are shared by all DataCygnets + */ + void subscribeToGroup(); + /** * Optional interface method. this has an implementation * in datacygnet.cpp, but needs to be overriden for kameleonplane @@ -80,13 +91,24 @@ protected: virtual void setUniforms() = 0; properties::SelectionProperty _dataOptions; + properties::StringProperty _transferFunctionsFile; + properties::Vec2Property _backgroundValues; + properties::Vec2Property _normValues; + properties::BoolProperty _useLog; + properties::BoolProperty _useHistogram; + properties::BoolProperty _autoFilter; + std::shared_ptr _dataProcessor; std::string _dataBuffer; glm::size3_t _textureDimensions; + //FOR TESTING + int _numOfBenchmarks; + double _avgBenchmarkTime; + private: bool readyToRender() const override; - bool downloadTextureResource() override; + bool downloadTextureResource(double timestamp = Time::ref().currentTime()) override; }; } //namespace openspace diff --git a/modules/iswa/rendering/dataplane.cpp b/modules/iswa/rendering/dataplane.cpp index fb721d080e..2ac68f7b7e 100644 --- a/modules/iswa/rendering/dataplane.cpp +++ b/modules/iswa/rendering/dataplane.cpp @@ -32,21 +32,7 @@ namespace openspace { DataPlane::DataPlane(const ghoul::Dictionary& dictionary) :DataCygnet(dictionary) - ,_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") { - - addProperty(_useLog); - addProperty(_useHistogram); - addProperty(_autoFilter); - addProperty(_normValues); - addProperty(_backgroundValues); - addProperty(_transferFunctionsFile); - _programName = "DataPlaneProgram"; _vsPath = "${MODULE_ISWA}/shaders/dataplane_vs.glsl"; _fsPath = "${MODULE_ISWA}/shaders/dataplane_fs.glsl"; @@ -61,13 +47,6 @@ bool DataPlane::initialize(){ _dataProcessor = _group->dataProcessor(); subscribeToGroup(); }else{ - OsEng.gui()._iswa.registerProperty(&_useLog); - OsEng.gui()._iswa.registerProperty(&_useHistogram); - OsEng.gui()._iswa.registerProperty(&_autoFilter); - OsEng.gui()._iswa.registerProperty(&_normValues); - OsEng.gui()._iswa.registerProperty(&_backgroundValues); - OsEng.gui()._iswa.registerProperty(&_transferFunctionsFile); - OsEng.gui()._iswa.registerProperty(&_dataOptions); _dataProcessor = std::make_shared(); //If autofiler is on, background values property should be hidden @@ -76,42 +55,17 @@ bool DataPlane::initialize(){ // and unregister backgroundvalues property. if(_autoFilter.value()){ _backgroundValues.setValue(_dataProcessor->filterValues()); - OsEng.gui()._iswa.unregisterProperty(&_backgroundValues); + _backgroundValues.setVisible(false); // else if autofilter is turned off, register backgroundValues } else { - OsEng.gui()._iswa.registerProperty(&_backgroundValues, &_autoFilter); + _backgroundValues.setVisible(true); } }); } readTransferFunctions(_transferFunctionsFile.value()); - _normValues.onChange([this](){ - _dataProcessor->normValues(_normValues.value()); - updateTexture(); - }); - - _useLog.onChange([this](){ - _dataProcessor->useLog(_useLog.value()); - updateTexture(); - }); - - _useHistogram.onChange([this](){ - _dataProcessor->useHistogram(_useHistogram.value()); - updateTexture(); - if(_autoFilter.value()) - _backgroundValues.setValue(_dataProcessor->filterValues()); - }); - - _dataOptions.onChange([this](){ - if(_dataOptions.value().size() > MAX_TEXTURES) - LWARNING("Too many options chosen, max is " + std::to_string(MAX_TEXTURES)); - updateTexture(); - }); - - _transferFunctionsFile.onChange([this](){ - readTransferFunctions(_transferFunctionsFile.value()); - }); + setPropertyCallbacks(); _autoFilter.setValue(true); @@ -191,65 +145,27 @@ std::vector DataPlane::textureData(){ return std::vector(); } } - _textureDimensions = _dataProcessor->dimensions(); - return _dataProcessor->processData(_dataBuffer, _dataOptions); -} + // _textureDimensions = _dataProcessor->dimensions(); -void DataPlane::subscribeToGroup(){ - auto groupEvent = _group->groupEvent(); - groupEvent->subscribe(name(), "useLogChanged", [&](const ghoul::Dictionary& dict){ - LDEBUG(name() + " Event useLogChanged"); - _useLog.setValue(dict.value("useLog")); - }); + // FOR TESTING + // =========== + std::chrono::time_point start, end; + start = std::chrono::system_clock::now(); + // =========== + std::vector d = _dataProcessor->processData(_dataBuffer, _dataOptions, _textureDimensions); - groupEvent->subscribe(name(), "normValuesChanged", [&](ghoul::Dictionary dict){ - LDEBUG(name() + " Event normValuesChanged"); - glm::vec2 values; - bool success = dict.getValue("normValues", values); - if(success){ - _normValues.setValue(values); - } - }); + // FOR TESTING + // =========== + end = std::chrono::system_clock::now(); + _numOfBenchmarks++; + std::chrono::duration elapsed_seconds = end-start; + _avgBenchmarkTime = ( (_avgBenchmarkTime * (_numOfBenchmarks-1)) + elapsed_seconds.count() ) / _numOfBenchmarks; + std::cout << " processData() " << name() << std::endl; + std::cout << "avg elapsed time: " << _avgBenchmarkTime << "s\n"; + std::cout << "num Benchmarks: " << _numOfBenchmarks << "\n"; + // =========== - groupEvent->subscribe(name(), "useHistogramChanged", [&](ghoul::Dictionary dict){ - LDEBUG(name() + " Event useHistogramChanged"); - _useHistogram.setValue(dict.value("useHistogram")); - }); - - groupEvent->subscribe(name(), "dataOptionsChanged", [&](ghoul::Dictionary dict){ - LDEBUG(name() + " Event dataOptionsChanged"); - std::vector values; - bool success = dict.getValue >("dataOptions", values); - if(success){ - _dataOptions.setValue(values); - } - }); - - groupEvent->subscribe(name(), "transferFunctionsChanged", [&](ghoul::Dictionary dict){ - LDEBUG(name() + " Event transferFunctionsChanged"); - _transferFunctionsFile.setValue(dict.value("transferFunctions")); - }); - - groupEvent->subscribe(name(), "backgroundValuesChanged", [&](ghoul::Dictionary dict){ - LDEBUG(name() + " Event backgroundValuesChanged"); - glm::vec2 values; - bool success = dict.getValue("backgroundValues", values); - if(success){ - _backgroundValues.setValue(values); - } - }); - - groupEvent->subscribe(name(), "autoFilterChanged", [&](ghoul::Dictionary dict){ - LDEBUG(name() + " Event autoFilterChanged"); - _autoFilter.setValue(dict.value("autoFilter")); - }); - - groupEvent->subscribe(name(), "updateGroup", [&](ghoul::Dictionary dict){ - LDEBUG(name() + " Event updateGroup"); - if(_autoFilter.value()) - _backgroundValues.setValue(_dataProcessor->filterValues()); - updateTexture(); - }); + return d; } }// namespace openspace \ No newline at end of file diff --git a/modules/iswa/rendering/dataplane.h b/modules/iswa/rendering/dataplane.h index 59fb144e31..2efa100e6f 100644 --- a/modules/iswa/rendering/dataplane.h +++ b/modules/iswa/rendering/dataplane.h @@ -26,8 +26,6 @@ #define __DATAPLANE_H__ #include -#include -#include namespace openspace{ /** @@ -53,14 +51,6 @@ private: void renderGeometry() const override; void setUniforms() override; std::vector textureData() override; - void subscribeToGroup(); - - properties::StringProperty _transferFunctionsFile; - properties::Vec2Property _backgroundValues; - properties::Vec2Property _normValues; - properties::BoolProperty _useLog; - properties::BoolProperty _useHistogram; - properties::BoolProperty _autoFilter; GLuint _quad; GLuint _vertexPositionBuffer; diff --git a/modules/iswa/rendering/datasphere.cpp b/modules/iswa/rendering/datasphere.cpp index f68a267101..9e3da7d657 100644 --- a/modules/iswa/rendering/datasphere.cpp +++ b/modules/iswa/rendering/datasphere.cpp @@ -26,6 +26,11 @@ #include #include +#ifdef WIN32 +#define _USE_MATH_DEFINES +#include +#endif + namespace { const std::string _loggerCat = "DataSphere"; } @@ -34,25 +39,12 @@ namespace openspace { DataSphere::DataSphere(const ghoul::Dictionary& dictionary) :DataCygnet(dictionary) - ,_useLog("useLog","Use Logarithm", false) - ,_useHistogram("useHistogram", "Auto Contrast", false) - ,_autoFilter("autoFilter", "Auto Filter", false) - ,_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") ,_sphere(nullptr) { float radius; dictionary.getValue("Radius", radius); _radius = radius; - addProperty(_useLog); - addProperty(_useHistogram); - addProperty(_autoFilter); - addProperty(_normValues); - addProperty(_backgroundValues); - addProperty(_transferFunctionsFile); - _programName = "DataSphereProgram"; _vsPath = "${MODULE_ISWA}/shaders/datasphere_vs.glsl"; _fsPath = "${MODULE_ISWA}/shaders/datasphere_fs.glsl"; @@ -63,18 +55,13 @@ DataSphere::~DataSphere(){} bool DataSphere::initialize(){ IswaCygnet::initialize(); + //rotate 90 degrees because of the texture coordinates in PowerScaledSphere + _rotation = glm::rotate(_rotation, (float)M_PI_2, glm::vec3(1.0, 0.0, 0.0)); + if(_group){ _dataProcessor = _group->dataProcessor(); subscribeToGroup(); }else{ - OsEng.gui()._iswa.registerProperty(&_useLog); - OsEng.gui()._iswa.registerProperty(&_useHistogram); - OsEng.gui()._iswa.registerProperty(&_autoFilter); - OsEng.gui()._iswa.registerProperty(&_backgroundValues); - OsEng.gui()._iswa.registerProperty(&_normValues); - OsEng.gui()._iswa.registerProperty(&_transferFunctionsFile); - OsEng.gui()._iswa.registerProperty(&_dataOptions); - _dataProcessor = std::make_shared(); //If autofiler is on, background values property should be hidden _autoFilter.onChange([this](){ @@ -82,42 +69,17 @@ bool DataSphere::initialize(){ // and unregister backgroundvalues property. if(_autoFilter.value()){ _backgroundValues.setValue(_dataProcessor->filterValues()); + _backgroundValues.setVisible(false); // else if autofilter is turned off, register backgroundValues } else { - OsEng.gui()._iswa.registerProperty(&_backgroundValues, &_autoFilter); + _backgroundValues.setVisible(true); } }); } readTransferFunctions(_transferFunctionsFile.value()); - _normValues.onChange([this](){ - _dataProcessor->normValues(_normValues.value()); - updateTexture(); - }); - - _useLog.onChange([this](){ - _dataProcessor->useLog(_useLog.value()); - updateTexture(); - }); - - _useHistogram.onChange([this](){ - _dataProcessor->useHistogram(_useHistogram.value()); - updateTexture(); - if(_autoFilter.value()) - _backgroundValues.setValue(_dataProcessor->filterValues()); - }); - - _dataOptions.onChange([this](){ - if(_dataOptions.value().size() > MAX_TEXTURES) - LWARNING("Too many options chosen, max is " + std::to_string(MAX_TEXTURES)); - updateTexture(); - }); - - _transferFunctionsFile.onChange([this](){ - readTransferFunctions(_transferFunctionsFile.value()); - }); - + setPropertyCallbacks(); _useHistogram.setValue(true); _autoFilter.setValue(true); @@ -159,8 +121,8 @@ std::vector DataSphere::textureData(){ return std::vector(); } } - _textureDimensions = _dataProcessor->dimensions(); - return _dataProcessor->processData(_dataBuffer, _dataOptions); + // _textureDimensions = _dataProcessor->dimensions(); + return _dataProcessor->processData(_dataBuffer, _dataOptions, _textureDimensions); } void DataSphere::setUniforms(){ @@ -169,60 +131,4 @@ void DataSphere::setUniforms(){ _shader->setUniform("backgroundValues", _backgroundValues.value()); _shader->setUniform("transparency", _alpha.value()); } - -void DataSphere::subscribeToGroup(){ - auto groupEvent = _group->groupEvent(); - groupEvent->subscribe(name(), "useLogChanged", [&](const ghoul::Dictionary& dict){ - LDEBUG(name() + " Event useLogChanged"); - _useLog.setValue(dict.value("useLog")); - }); - - groupEvent->subscribe(name(), "normValuesChanged", [&](ghoul::Dictionary dict){ - LDEBUG(name() + " Event normValuesChanged"); - glm::vec2 values; - bool success = dict.getValue("normValues", values); - if(success){ - _normValues.setValue(values); - } - }); - - groupEvent->subscribe(name(), "useHistogramChanged", [&](ghoul::Dictionary dict){ - LDEBUG(name() + " Event useHistogramChanged"); - _useHistogram.setValue(dict.value("useHistogram")); - }); - - groupEvent->subscribe(name(), "dataOptionsChanged", [&](ghoul::Dictionary dict){ - LDEBUG(name() + " Event dataOptionsChanged"); - std::vector values; - bool success = dict.getValue >("dataOptions", values); - if(success){ - _dataOptions.setValue(values); - } - }); - - groupEvent->subscribe(name(), "transferFunctionsChanged", [&](ghoul::Dictionary dict){ - LDEBUG(name() + " Event transferFunctionsChanged"); - _transferFunctionsFile.setValue(dict.value("transferFunctions")); - }); - - groupEvent->subscribe(name(), "backgroundValuesChanged", [&](ghoul::Dictionary dict){ - LDEBUG(name() + " Event backgroundValuesChanged"); - glm::vec2 values; - bool success = dict.getValue("backgroundValues", values); - if(success){ - _backgroundValues.setValue(values); - } - }); - - groupEvent->subscribe(name(), "autoFilterChanged", [&](ghoul::Dictionary dict){ - LDEBUG(name() + " Event autoFilterChanged"); - _autoFilter.setValue(dict.value("autoFilter")); - }); - - groupEvent->subscribe(name(), "updateGroup", [&](ghoul::Dictionary dict){ - LDEBUG(name() + " Event updateGroup"); - updateTexture(); - }); -} - } //namespace openspace \ No newline at end of file diff --git a/modules/iswa/rendering/datasphere.h b/modules/iswa/rendering/datasphere.h index 6c96e263da..47206615a1 100644 --- a/modules/iswa/rendering/datasphere.h +++ b/modules/iswa/rendering/datasphere.h @@ -26,8 +26,6 @@ #define __DATASPHERE_H__ #include -#include -#include namespace openspace{ class PowerScaledSphere; @@ -53,14 +51,6 @@ protected: void renderGeometry() const override; void setUniforms() override; std::vector textureData() override; - void subscribeToGroup(); - - properties::StringProperty _transferFunctionsFile; - properties::Vec2Property _backgroundValues; - properties::Vec2Property _normValues; - properties::BoolProperty _useLog; - properties::BoolProperty _useHistogram; - properties::BoolProperty _autoFilter; std::shared_ptr _sphere; float _radius; diff --git a/modules/iswa/rendering/iswabasegroup.cpp b/modules/iswa/rendering/iswabasegroup.cpp index e7fb9de70d..2e3e56cc83 100644 --- a/modules/iswa/rendering/iswabasegroup.cpp +++ b/modules/iswa/rendering/iswabasegroup.cpp @@ -34,7 +34,6 @@ #include #include - namespace { const std::string _loggerCat = "IswaBaseGroup"; using json = nlohmann::json; @@ -87,9 +86,6 @@ std::shared_ptr > IswaBaseGroup::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()}})); @@ -101,7 +97,6 @@ void IswaBaseGroup::registerProperties(){ }); - OsEng.gui()._iswa.registerProperty(&_delete); _delete.onChange([this]{ clearGroup(); }); @@ -110,7 +105,6 @@ void IswaBaseGroup::registerProperties(){ } void IswaBaseGroup::unregisterProperties(){ - OsEng.gui()._iswa.unregisterProperties(name()); _registered = false; } diff --git a/modules/iswa/rendering/iswabasegroup.h b/modules/iswa/rendering/iswabasegroup.h index b69e75f3e9..5df21788db 100644 --- a/modules/iswa/rendering/iswabasegroup.h +++ b/modules/iswa/rendering/iswabasegroup.h @@ -42,29 +42,29 @@ class IswaCygnet; class IswaBaseGroup : public properties::PropertyOwner{ public: - IswaBaseGroup(std::string name, std::string type); - ~IswaBaseGroup(); - bool isType(std::string type); + IswaBaseGroup(std::string name, std::string type); + ~IswaBaseGroup(); + bool isType(std::string type); - void updateGroup(); - virtual void clearGroup(); + void updateGroup(); + virtual void clearGroup(); - std::shared_ptr dataProcessor(); - std::shared_ptr > groupEvent(); + std::shared_ptr dataProcessor(); + std::shared_ptr > groupEvent(); protected: - void registerProperties(); - void unregisterProperties(); + void registerProperties(); + void unregisterProperties(); - properties::BoolProperty _enabled; - properties::FloatProperty _alpha; + properties::BoolProperty _enabled; + properties::FloatProperty _alpha; properties::TriggerProperty _delete; - std::shared_ptr > _groupEvent; + std::shared_ptr > _groupEvent; std::shared_ptr _dataProcessor; - bool _registered; - std::string _type; + bool _registered; + std::string _type; }; } //namespace openspace diff --git a/modules/iswa/rendering/iswacygnet.cpp b/modules/iswa/rendering/iswacygnet.cpp index 816b88ff42..ee964d75e7 100644 --- a/modules/iswa/rendering/iswacygnet.cpp +++ b/modules/iswa/rendering/iswacygnet.cpp @@ -28,7 +28,6 @@ #include #include - namespace { const std::string _loggerCat = "IswaCygnet"; } @@ -42,6 +41,7 @@ IswaCygnet::IswaCygnet(const ghoul::Dictionary& dictionary) , _shader(nullptr) , _group(nullptr) , _textureDirty(false) + , _rotation(glm::mat4(1.0f)) { std::string name; dictionary.getValue("Name", name); @@ -52,6 +52,7 @@ IswaCygnet::IswaCygnet(const ghoul::Dictionary& dictionary) // dict.getValue can only set strings in _data directly float renderableId; float updateTime; + float xOffset; glm::vec3 min, max; glm::vec4 spatialScale; @@ -62,6 +63,7 @@ IswaCygnet::IswaCygnet(const ghoul::Dictionary& dictionary) dictionary.getValue("GridMax", max); dictionary.getValue("Frame",_data->frame); dictionary.getValue("CoordinateType", _data->coordinateType); + dictionary.getValue("XOffset", xOffset); _data->id = (int) renderableId; _data->updateTime = (int) updateTime; @@ -79,8 +81,9 @@ IswaCygnet::IswaCygnet(const ghoul::Dictionary& dictionary) (max.z - min.z) ); + offset = glm::vec3( - (min.x + (std::abs(min.x)+std::abs(max.x))/2.0f), + (min.x + (std::abs(min.x)+std::abs(max.x))/2.0f)+xOffset, (min.y + (std::abs(min.y)+std::abs(max.y))/2.0f), (min.z + (std::abs(min.z)+std::abs(max.z))/2.0f) ); @@ -102,9 +105,6 @@ bool IswaCygnet::initialize(){ if(!_data->groupName.empty()){ initializeGroup(); }else{ - OsEng.gui()._iswa.registerProperty(&_alpha); - OsEng.gui()._iswa.registerProperty(&_delete); - _delete.onChange([this](){ deinitialize(); OsEng.scriptEngine().queueScript("openspace.removeSceneGraphNode('" + name() + "')"); @@ -116,7 +116,7 @@ bool IswaCygnet::initialize(){ createShader(); downloadTextureResource(); - return true; + return true; } bool IswaCygnet::deinitialize(){ @@ -143,12 +143,12 @@ void IswaCygnet::render(const RenderData& data){ psc position = data.position; glm::mat4 transform = glm::mat4(1.0); - glm::mat4 rot = glm::mat4(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*_rotation; position += transform*glm::vec4(_data->spatialScale.x*_data->offset, _data->spatialScale.w); @@ -171,6 +171,13 @@ void IswaCygnet::render(const RenderData& data){ } void IswaCygnet::update(const UpdateData& data){ + + if (!_enabled) + return; + + // 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(); _realTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()); _stateMatrix = TransformationManager::ref().frameTransformationMatrix(_data->frame, "GALACTIC", _openSpaceTime); @@ -178,22 +185,19 @@ void IswaCygnet::update(const UpdateData& data){ bool timeToUpdate = (fabs(_openSpaceTime-_lastUpdateOpenSpaceTime) >= _data->updateTime && (_realTime.count()-_lastUpdateRealTime.count()) > _minRealTimeUpdateInterval); - if( _data->updateTime != 0 && (Time::ref().timeJumped() || timeToUpdate )){ - downloadTextureResource(); - - _lastUpdateRealTime = _realTime; - _lastUpdateOpenSpaceTime = _openSpaceTime; - } - if(_futureObject.valid() && DownloadManager::futureReady(_futureObject)) { bool success = updateTextureResource(); if(success) _textureDirty = true; } - - if(_textureDirty) { + + if(_textureDirty && _data->updateTime != 0 && timeToUpdate) { updateTexture(); _textureDirty = false; + + downloadTextureResource(_openSpaceTime + clockwiseSign*_data->updateTime); + _lastUpdateRealTime = _realTime; + _lastUpdateOpenSpaceTime =_openSpaceTime; } if(!_transferFunctions.empty()) @@ -208,21 +212,18 @@ bool IswaCygnet::destroyShader(){ renderEngine.removeRenderProgram(_shader); _shader = nullptr; } - return true; + return true; } void IswaCygnet::registerProperties(){ - OsEng.gui()._iswa.registerProperty(&_enabled); - // OsEng.gui()._iswa.registerProperty(&_delete); } void IswaCygnet::unregisterProperties(){ - OsEng.gui()._iswa.unregisterProperties(name()); } void IswaCygnet::initializeTime(){ _openSpaceTime = Time::ref().currentTime(); - _lastUpdateOpenSpaceTime = _openSpaceTime; + _lastUpdateOpenSpaceTime = 0.0; _realTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()); _lastUpdateRealTime = _realTime; diff --git a/modules/iswa/rendering/iswacygnet.h b/modules/iswa/rendering/iswacygnet.h index 8ee87f1ce4..c123aa5c22 100644 --- a/modules/iswa/rendering/iswacygnet.h +++ b/modules/iswa/rendering/iswacygnet.h @@ -25,10 +25,6 @@ #ifndef __ISWACYGNET_H__ #define __ISWACYGNET_H__ -#define _USE_MATH_DEFINES -#include - -#include #include #include #include @@ -38,6 +34,7 @@ #include #include #include +#include #include #include @@ -64,7 +61,6 @@ struct Metadata { class IswaCygnet : public Renderable, public std::enable_shared_from_this { - friend class IswaBaseGroup; public: IswaCygnet(const ghoul::Dictionary& dictionary); @@ -119,7 +115,7 @@ protected: * this should be the data file. * @return true if update was successfull */ - virtual bool downloadTextureResource() = 0; + virtual bool downloadTextureResource(double timestamp = Time::ref().currentTime()) = 0; virtual bool readyToRender() const = 0; /** * should set all uniforms needed to render @@ -134,6 +130,21 @@ protected: std::shared_ptr _data; + std::vector> _transferFunctions; + std::future _futureObject; + + std::shared_ptr _group; + + bool _textureDirty; + + // Must be set by children. + std::string _vsPath; + std::string _fsPath; + std::string _programName; + + glm::mat4 _rotation; //to rotate objects with fliped texture coordniates +private: + bool destroyShader(); glm::dmat3 _stateMatrix; double _openSpaceTime; @@ -143,20 +154,6 @@ protected: std::chrono::milliseconds _lastUpdateRealTime; int _minRealTimeUpdateInterval; - std::vector> _transferFunctions; - std::future _futureObject; - - std::shared_ptr _group; - - bool _textureDirty; - - std::string _vsPath; - std::string _fsPath; - std::string _programName; - -private: - bool destroyShader(); - }; }//namespace openspace diff --git a/modules/iswa/rendering/iswadatagroup.cpp b/modules/iswa/rendering/iswadatagroup.cpp index fbe7bb9723..6fbff8e972 100644 --- a/modules/iswa/rendering/iswadatagroup.cpp +++ b/modules/iswa/rendering/iswadatagroup.cpp @@ -66,15 +66,15 @@ IswaDataGroup::IswaDataGroup(std::string name, std::string type) IswaDataGroup::~IswaDataGroup(){} void IswaDataGroup::registerProperties(){ - OsEng.gui()._iswa.registerProperty(&_useLog); - OsEng.gui()._iswa.registerProperty(&_useHistogram); - OsEng.gui()._iswa.registerProperty(&_autoFilter); - if(!_autoFilter.value()) - OsEng.gui()._iswa.registerProperty(&_backgroundValues); - // OsEng.gui()._iswa.registerProperty(&_autoFilter); - OsEng.gui()._iswa.registerProperty(&_normValues); - OsEng.gui()._iswa.registerProperty(&_transferFunctionsFile); - OsEng.gui()._iswa.registerProperty(&_dataOptions); + //OsEng.gui()._iswa.registerProperty(&_useLog); + //OsEng.gui()._iswa.registerProperty(&_useHistogram); + //OsEng.gui()._iswa.registerProperty(&_autoFilter); + //if(!_autoFilter.value()) + // OsEng.gui()._iswa.registerProperty(&_backgroundValues); + //// OsEng.gui()._iswa.registerProperty(&_autoFilter); + //OsEng.gui()._iswa.registerProperty(&_normValues); + //OsEng.gui()._iswa.registerProperty(&_transferFunctionsFile); + //OsEng.gui()._iswa.registerProperty(&_dataOptions); _useLog.onChange([this]{ @@ -94,10 +94,10 @@ void IswaDataGroup::registerProperties(){ // and unregister backgroundvalues property. if(_autoFilter.value()){ _backgroundValues.setValue(_dataProcessor->filterValues()); - OsEng.gui()._iswa.unregisterProperty(&_backgroundValues); + _backgroundValues.setVisible(false); // else if autofilter is turned off, register backgroundValues } else { - OsEng.gui()._iswa.registerProperty(&_backgroundValues, &_autoFilter); + _backgroundValues.setVisible(true); } _groupEvent->publish("autoFilterChanged", ghoul::Dictionary({{"autoFilter", _autoFilter.value()}})); }); diff --git a/modules/iswa/rendering/iswagroup.h b/modules/iswa/rendering/iswagroup.h index b69e75f3e9..5df21788db 100644 --- a/modules/iswa/rendering/iswagroup.h +++ b/modules/iswa/rendering/iswagroup.h @@ -42,29 +42,29 @@ class IswaCygnet; class IswaBaseGroup : public properties::PropertyOwner{ public: - IswaBaseGroup(std::string name, std::string type); - ~IswaBaseGroup(); - bool isType(std::string type); + IswaBaseGroup(std::string name, std::string type); + ~IswaBaseGroup(); + bool isType(std::string type); - void updateGroup(); - virtual void clearGroup(); + void updateGroup(); + virtual void clearGroup(); - std::shared_ptr dataProcessor(); - std::shared_ptr > groupEvent(); + std::shared_ptr dataProcessor(); + std::shared_ptr > groupEvent(); protected: - void registerProperties(); - void unregisterProperties(); + void registerProperties(); + void unregisterProperties(); - properties::BoolProperty _enabled; - properties::FloatProperty _alpha; + properties::BoolProperty _enabled; + properties::FloatProperty _alpha; properties::TriggerProperty _delete; - std::shared_ptr > _groupEvent; + std::shared_ptr > _groupEvent; std::shared_ptr _dataProcessor; - bool _registered; - std::string _type; + bool _registered; + std::string _type; }; } //namespace openspace diff --git a/modules/iswa/rendering/iswakameleongroup.cpp b/modules/iswa/rendering/iswakameleongroup.cpp index 688bba237b..4273f8330e 100644 --- a/modules/iswa/rendering/iswakameleongroup.cpp +++ b/modules/iswa/rendering/iswakameleongroup.cpp @@ -41,15 +41,15 @@ namespace { namespace openspace{ IswaKameleonGroup::IswaKameleonGroup(std::string name, std::string type) - :IswaDataGroup(name, type) + :IswaDataGroup(name, type) ,_resolution("resolution", "Resolution%", 100.0f, 10.0f, 200.0f) - ,_fieldlines("fieldlineSeedsIndexFile", "Fieldline Seedpoints") + ,_fieldlines("fieldlineSeedsIndexFile", "Fieldline Seedpoints") ,_fieldlineIndexFile("") ,_kameleonPath("") { addProperty(_resolution); addProperty(_fieldlines); - registerProperties(); + registerProperties(); } IswaKameleonGroup::~IswaKameleonGroup(){} @@ -60,7 +60,7 @@ void IswaKameleonGroup::clearGroup(){ } std::vector IswaKameleonGroup::fieldlineValue(){ - return _fieldlines.value(); + return _fieldlines.value(); } void IswaKameleonGroup::setFieldlineInfo(std::string fieldlineIndexFile, std::string kameleonPath){ @@ -78,8 +78,8 @@ void IswaKameleonGroup::setFieldlineInfo(std::string fieldlineIndexFile, std::st void IswaKameleonGroup::registerProperties(){ - OsEng.gui()._iswa.registerProperty(&_resolution); - OsEng.gui()._iswa.registerProperty(&_fieldlines); + //OsEng.gui()._iswa.registerProperty(&_resolution); + //OsEng.gui()._iswa.registerProperty(&_fieldlines); _resolution.onChange([this]{ LDEBUG("Group " + name() + " published resolutionChanged"); @@ -88,7 +88,7 @@ void IswaKameleonGroup::registerProperties(){ _fieldlines.onChange([this]{ updateFieldlineSeeds(); - }); + }); } void IswaKameleonGroup::readFieldlinePaths(std::string indexFile){ diff --git a/modules/iswa/rendering/kameleonplane.cpp b/modules/iswa/rendering/kameleonplane.cpp index 79d046c9b9..9a5dab1125 100644 --- a/modules/iswa/rendering/kameleonplane.cpp +++ b/modules/iswa/rendering/kameleonplane.cpp @@ -39,25 +39,13 @@ namespace openspace { KameleonPlane::KameleonPlane(const ghoul::Dictionary& dictionary) :DataCygnet(dictionary) - ,_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") ,_fieldlines("fieldlineSeedsIndexFile", "Fieldline Seedpoints") ,_resolution("resolution", "Resolution%", 100.0f, 10.0f, 200.0f) ,_slice("slice", "Slice", 0.0, 0.0, 1.0) { - addProperty(_useLog); - addProperty(_useHistogram); - addProperty(_autoFilter); - addProperty(_normValues); - addProperty(_backgroundValues); addProperty(_resolution); addProperty(_slice); - addProperty(_transferFunctionsFile); addProperty(_fieldlines); dictionary.getValue("kwPath", _kwPath); @@ -68,9 +56,6 @@ KameleonPlane::KameleonPlane(const ghoul::Dictionary& dictionary) std::string axis; dictionary.getValue("axisCut", axis); - OsEng.gui()._iswa.registerProperty(&_slice); - - if(axis == "x") _cut = 0; else if (axis == "y") _cut = 1; else _cut = 2; @@ -114,15 +99,6 @@ bool KameleonPlane::initialize(){ _dataProcessor = _group->dataProcessor(); subscribeToGroup(); }else{ - OsEng.gui()._iswa.registerProperty(&_useLog); - OsEng.gui()._iswa.registerProperty(&_useHistogram); - OsEng.gui()._iswa.registerProperty(&_autoFilter); - OsEng.gui()._iswa.registerProperty(&_normValues); - OsEng.gui()._iswa.registerProperty(&_backgroundValues); - OsEng.gui()._iswa.registerProperty(&_resolution); - OsEng.gui()._iswa.registerProperty(&_transferFunctionsFile); - OsEng.gui()._iswa.registerProperty(&_fieldlines); - OsEng.gui()._iswa.registerProperty(&_dataOptions); _dataProcessor = std::make_shared(); //If autofiler is on, background values property should be hidden @@ -131,35 +107,22 @@ bool KameleonPlane::initialize(){ // and unregister backgroundvalues property. if(_autoFilter.value()){ _backgroundValues.setValue(_dataProcessor->filterValues()); - OsEng.gui()._iswa.unregisterProperty(&_backgroundValues); + _backgroundValues.setVisible(false); // else if autofilter is turned off, register backgroundValues } else { - OsEng.gui()._iswa.registerProperty(&_backgroundValues, &_autoFilter); + _backgroundValues.setVisible(true); } }); } + fillOptions(_kwPath); + readTransferFunctions(_transferFunctionsFile.value()); - _normValues.onChange([this](){ - _dataProcessor->normValues(_normValues.value()); - updateTexture(); - }); - - _useLog.onChange([this](){ - _dataProcessor->useLog(_useLog.value()); - updateTexture(); - }); - - _useHistogram.onChange([this](){ - _dataProcessor->useHistogram(_useHistogram.value()); - updateTexture(); - }); - - _transferFunctionsFile.onChange([this](){ - readTransferFunctions(_transferFunctionsFile.value()); - }); - + // Set Property Callbacks of DataCygnet (must be called after fillOptions) + setPropertyCallbacks(); + + // Set Property callback specific to KameleonPlane _resolution.onChange([this](){ for(int i=0; i<_textures.size(); i++){ _textures[i] = std::move(nullptr); @@ -178,14 +141,6 @@ bool KameleonPlane::initialize(){ updateFieldlineSeeds(); }); - fillOptions(_kwPath); - // Has to be done after fillOptions - _dataOptions.onChange([this](){ - if(_dataOptions.value().size() > MAX_TEXTURES) - LWARNING("Too many options chosen, max is " + std::to_string(MAX_TEXTURES)); - updateTexture(); - }); - std::dynamic_pointer_cast(_dataProcessor)->dimensions(_dimensions); _dataProcessor->addDataValues(_kwPath, _dataOptions); // if this datacygnet has added new values then reload texture @@ -195,7 +150,7 @@ bool KameleonPlane::initialize(){ } updateTextureResource(); - return true; + return true; } bool KameleonPlane::createGeometry() { @@ -249,14 +204,14 @@ void KameleonPlane::renderGeometry() const { } std::vector KameleonPlane::textureData() { - return std::dynamic_pointer_cast(_dataProcessor)->processData(_kwPath, _dataOptions, _slice, _dimensions); + return std::dynamic_pointer_cast(_dataProcessor)->processData(_kwPath, _dataOptions, _dimensions, _slice); }; bool KameleonPlane::updateTextureResource(){ _data->offset[_cut] = _data->gridMin[_cut]+_slice.value()*_scale; - _textureDirty = true; - + // _textureDirty = true; + updateTexture(); return true; } @@ -319,62 +274,11 @@ void KameleonPlane::readFieldlinePaths(std::string indexFile){ } void KameleonPlane::subscribeToGroup(){ + // Subscribe to DataCygnet events + DataCygnet::subscribeToGroup(); + + //Add additional Events specific to KameleonPlane auto groupEvent = _group->groupEvent(); - - groupEvent->subscribe(name(), "useLogChanged", [&](const ghoul::Dictionary& dict){ - LDEBUG(name() + " Event useLogChanged"); - _useLog.setValue(dict.value("useLog")); - }); - - groupEvent->subscribe(name(), "normValuesChanged", [&](ghoul::Dictionary dict){ - LDEBUG(name() + " Event normValuesChanged"); - glm::vec2 values; - bool success = dict.getValue("normValues", values); - if(success){ - _normValues.setValue(values); - } - }); - - groupEvent->subscribe(name(), "useHistogramChanged", [&](ghoul::Dictionary dict){ - LDEBUG(name() + " Event useHistogramChanged"); - _useHistogram.setValue(dict.value("useHistogram")); - }); - - groupEvent->subscribe(name(), "dataOptionsChanged", [&](ghoul::Dictionary dict){ - LDEBUG(name() + " Event dataOptionsChanged"); - std::vector values; - bool success = dict.getValue >("dataOptions", values); - if(success){ - _dataOptions.setValue(values); - } - }); - - groupEvent->subscribe(name(), "transferFunctionsChanged", [&](ghoul::Dictionary dict){ - LDEBUG(name() + " Event transferFunctionsChanged"); - _transferFunctionsFile.setValue(dict.value("transferFunctions")); - }); - - groupEvent->subscribe(name(), "backgroundValuesChanged", [&](ghoul::Dictionary dict){ - LDEBUG(name() + " Event backgroundValuesChanged"); - glm::vec2 values; - bool success = dict.getValue("backgroundValues", values); - if(success){ - _backgroundValues.setValue(values); - } - }); - - groupEvent->subscribe(name(), "autoFilterChanged", [&](ghoul::Dictionary dict){ - LDEBUG(name() + " Event autoFilterChanged"); - _autoFilter.setValue(dict.value("autoFilter")); - }); - - groupEvent->subscribe(name(), "updateGroup", [&](ghoul::Dictionary dict){ - LDEBUG(name() + " Event updateGroup"); - if(_autoFilter.value()) - _backgroundValues.setValue(_dataProcessor->filterValues()); - updateTexture(); - }); - groupEvent->subscribe(name(), "resolutionChanged", [&](ghoul::Dictionary dict){ LDEBUG(name() + " Event resolutionChanged"); float resolution; @@ -391,7 +295,6 @@ void KameleonPlane::subscribeToGroup(){ if(success){ changeKwPath(path); } - updateTexture(); }); } diff --git a/modules/iswa/rendering/kameleonplane.h b/modules/iswa/rendering/kameleonplane.h index b4fe88ae24..9b1ab3a933 100644 --- a/modules/iswa/rendering/kameleonplane.h +++ b/modules/iswa/rendering/kameleonplane.h @@ -26,7 +26,6 @@ #define __KAMELEONPLANE_H__ #include -#include #include namespace openspace{ @@ -41,8 +40,8 @@ namespace openspace{ */ class KameleonPlane : public DataCygnet { public: - KameleonPlane(const ghoul::Dictionary& dictionary); - ~KameleonPlane(); + KameleonPlane(const ghoul::Dictionary& dictionary); + ~KameleonPlane(); bool initialize() override; bool deinitialize() override; @@ -77,21 +76,12 @@ private: void subscribeToGroup(); void changeKwPath(std::string path); - static int id(); + static int id(); properties::FloatProperty _resolution; properties::FloatProperty _slice; - properties::StringProperty _transferFunctionsFile; - properties::SelectionProperty _fieldlines; - properties::Vec2Property _backgroundValues; - properties::Vec2Property _normValues; - - properties::BoolProperty _useLog; - properties::BoolProperty _useHistogram; - properties::BoolProperty _autoFilter; - std::string _kwPath; glm::size3_t _dimensions; diff --git a/modules/iswa/rendering/screenspacecygnet.cpp b/modules/iswa/rendering/screenspacecygnet.cpp index ea6689dd4a..7b493ea866 100644 --- a/modules/iswa/rendering/screenspacecygnet.cpp +++ b/modules/iswa/rendering/screenspacecygnet.cpp @@ -27,6 +27,7 @@ #include #include #include +#include namespace { const std::string _loggerCat = "ScreenSpaceCygnet"; diff --git a/modules/iswa/rendering/texturecygnet.cpp b/modules/iswa/rendering/texturecygnet.cpp index 0616cc4f20..7a601e55d3 100644 --- a/modules/iswa/rendering/texturecygnet.cpp +++ b/modules/iswa/rendering/texturecygnet.cpp @@ -58,7 +58,7 @@ bool TextureCygnet::updateTexture() { return false; } -bool TextureCygnet::downloadTextureResource(){ +bool TextureCygnet::downloadTextureResource(double timestamp){ if(_futureObject.valid()) return false; @@ -66,7 +66,7 @@ bool TextureCygnet::downloadTextureResource(){ if(_textures.empty()) _textures.push_back(nullptr); - std::future future = IswaManager::ref().fetchImageCygnet(_data->id); + std::future future = IswaManager::ref().fetchImageCygnet(_data->id, timestamp); if(future.valid()){ _futureObject = std::move(future); diff --git a/modules/iswa/rendering/texturecygnet.h b/modules/iswa/rendering/texturecygnet.h index 8d977d1f5b..1beef542c2 100644 --- a/modules/iswa/rendering/texturecygnet.h +++ b/modules/iswa/rendering/texturecygnet.h @@ -43,7 +43,7 @@ public: protected: bool updateTexture() override; - bool downloadTextureResource() override; + bool downloadTextureResource(double timestamp = Time::ref().currentTime()) override; bool readyToRender() const override; bool updateTextureResource() override; diff --git a/modules/iswa/rendering/textureplane.cpp b/modules/iswa/rendering/textureplane.cpp index 777dac2c1a..6276fb9900 100644 --- a/modules/iswa/rendering/textureplane.cpp +++ b/modules/iswa/rendering/textureplane.cpp @@ -37,8 +37,8 @@ TexturePlane::TexturePlane(const ghoul::Dictionary& dictionary) ,_vertexPositionBuffer(0) { _programName = "PlaneProgram"; - _vsPath = "${MODULE_ISWA}/shaders/cygnetplane_vs.glsl"; - _fsPath = "${MODULE_ISWA}/shaders/cygnetplane_fs.glsl"; + _vsPath = "${MODULE_ISWA}/shaders/textureplane_vs.glsl"; + _fsPath = "${MODULE_ISWA}/shaders/textureplane_fs.glsl"; } TexturePlane::~TexturePlane(){} diff --git a/modules/iswa/shaders/dataplane_fs.glsl b/modules/iswa/shaders/dataplane_fs.glsl index 58f45b1052..7307cf0e6e 100644 --- a/modules/iswa/shaders/dataplane_fs.glsl +++ b/modules/iswa/shaders/dataplane_fs.glsl @@ -55,7 +55,7 @@ Fragment getFragment() { if((numTransferFunctions == 1) || (numTextures > numTransferFunctions)){ for(int i=0; i(x-y)) color = transparent; diff --git a/modules/iswa/shaders/cygnetplane_fs.glsl b/modules/iswa/shaders/textureplane_fs.glsl similarity index 87% rename from modules/iswa/shaders/cygnetplane_fs.glsl rename to modules/iswa/shaders/textureplane_fs.glsl index a08658ee89..d290d159c3 100644 --- a/modules/iswa/shaders/cygnetplane_fs.glsl +++ b/modules/iswa/shaders/textureplane_fs.glsl @@ -36,19 +36,7 @@ Fragment getFragment() { vec4 position = vs_position; float depth = pscDepth(position); vec4 diffuse; - diffuse = texture(texture1, vec2(vs_st.s, 1-vs_st.t)); - - //vec4 diffuse = vec4(1,vs_st,1); - //vec4 diffuse = vec4(1,0,0,1); - // if(position.w > 9.0) { - // diffuse = vec4(1,0,0,1); - // } - - //diffuse.a = diffuse.r; - float tot = diffuse.r + diffuse.g + diffuse.b; - tot /= 3.0; - if (tot >= 0.5 || tot <= 0.05) - discard; + diffuse = texture(texture1, vs_st); diffuse.a *= transparency; diff --git a/modules/iswa/shaders/cygnetplane_vs.glsl b/modules/iswa/shaders/textureplane_vs.glsl similarity index 100% rename from modules/iswa/shaders/cygnetplane_vs.glsl rename to modules/iswa/shaders/textureplane_vs.glsl diff --git a/modules/iswa/util/dataprocessor.cpp b/modules/iswa/util/dataprocessor.cpp index d0897ec2f5..5e7e80e50f 100644 --- a/modules/iswa/util/dataprocessor.cpp +++ b/modules/iswa/util/dataprocessor.cpp @@ -25,21 +25,9 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include namespace { const std::string _loggerCat = "DataProcessor"; - using json = nlohmann::json; } namespace openspace { @@ -48,6 +36,7 @@ DataProcessor::DataProcessor() ,_useHistogram(false) ,_normValues(glm::vec2(1.0)) ,_filterValues(glm::vec2(0.0)) + ,_histNormValues(glm::vec2(10.f, 10.f)) { _coordinateVariables = {"x", "y", "z", "phi", "theta"}; } @@ -90,20 +79,21 @@ float DataProcessor::processDataPoint(float value, int option){ float mean = (1.0 / _numValues[option]) * _sum[option]; float sd = _standardDeviation[option]; + float v; if(_useHistogram){ - sd = histogram->equalize(sd); - mean = histogram->equalize(mean); - value = histogram->equalize(value); + v = histogram->equalize(normalizeWithStandardScore(value, mean, sd, _histNormValues))/(float)512; + }else{ + v = normalizeWithStandardScore(value, mean, sd, _normValues); } - float v = normalizeWithStandardScore(value, mean, sd); + // float v = normalizeWithStandardScore(value, mean, sd, _normValues); return v; } -float DataProcessor::normalizeWithStandardScore(float value, float mean, float sd){ +float DataProcessor::normalizeWithStandardScore(float value, float mean, float sd, glm::vec2 normalizationValues){ - float zScoreMin = _normValues.x; - float zScoreMax = _normValues.y; + float zScoreMin = normalizationValues.x; //10.0f;//_normValues.x; + float zScoreMax = normalizationValues.y; //10.0f;//_normValues.y; float standardScore = ( value - mean ) / sd; // Clamp intresting values standardScore = glm::clamp(standardScore, -zScoreMin, zScoreMax); @@ -111,6 +101,22 @@ float DataProcessor::normalizeWithStandardScore(float value, float mean, float s return ( standardScore + zScoreMin )/(zScoreMin + zScoreMax ); } +float DataProcessor::unnormalizeWithStandardScore(float standardScore, float mean, float sd, glm::vec2 normalizationValues){ + float zScoreMin = normalizationValues.x; + float zScoreMax = normalizationValues.y; + + float value = standardScore*(zScoreMax+zScoreMin)-zScoreMin; + value = value*sd+mean; + + // std::cout << value << std::endl; + return value; + // float standardScore = ( value - mean ) / sd; + // // Clamp intresting values + // standardScore = glm::clamp(standardScore, -zScoreMin, zScoreMax); + // //return and normalize + // return ( standardScore + zScoreMin )/(zScoreMin + zScoreMax ); +} + void DataProcessor::initializeVectors(int numOptions){ if(_min.empty()) _min = std::vector(numOptions, std::numeric_limits::max()); if(_max.empty()) _max = std::vector(numOptions, std::numeric_limits::min()); @@ -130,22 +136,24 @@ void DataProcessor::calculateFilterValues(std::vector selectedOptions){ if(!_histograms.empty()){ for(int option : selectedOptions){ - histogram = _histograms[option]; - mean = (1.0/_numValues[option])*_sum[option]; - standardDeviation = _standardDeviation[option]; - - filterMid = histogram->highestBinValue(_useHistogram); - filterWidth = mean+histogram->binWidth(); - - if(_useHistogram){ - standardDeviation = histogram->equalize(standardDeviation); - mean = histogram->equalize(mean); - filterWidth = mean+1; + if(!_useHistogram){ + mean = (1.0/_numValues[option])*_sum[option]; + standardDeviation = _standardDeviation[option]; + histogram = _histograms[option]; + + filterMid = histogram->highestBinValue(_useHistogram); + filterWidth = mean+histogram->binWidth(); + + filterMid = normalizeWithStandardScore(filterMid, mean, standardDeviation, _normValues); + filterWidth = fabs(0.5-normalizeWithStandardScore(filterWidth, mean, standardDeviation, _normValues)); + }else{ + Histogram hist = _histograms[option]->equalize(); + filterMid = hist.highestBinValue(true); + std::cout << filterMid << std::endl; + filterWidth = 1.f/512.f; } - filterMid = normalizeWithStandardScore(filterMid, mean, standardDeviation); - filterWidth = fabs(0.5-normalizeWithStandardScore(filterWidth, mean, standardDeviation)); - _filterValues += glm::vec2(filterMid, filterWidth); + _filterValues += glm::vec2(filterMid, filterWidth); } _filterValues /= numSelected; @@ -158,12 +166,6 @@ void DataProcessor::add(std::vector>& optionValues, std::vect float mean, value, variance, standardDeviation; for(int i=0; i(_min[i], _max[i], 512); - } - else{ - _histograms[i]->changeRange(_min[i], _max[i]); - } std::vector values = optionValues[i]; numValues = values.size(); @@ -174,16 +176,64 @@ void DataProcessor::add(std::vector>& optionValues, std::vect for(int j=0; jadd(value, 1); } standardDeviation = sqrt(variance/ numValues); + float oldStandardDeviation = _standardDeviation[i]; + float oldMean = (1.0f/_numValues[i])*_sum[i]; + _sum[i] += sum[i]; _standardDeviation[i] = sqrt(pow(standardDeviation, 2) + pow(_standardDeviation[i], 2)); _numValues[i] += numValues; + + + mean = (1.0f/_numValues[i])*_sum[i]; + float min = normalizeWithStandardScore(_min[i], mean, _standardDeviation[i], _histNormValues); + float max = normalizeWithStandardScore(_max[i], mean, _standardDeviation[i], _histNormValues); + + if(!_histograms[i]){ + _histograms[i] = std::make_shared(min, max, 512); + } + else{ + + const float* histData = _histograms[i]->data(); + float histMin = _histograms[i]->minValue(); + float histMax = _histograms[i]->maxValue(); + int numBins = _histograms[i]->numBins(); + + float unNormHistMin = unnormalizeWithStandardScore(histMin, oldMean, oldStandardDeviation, _histNormValues); + float unNormHistMax = unnormalizeWithStandardScore(histMax, oldMean, oldStandardDeviation, _histNormValues); + //unnormalize histMin, histMax + // min = std::min(min, histMin) + std::shared_ptr newHist = std::make_shared( + std::min(min, normalizeWithStandardScore(unNormHistMin, mean, _standardDeviation[i], _histNormValues)), + std::min(max, normalizeWithStandardScore(unNormHistMax, mean, _standardDeviation[i], _histNormValues)), + numBins + ); + + for(int j=0; jadd(normalizeWithStandardScore(value, mean, _standardDeviation[i], _histNormValues), histData[j]); + } + // _histograms[i]->changeRange(min, max); + _histograms[i] = newHist; + } + + for(int j=0; jadd(normalizeWithStandardScore(value, mean, _standardDeviation[i], _histNormValues), 1); + } _histograms[i]->generateEqualizer(); + + std::cout << std::endl; + _histograms[i]->print(); + std::cout << std::endl; + std::cout << "Eq: "; + Histogram hist = _histograms[i]->equalize(); + hist.print(); } } diff --git a/modules/iswa/util/dataprocessor.h b/modules/iswa/util/dataprocessor.h index c50b8cfe23..75ecd78da0 100644 --- a/modules/iswa/util/dataprocessor.h +++ b/modules/iswa/util/dataprocessor.h @@ -25,11 +25,9 @@ #ifndef __DATAPROCESSOR_H__ #define __DATAPROCESSOR_H__ -#include -#include #include #include -#include +#include #include #include @@ -40,9 +38,9 @@ public: DataProcessor(); ~DataProcessor(); - virtual std::vector readMetadata(std::string data) = 0; + virtual std::vector readMetadata(std::string data, glm::size3_t& dimensions) = 0; virtual void addDataValues(std::string data, properties::SelectionProperty& dataOptions) = 0; - virtual std::vector processData(std::string data, properties::SelectionProperty& dataOptions) = 0; + virtual std::vector processData(std::string data, properties::SelectionProperty& dataOptions, glm::size3_t& dimensions) = 0; void useLog(bool useLog); void useHistogram(bool useHistogram); @@ -53,7 +51,8 @@ public: void clear(); protected: float processDataPoint(float value, int option); - float normalizeWithStandardScore(float value, float mean, float sd); + float normalizeWithStandardScore(float value, float mean, float sd, glm::vec2 normalizationValues = glm::vec2(1.0f, 1.0f)); + float unnormalizeWithStandardScore(float value, float mean, float sd, glm::vec2 normalizationValues = glm::vec2(1.0f, 1.0f)); void initializeVectors(int numOptions); void calculateFilterValues(std::vector selectedOptions); @@ -72,6 +71,8 @@ protected: std::vector _numValues; std::vector> _histograms; std::set _coordinateVariables; + + glm::vec2 _histNormValues; }; } // namespace openspace diff --git a/modules/iswa/util/dataprocessorjson.cpp b/modules/iswa/util/dataprocessorjson.cpp index b3da5953a2..151f8e6a13 100644 --- a/modules/iswa/util/dataprocessorjson.cpp +++ b/modules/iswa/util/dataprocessorjson.cpp @@ -39,7 +39,7 @@ DataProcessorJson::DataProcessorJson() DataProcessorJson::~DataProcessorJson(){} -std::vector DataProcessorJson::readMetadata(std::string data){ +std::vector DataProcessorJson::readMetadata(std::string data, glm::size3_t& dimensions){ std::vector options = std::vector(); if(!data.empty()){ json j = json::parse(data); @@ -47,11 +47,11 @@ std::vector DataProcessorJson::readMetadata(std::string data){ for(json::iterator it = variables.begin(); it != variables.end(); ++it){ std::string option = it.key(); - if(option == "x"){ + if(option == "ep"){ json row = it.value(); json col = row.at(0); - _dimensions = glm::size3_t(col.size(), row.size(), 1); + dimensions = glm::size3_t(col.size(), row.size(), 1); } if(_coordinateVariables.find(option) == _coordinateVariables.end()){ @@ -99,7 +99,7 @@ void DataProcessorJson::addDataValues(std::string data, properties::SelectionPro } } -std::vector DataProcessorJson::processData(std::string data, properties::SelectionProperty& dataOptions){ +std::vector DataProcessorJson::processData(std::string data, properties::SelectionProperty& dataOptions, glm::size3_t& dimensions){ if(!data.empty()){ json j = json::parse(data); json variables = j["variables"]; @@ -115,7 +115,7 @@ std::vector DataProcessorJson::processData(std::string data, properties: std::vector dataOptions(numOptions, nullptr); for(int option : selectedOptions){ - dataOptions[option] = new float[_dimensions.x*_dimensions.y]{0.0f}; + dataOptions[option] = new float[dimensions.x*dimensions.y]{0.0f}; json row = variables[options[option].description]; rowsize = row.size(); diff --git a/modules/iswa/util/dataprocessorjson.h b/modules/iswa/util/dataprocessorjson.h index b6213cd7d4..2516bea159 100644 --- a/modules/iswa/util/dataprocessorjson.h +++ b/modules/iswa/util/dataprocessorjson.h @@ -33,9 +33,9 @@ public: DataProcessorJson(); ~DataProcessorJson(); - virtual std::vector readMetadata(std::string data) override; + virtual std::vector readMetadata(std::string data, glm::size3_t& dimensions) override; virtual void addDataValues(std::string data, properties::SelectionProperty& dataOptions) override; - virtual std::vector processData(std::string data, properties::SelectionProperty& dataOptions) override; + virtual std::vector processData(std::string data, properties::SelectionProperty& dataOptions, glm::size3_t& dimensions) override; }; }// namespace diff --git a/modules/iswa/util/dataprocessorkameleon.cpp b/modules/iswa/util/dataprocessorkameleon.cpp index 085eb196c3..5abba4833b 100644 --- a/modules/iswa/util/dataprocessorkameleon.cpp +++ b/modules/iswa/util/dataprocessorkameleon.cpp @@ -22,7 +22,7 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include -#include +//#include #include namespace { @@ -42,7 +42,7 @@ DataProcessorKameleon::DataProcessorKameleon() DataProcessorKameleon::~DataProcessorKameleon(){} -std::vector DataProcessorKameleon::readMetadata(std::string path){ +std::vector DataProcessorKameleon::readMetadata(std::string path, glm::size3_t& dimensions){ if(!path.empty()){ if(path != _kwPath || !_kw){ @@ -98,13 +98,13 @@ void DataProcessorKameleon::addDataValues(std::string path, properties::Selectio add(optionValues, sum); } } -std::vector DataProcessorKameleon::processData(std::string path, properties::SelectionProperty& dataOptions, float slice, glm::size3_t& dimensions){ +std::vector DataProcessorKameleon::processData(std::string path, properties::SelectionProperty& dataOptions, glm::size3_t& dimensions, float slice){ _slice = slice; - _dimensions = dimensions; - return processData(path, dataOptions); + // _dimensions = dimensions; + return processData(path, dataOptions, dimensions); } -std::vector DataProcessorKameleon::processData(std::string path, properties::SelectionProperty& dataOptions){ +std::vector DataProcessorKameleon::processData(std::string path, properties::SelectionProperty& dataOptions, glm::size3_t& dimensions){ int numOptions = dataOptions.options().size(); if(!path.empty()){ @@ -117,13 +117,13 @@ std::vector DataProcessorKameleon::processData(std::string path, propert auto options = dataOptions.options(); int numOptions = options.size(); - int numValues = _dimensions.x*_dimensions.y*_dimensions.z; + int numValues = dimensions.x*dimensions.y*dimensions.z; float value; std::vector dataOptions(numOptions, nullptr); for(int option : selectedOptions){ - dataOptions[option] = _kw->getUniformSliceValues(options[option].description, _dimensions, _slice); + dataOptions[option] = _kw->getUniformSliceValues(options[option].description, dimensions, _slice); for(int i=0; i readMetadata(std::string path) override; + virtual std::vector readMetadata(std::string path, glm::size3_t& dimensions) override; virtual void addDataValues(std::string data, properties::SelectionProperty& dataOptions) override; - virtual std::vector processData(std::string path, properties::SelectionProperty& dataOptions) override; - virtual std::vector processData(std::string path, properties::SelectionProperty& dataOptions, float slice, glm::size3_t& dimensions); + virtual std::vector processData(std::string path, properties::SelectionProperty& dataOptions, glm::size3_t& dimensions) override; + virtual std::vector processData(std::string path, properties::SelectionProperty& dataOptions, glm::size3_t& dimensions, float slice); void dimensions(glm::size3_t dimensions){_dimensions = dimensions;} private: diff --git a/modules/iswa/util/dataprocessortext.cpp b/modules/iswa/util/dataprocessortext.cpp index 4f27d31229..ecdb1ac4d0 100644 --- a/modules/iswa/util/dataprocessortext.cpp +++ b/modules/iswa/util/dataprocessortext.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 * @@ -22,8 +22,14 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include -#include -#include +//#include +//#include +// +//#include +//#include +//#include +//#include +//#include namespace { const std::string _loggerCat = "DataProcessorText"; @@ -37,7 +43,7 @@ DataProcessorText::DataProcessorText() DataProcessorText::~DataProcessorText(){} -std::vector DataProcessorText::readMetadata(std::string data){ +std::vector DataProcessorText::readMetadata(std::string data, glm::size3_t& dimensions){ //The intresting part of the file looks like this: //# Output data: field with 61x61=3721 elements //# x y z N V_x B_x @@ -60,7 +66,7 @@ std::vector DataProcessorText::readMetadata(std::string data){ getline(ss, token, '='); int y = std::stoi(token); - _dimensions = glm::size3_t(x, y, 1); + dimensions = glm::size3_t(x, y, 1); getline(memorystream, line); line = line.substr(1); //because of the # char @@ -74,6 +80,7 @@ std::vector DataProcessorText::readMetadata(std::string data){ } } } + return options; } @@ -91,21 +98,38 @@ void DataProcessorText::addDataValues(std::string data, properties::SelectionPro std::vector values; float value; + int first, last, option, lineSize; + + + // for each data point while(getline(memorystream, line)){ if(line.find("#") == 0) continue; - values = std::vector(); - std::stringstream ss(line); - copy( - std::istream_iterator (ss), - std::istream_iterator (), - back_inserter(values) - ); + std::istringstream ss(line); + std::string val; + int skip = 0; + //for each data option (variable) + while(ss >> val){ + // first three values are coordinates + if( skip < 3 ){ + skip++; + continue; + } + + float v = std::stof(val); + // Some values are "NaN", use 0 instead + if(!std::isnan(v)){ + values.push_back(v); + } else { + values.push_back(0.0f); + } + val.clear(); + } if(values.size() <= 0) continue; for(int i=0; i DataProcessorText::processData(std::string data, properties::SelectionProperty& dataOptions){ +std::vector DataProcessorText::processData(std::string data, properties::SelectionProperty& dataOptions, glm::size3_t& dimensions){ if(!data.empty()){ + std::string line; std::stringstream memorystream(data); @@ -130,31 +155,70 @@ std::vector DataProcessorText::processData(std::string data, properties: std::vector values; float value; + int first, last, option, lineSize; + std::vector dataOptions(numOptions, nullptr); - for(int option : selectedOptions){ - dataOptions[option] = new float[_dimensions.x*_dimensions.y]{0.0f}; + for (int option : selectedOptions) { + dataOptions[option] = new float[dimensions.x*dimensions.y]{0.0f}; } int numValues = 0; - while(getline(memorystream, line)){ - if(line.find("#") == 0) continue; + while (getline(memorystream, line)) { + if (line.find("#") == 0) continue; - values = std::vector(); - std::stringstream ss(line); - copy( - std::istream_iterator (ss), - std::istream_iterator (), - back_inserter(values) - ); + + // ----------- OLD METHODS ------------------------ + // values = std::vector(); + // std::stringstream ss(line); + // float v; + // while(ss >> v){ + // values.push_back(v); + // } - for(int option : selectedOptions){ - value = values[option+3]; //+3 because options x, y and z in the file - dataOptions[option][numValues] = processDataPoint(value, option); + // copy( + // std::istream_iterator (ss), + // std::istream_iterator (), + // back_inserter(values) + // ); + + // copy( + // std::next( std::istream_iterator (ss), 3 ), //+3 because options x, y and z in the file + // std::istream_iterator (), + // back_inserter(values) + // ); + + // for(int option : selectedOptions){ + // value = values[option]; + // //value = values[option+3]; //+3 because options x, y and z in the file + // dataOptions[option][numValues] = processDataPoint(value, option); + // } + // ----------- OLD METHODS ------------------------ + + first = 0; + last = 0; + option = -3; + lineSize = line.size(); + + while(last < lineSize){ + + first = line.find_first_not_of(" \t", last); + last = line.find_first_of(" \t", first); + last = (last > 0)? last : lineSize; + + if(option >= 0 && std::find(selectedOptions.begin(), selectedOptions.end(), option) != selectedOptions.end()){ + // boost::spirit::qi::parse(&line[first], &line[last], boost::spirit::qi::float_, value); + value = std::stof(line.substr(first, last)); + dataOptions[option][numValues] = processDataPoint(value, option); + } + + option++; } + numValues++; } calculateFilterValues(selectedOptions); + return dataOptions; } return std::vector(); diff --git a/modules/iswa/util/dataprocessortext.h b/modules/iswa/util/dataprocessortext.h index 17f87e0bb9..ac575a0f70 100644 --- a/modules/iswa/util/dataprocessortext.h +++ b/modules/iswa/util/dataprocessortext.h @@ -33,9 +33,9 @@ public: DataProcessorText(); ~DataProcessorText(); - virtual std::vector readMetadata(std::string data) override; + virtual std::vector readMetadata(std::string data, glm::size3_t& dimensions) override; virtual void addDataValues(std::string data, properties::SelectionProperty& dataOptions) override; - virtual std::vector processData(std::string data, properties::SelectionProperty& dataOptions) override; + virtual std::vector processData(std::string data, properties::SelectionProperty& dataOptions, glm::size3_t& dimensions) override; private: // void initialize(int numOptions); diff --git a/modules/iswa/util/iswamanager.cpp b/modules/iswa/util/iswamanager.cpp index 3dec502c8f..2b0728698b 100644 --- a/modules/iswa/util/iswamanager.cpp +++ b/modules/iswa/util/iswamanager.cpp @@ -40,7 +40,7 @@ #include #include #include -#include +#include #include #include #include @@ -51,6 +51,8 @@ namespace { using json = nlohmann::json; const std::string _loggerCat = "IswaManager"; + std::string baseUrl = "https://iswa-demo-server.herokuapp.com/"; + //const std::string baseUrl = "http://128.183.168.116:3000/"; } namespace openspace{ @@ -82,7 +84,7 @@ IswaManager::IswaManager() _geom[CygnetGeometry::Plane] = "Plane"; _geom[CygnetGeometry::Sphere] = "Sphere"; - DlManager.fetchFile( + OsEng.downloadManager().fetchFile( "http://iswa3.ccmc.gsfc.nasa.gov/IswaSystemWebApp/CygnetHealthServlet", [this](const DownloadManager::MemoryFile& file){ fillCygnetInfo(std::string(file.buffer)); @@ -144,9 +146,8 @@ void IswaManager::addIswaCygnet(int id, std::string type, std::string group){ }; // Download metadata - DlManager.fetchFile( - "http://128.183.168.116:3000/" + std::to_string(-id), - // "http://localhost:3000/" + std::to_string(-id), + OsEng.downloadManager().fetchFile( + baseUrl + std::to_string(-id), metadataCallback, [id](const std::string& err){ LDEBUG("Download to memory was aborted for data cygnet with id "+ std::to_string(id)+": " + err); @@ -157,7 +158,6 @@ void IswaManager::addIswaCygnet(int id, std::string type, std::string group){ void IswaManager::addKameleonCdf(std::string groupName, int pos){ // auto info = _cdfInformation[group][pos]; - // std::cout << group << " " << pos << std::endl; auto group = iswaGroup(groupName); if(group){ std::dynamic_pointer_cast(group)->changeCdf(_cdfInformation[groupName][pos].path); @@ -169,9 +169,9 @@ void IswaManager::addKameleonCdf(std::string groupName, int pos){ createKameleonPlane(_cdfInformation[groupName][pos], "x"); } -std::future IswaManager::fetchImageCygnet(int id){ - return std::move( DlManager.fetchFile( - iswaUrl(id, "image"), +std::future IswaManager::fetchImageCygnet(int id, double timestamp){ + return std::move(OsEng.downloadManager().fetchFile( + iswaUrl(id, timestamp, "image"), [id](const DownloadManager::MemoryFile& file){ LDEBUG("Download to memory finished for image cygnet with id: " + std::to_string(id)); }, @@ -181,9 +181,9 @@ std::future IswaManager::fetchImageCygnet(int id){ ) ); } -std::future IswaManager::fetchDataCygnet(int id){ - return std::move( DlManager.fetchFile( - iswaUrl(id, "data"), +std::future IswaManager::fetchDataCygnet(int id, double timestamp){ + return std::move(OsEng.downloadManager().fetchFile( + iswaUrl(id, timestamp, "data"), [id](const DownloadManager::MemoryFile& file){ LDEBUG("Download to memory finished for data cygnet with id: " + std::to_string(id)); }, @@ -193,16 +193,16 @@ std::future IswaManager::fetchDataCygnet(int id){ ) ); } -std::string IswaManager::iswaUrl(int id, std::string type){ +std::string IswaManager::iswaUrl(int id, double timestamp, std::string type){ std::string url; if(id < 0){ - url = "http://128.183.168.116:3000/"+type+"/" + std::to_string(-id) + "/"; - // url = "http://localhost:3000/"+type+"/" + std::to_string(-id) + "/"; + url = baseUrl+type+"/" + std::to_string(-id) + "/"; } else{ url = "http://iswa3.ccmc.gsfc.nasa.gov/IswaSystemWebApp/iSWACygnetStreamer?window=-1&cygnetId="+ std::to_string(id) +"×tamp="; } - std::string t = Time::ref().currentTimeUTC(); + //std::string t = Time::ref().currentTimeUTC(); + std::string t = SpiceManager::ref().dateFromEphemerisTime(timestamp); std::stringstream ss(t); std::string token; @@ -261,9 +261,8 @@ std::shared_ptr IswaManager::downloadMetadata(int id){ std::shared_ptr metaFuture = std::make_shared(); metaFuture->id = id; - DlManager.fetchFile( - "http://128.183.168.116:3000/" + std::to_string(-id), - // "http://localhost:3000/" + std::to_string(-id), + OsEng.downloadManager().fetchFile( + baseUrl + std::to_string(-id), [&metaFuture](const DownloadManager::MemoryFile& file){ metaFuture->json = std::string(file.buffer, file.size); metaFuture->isFinished = true; @@ -305,6 +304,13 @@ std::string IswaManager::jsonPlaneToLuaTable(std::shared_ptr dat spatialScale.w = 6; } + float xOffset = 0.0f; + if(data->id == -7) + xOffset = -10.0f; + if(data->id == -8) + xOffset = -20.0f; + if(data->id == -9) + xOffset = -30.0f; std::string table = "{" "Name = '" + data->name +"' , " @@ -319,6 +325,7 @@ std::string IswaManager::jsonPlaneToLuaTable(std::shared_ptr dat "UpdateTime = " + std::to_string(updateTime) + ", " "CoordinateType = '" + coordinateType + "', " "Group = '"+ data->group + "'," + "XOffset = "+ std::to_string(xOffset) + "," "}" "}"; @@ -393,7 +400,7 @@ std::string IswaManager::jsonSphereToLuaTable(std::shared_ptr da parent[0] = toupper(parent[0]); std::string frame = j["standard_grid_target"]; std::string coordinateType = j["grid_1_type"]; - std::string updateTime = j["output_time_interval"]; + float updateTime = j["output_time_interval"]; float radius = j["radius"]; glm::vec4 spatialScale(6.371f, 6.371f, 6.371f, 6); @@ -419,7 +426,7 @@ std::string IswaManager::jsonSphereToLuaTable(std::shared_ptr da "Frame = '" + frame + "' , " "GridMin = " + std::to_string(min) + ", " "GridMax = " + std::to_string(max) + ", " - "UpdateTime = " + updateTime + ", " + "UpdateTime = " + std::to_string(updateTime) + ", " "Radius = " + std::to_string(radius) + ", " "CoordinateType = '" + coordinateType + "', " "Group = '"+ data->group + "'," @@ -640,6 +647,11 @@ void IswaManager::addCdfFiles(std::string path){ } } +void IswaManager::setBaseUrl(std::string bUrl){ + LDEBUG("Swapped baseurl to: " + bUrl); + baseUrl = bUrl; +} + scripting::ScriptEngine::LuaLibrary IswaManager::luaLibrary() { return { "iswa", @@ -699,6 +711,13 @@ scripting::ScriptEngine::LuaLibrary IswaManager::luaLibrary() { "int", "Remove a group of Cygnets", true + }, + { + "setBaseUrl", + &luascriptfunctions::iswa_setBaseUrl, + "string", + "sets the base url", + true } } }; diff --git a/modules/iswa/util/iswamanager.h b/modules/iswa/util/iswamanager.h index 7707fa4a14..bab50f2deb 100644 --- a/modules/iswa/util/iswamanager.h +++ b/modules/iswa/util/iswamanager.h @@ -42,9 +42,7 @@ #include #include #include - -// #include -// #include +#include namespace openspace { @@ -91,9 +89,9 @@ public: void addKameleonCdf(std::string group, int pos); void createFieldline(std::string name, std::string cdfPath, std::string seedPath); - std::future fetchImageCygnet(int id); - std::future fetchDataCygnet(int id); - std::string iswaUrl(int id, std::string type = "image"); + std::future fetchImageCygnet(int id, double timestamp); + std::future fetchDataCygnet(int id, double timestamp); + std::string iswaUrl(int id, double timestamp = Time::ref().currentTime(), std::string type = "image"); std::shared_ptr iswaGroup(std::string name); @@ -108,6 +106,7 @@ public: } void addCdfFiles(std::string path); + void setBaseUrl(std::string bUrl); private: std::shared_ptr downloadMetadata(int id); std::string jsonPlaneToLuaTable(std::shared_ptr data); diff --git a/modules/iswa/util/iswamanager_lua.inl b/modules/iswa/util/iswamanager_lua.inl index 8e44701ca5..703a053ba0 100644 --- a/modules/iswa/util/iswamanager_lua.inl +++ b/modules/iswa/util/iswamanager_lua.inl @@ -140,13 +140,13 @@ int iswa_removeScrenSpaceCygnet(lua_State* L){ int iswa_removeGroup(lua_State* L){ std::string name = luaL_checkstring(L, -1); - // IswaManager::ref().unregisterGroup(id); + // IswaManager::ref().unregisterGroup(id); auto groups = IswaManager::ref().groups(); if(groups.find(name) != groups.end()) groups[name]->clearGroup(); - return 0; + return 0; } int iswa_addCdfFiles(lua_State* L){ @@ -164,6 +164,12 @@ int iswa_addKameleonPlanes(lua_State* L){ return 0; } +int iswa_setBaseUrl(lua_State* L){ + std::string url = luaL_checkstring(L, 1); + IswaManager::ref().setBaseUrl(url); + return 0; +} + }// namespace luascriptfunctions }// namespace openspace \ No newline at end of file diff --git a/modules/kameleon/ext/kameleon b/modules/kameleon/ext/kameleon index f9ba0caae4..3de739a553 160000 --- a/modules/kameleon/ext/kameleon +++ b/modules/kameleon/ext/kameleon @@ -1 +1 @@ -Subproject commit f9ba0caae41dc13a752c71a2e873c02bb0dce7c3 +Subproject commit 3de739a55387051fb6fdfd327ad761dffa317420 diff --git a/modules/kameleon/src/kameleonwrapper.cpp b/modules/kameleon/src/kameleonwrapper.cpp index b9f0423075..3a08b6c153 100644 --- a/modules/kameleon/src/kameleonwrapper.cpp +++ b/modules/kameleon/src/kameleonwrapper.cpp @@ -464,12 +464,12 @@ float* KameleonWrapper::getUniformSliceValues( if(value != missingValue){ doubleData[index] = value; data[index] = value; - if(value > maxValue){ - maxValue = value; - } - if(value < minValue){ - minValue = value; - } + // if(value > maxValue){ + // maxValue = value; + // } + // if(value < minValue){ + // minValue = value; + // } }else{ // std::cout << "value missing" << std::endl; doubleData[index] = 0; diff --git a/modules/multiresvolume/include.cmake b/modules/multiresvolume/include.cmake index 3ccace7c97..e69de29bb2 100644 --- a/modules/multiresvolume/include.cmake +++ b/modules/multiresvolume/include.cmake @@ -1 +0,0 @@ -set (DEFAULT_MODULE ON) diff --git a/modules/newhorizons/rendering/renderablemodelprojection.cpp b/modules/newhorizons/rendering/renderablemodelprojection.cpp index d43e9b8a31..477e2b62ca 100644 --- a/modules/newhorizons/rendering/renderablemodelprojection.cpp +++ b/modules/newhorizons/rendering/renderablemodelprojection.cpp @@ -24,6 +24,7 @@ #include +#include #include #include #include @@ -81,8 +82,7 @@ RenderableModelProjection::RenderableModelProjection(const ghoul::Dictionary& di _defaultProjImage = absPath(texturePath); addPropertySubOwner(_geometry.get()); - - addProperty(_projectionFading); + addPropertySubOwner(_projectionComponent); addProperty(_colorTexturePath); _colorTexturePath.onChange(std::bind(&RenderableModelProjection::loadTextures, this)); @@ -94,17 +94,15 @@ RenderableModelProjection::RenderableModelProjection(const ghoul::Dictionary& di setBody(_target); bool completeSuccess = true; - completeSuccess &= initializeProjectionSettings(dictionary); + completeSuccess &= _projectionComponent.initializeProjectionSettings(dictionary); openspace::SpiceManager::ref().addFrame(_target, _source); setBoundingSphere(pss(1.f, 9.f)); - addProperty(_performShading); - addProperty(_performProjection); - addProperty(_clearAllProjections); - addProperty(_rotation); + Renderable::addProperty(_performShading); + Renderable::addProperty(_rotation); - success = initializeParser(dictionary); + success = _projectionComponent.initializeParser(dictionary); ghoul_assert(success, ""); } @@ -112,7 +110,7 @@ bool RenderableModelProjection::isReady() const { bool ready = true; ready &= (_programObject != nullptr); ready &= (_baseTexture != nullptr); - ready &= (_projectionTexture != nullptr); + ready &= (_projectionComponent.isReady()); return ready; } @@ -134,7 +132,7 @@ bool RenderableModelProjection::initialize() { completeSuccess &= loadTextures(); - completeSuccess &= ProjectionComponent::initialize(); + completeSuccess &= _projectionComponent.initialize(); completeSuccess &= _geometry->initialize(this); completeSuccess &= !_source.empty(); @@ -150,7 +148,7 @@ bool RenderableModelProjection::deinitialize() { _geometry = nullptr; _baseTexture = nullptr; - ProjectionComponent::deinitialize(); + _projectionComponent.deinitialize(); OsEng.renderEngine().removeRenderProgram(_programObject); _programObject = nullptr; @@ -158,13 +156,18 @@ bool RenderableModelProjection::deinitialize() { return true; } +ghoul::opengl::Texture& RenderableModelProjection::baseTexture() const { + return _projectionComponent.projectionTexture(); +} + void RenderableModelProjection::render(const RenderData& data) { - if (_clearAllProjections) - clearAllProjections(); + if (_projectionComponent.needsClearProjection()) + _projectionComponent.clearAllProjections(); _camScaling = data.camera.scaling(); + _up = data.camera.lookUpVectorCameraSpace(); - if (_capture && _performProjection) + if (_capture && _projectionComponent.doesPerformProjection()) project(); _programObject->activate(); @@ -176,7 +179,7 @@ void RenderableModelProjection::render(const RenderData& data) { _programObject->setUniform("sun_pos", _sunPosition.vec3()); _programObject->setUniform("ViewProjection", data.camera.viewProjectionMatrix()); _programObject->setUniform("ModelTransform", _transform); - _programObject->setUniform("_projectionFading", _projectionFading); + _programObject->setUniform("_projectionFading", _projectionComponent.projectionFading()); setPscUniforms(*_programObject, data.camera, data.position); _geometry->setUniforms(*_programObject); @@ -187,7 +190,7 @@ void RenderableModelProjection::render(const RenderData& data) { _programObject->setUniform("baseTexture", unit[0]); unit[1].activate(); - _projectionTexture->bind(); + _projectionComponent.projectionTexture().bind(); _programObject->setUniform("projectionTexture", unit[1]); _geometry->render(); @@ -204,11 +207,15 @@ void RenderableModelProjection::update(const UpdateData& data) { _time = data.time; - if (openspace::ImageSequencer::ref().isReady() && _performProjection) { + if (openspace::ImageSequencer::ref().isReady()) { openspace::ImageSequencer::ref().updateSequencer(_time); - _capture = openspace::ImageSequencer::ref().getImagePaths( - _imageTimes, _projecteeID, _instrumentID - ); + if (_projectionComponent.doesPerformProjection()) { + _capture = openspace::ImageSequencer::ref().getImagePaths( + _imageTimes, + _projectionComponent.projecteeId(), + _projectionComponent.instrumentId() + ); + } } // set spice-orientation in accordance to timestamp @@ -229,7 +236,7 @@ void RenderableModelProjection::update(const UpdateData& data) { void RenderableModelProjection::imageProjectGPU( std::shared_ptr projectionTexture) { - ProjectionComponent::imageProjectBegin(); + _projectionComponent.imageProjectBegin(); _fboProgramObject->activate(); @@ -248,13 +255,13 @@ void RenderableModelProjection::imageProjectGPU( _fboProgramObject->deactivate(); - ProjectionComponent::imageProjectEnd(); + _projectionComponent.imageProjectEnd(); } void RenderableModelProjection::attitudeParameters(double time) { try { _stateMatrix = SpiceManager::ref().positionTransformMatrix(_source, _destination, time); - _instrumentMatrix = SpiceManager::ref().positionTransformMatrix(_instrumentID, _destination, time); + _instrumentMatrix = SpiceManager::ref().positionTransformMatrix(_projectionComponent.instrumentId(), _destination, time); } catch (const SpiceManager::SpiceException& e) { return; @@ -286,7 +293,7 @@ void RenderableModelProjection::attitudeParameters(double time) { glm::dvec3 boresight; try { - SpiceManager::FieldOfViewResult res = SpiceManager::ref().fieldOfView(_instrumentID); + SpiceManager::FieldOfViewResult res = SpiceManager::ref().fieldOfView(_projectionComponent.instrumentId()); boresight = std::move(res.boresightVector); } catch (const SpiceManager::SpiceException& e) { return; @@ -294,21 +301,31 @@ void RenderableModelProjection::attitudeParameters(double time) { double lightTime; glm::dvec3 p = - SpiceManager::ref().targetPosition(_projectorID, _projecteeID, _destination, _aberration, time, lightTime); + SpiceManager::ref().targetPosition( + _projectionComponent.projectorId(), + _projectionComponent.projecteeId(), + _destination, + _projectionComponent.aberration(), + time, lightTime); psc position = PowerScaledCoordinate::CreatePowerScaledCoordinate(p.x, p.y, p.z); position[3] += (3 + _camScaling[1]); glm::vec3 cpos = position.vec3(); - _projectorMatrix = computeProjectorMatrix(cpos, boresight, _up, _instrumentMatrix, - _fovy, _aspectRatio, _nearPlane, _farPlane, _boresight + _projectorMatrix = _projectionComponent.computeProjectorMatrix( + cpos, boresight, _up, _instrumentMatrix, + _projectionComponent.fieldOfViewY(), + _projectionComponent.aspectRatio(), + _projectionComponent.nearPlane(), + _projectionComponent.farPlane(), + _boresight ); } void RenderableModelProjection::project() { for (auto img : _imageTimes) { attitudeParameters(img.startTime); - imageProjectGPU(loadProjectionTexture(img.path)); + imageProjectGPU(_projectionComponent.loadProjectionTexture(img.path)); } _capture = false; } diff --git a/modules/newhorizons/rendering/renderablemodelprojection.h b/modules/newhorizons/rendering/renderablemodelprojection.h index de9508f445..644af7b905 100644 --- a/modules/newhorizons/rendering/renderablemodelprojection.h +++ b/modules/newhorizons/rendering/renderablemodelprojection.h @@ -45,7 +45,7 @@ namespace modelgeometry { class ModelGeometry; } -class RenderableModelProjection : public Renderable, private ProjectionComponent { +class RenderableModelProjection : public Renderable { public: RenderableModelProjection(const ghoul::Dictionary& dictionary); @@ -57,6 +57,8 @@ public: void render(const RenderData& data) override; void update(const UpdateData& data) override; + ghoul::opengl::Texture& baseTexture() const; + private: bool loadTextures(); void attitudeParameters(double time); @@ -64,6 +66,8 @@ private: void project(); + ProjectionComponent _projectionComponent; + properties::StringProperty _colorTexturePath; properties::Vec3Property _rotation; diff --git a/modules/newhorizons/rendering/renderableplanetprojection.cpp b/modules/newhorizons/rendering/renderableplanetprojection.cpp index e95f9eba02..13516f1e5f 100644 --- a/modules/newhorizons/rendering/renderableplanetprojection.cpp +++ b/modules/newhorizons/rendering/renderableplanetprojection.cpp @@ -26,6 +26,7 @@ #include +#include #include #include #include @@ -36,6 +37,11 @@ #include #include +#ifdef WIN32 +#define _USE_MATH_DEFINES +#include +#endif + namespace { const std::string _loggerCat = "RenderablePlanetProjection"; @@ -81,7 +87,7 @@ RenderablePlanetProjection::RenderablePlanetProjection(const ghoul::Dictionary& if (_target != "") setBody(_target); - success = initializeProjectionSettings(dictionary); + success = _projectionComponent.initializeProjectionSettings(dictionary); ghoul_assert(success, ""); // TODO: textures need to be replaced by a good system similar to the geometry as soon @@ -98,8 +104,7 @@ RenderablePlanetProjection::RenderablePlanetProjection(const ghoul::Dictionary& _heightMapTexturePath = absPath(heightMapPath); addPropertySubOwner(_geometry.get()); - addProperty(_performProjection); - addProperty(_clearAllProjections); + addPropertySubOwner(_projectionComponent); addProperty(_colorTexturePath); _colorTexturePath.onChange(std::bind(&RenderablePlanetProjection::loadTextures, this)); @@ -107,11 +112,10 @@ RenderablePlanetProjection::RenderablePlanetProjection(const ghoul::Dictionary& addProperty(_heightMapTexturePath); _heightMapTexturePath.onChange(std::bind(&RenderablePlanetProjection::loadTextures, this)); - addProperty(_projectionFading); addProperty(_heightExaggeration); addProperty(_debugProjectionTextureRotation); - success = initializeParser(dictionary); + success = _projectionComponent.initializeParser(dictionary); ghoul_assert(success, ""); } @@ -131,7 +135,7 @@ bool RenderablePlanetProjection::initialize() { ); completeSuccess &= loadTextures(); - completeSuccess &= ProjectionComponent::initialize(); + completeSuccess &= _projectionComponent.initialize(); completeSuccess &= _geometry->initialize(this); @@ -166,7 +170,7 @@ bool RenderablePlanetProjection::initialize() { } bool RenderablePlanetProjection::deinitialize() { - ProjectionComponent::deinitialize(); + _projectionComponent.deinitialize(); _baseTexture = nullptr; _geometry = nullptr; @@ -181,13 +185,13 @@ bool RenderablePlanetProjection::deinitialize() { return true; } bool RenderablePlanetProjection::isReady() const { - return _geometry && _programObject && _baseTexture && _projectionTexture; + return _geometry && _programObject && _baseTexture && _projectionComponent.isReady(); } void RenderablePlanetProjection::imageProjectGPU( std::shared_ptr projectionTexture) { - imageProjectBegin(); + _projectionComponent.imageProjectBegin(); _fboProgramObject->activate(); @@ -222,14 +226,14 @@ void RenderablePlanetProjection::imageProjectGPU( glDrawArrays(GL_TRIANGLES, 0, 6); _fboProgramObject->deactivate(); - imageProjectEnd(); + _projectionComponent.imageProjectEnd(); } void RenderablePlanetProjection::attitudeParameters(double time) { // precomputations for shader _stateMatrix = SpiceManager::ref().positionTransformMatrix(_frame, _mainFrame, time); _instrumentMatrix = SpiceManager::ref().positionTransformMatrix( - _instrumentID, _mainFrame, time + _projectionComponent.instrumentId(), _mainFrame, time ); _transform = glm::mat4(1); @@ -259,7 +263,7 @@ void RenderablePlanetProjection::attitudeParameters(double time) { glm::dvec3 bs; try { - SpiceManager::FieldOfViewResult res = SpiceManager::ref().fieldOfView(_instrumentID); + SpiceManager::FieldOfViewResult res = SpiceManager::ref().fieldOfView(_projectionComponent.instrumentId()); bs = std::move(res.boresightVector); } catch (const SpiceManager::SpiceException& e) { @@ -269,7 +273,12 @@ void RenderablePlanetProjection::attitudeParameters(double time) { double lightTime; glm::dvec3 p = SpiceManager::ref().targetPosition( - _projectorID, _projecteeID, _mainFrame, _aberration, time, lightTime + _projectionComponent.projectorId(), + _projectionComponent.projecteeId(), + _mainFrame, + _projectionComponent.aberration(), + time, + lightTime ); psc position = PowerScaledCoordinate::CreatePowerScaledCoordinate(p.x, p.y, p.z); @@ -278,21 +287,34 @@ void RenderablePlanetProjection::attitudeParameters(double time) { //position[3] += 3; glm::vec3 cpos = position.vec3(); - _projectorMatrix = computeProjectorMatrix(cpos, bs, _up, _instrumentMatrix, - _fovy, _aspectRatio, _nearPlane, _farPlane, _boresight + _projectorMatrix = _projectionComponent.computeProjectorMatrix( + cpos, + bs, + _up, + _instrumentMatrix, + _projectionComponent.fieldOfViewY(), + _projectionComponent.aspectRatio(), + _projectionComponent.nearPlane(), + _projectionComponent.farPlane(), + _boresight ); } +ghoul::opengl::Texture& RenderablePlanetProjection::baseTexture() const { + return _projectionComponent.projectionTexture(); +} + void RenderablePlanetProjection::render(const RenderData& data) { - if (_clearAllProjections) - clearAllProjections(); + if (_projectionComponent.needsClearProjection()) + _projectionComponent.clearAllProjections(); _camScaling = data.camera.scaling(); + _up = data.camera.lookUpVectorCameraSpace(); - if (_capture && _performProjection) { + if (_capture && _projectionComponent.doesPerformProjection()) { for (const Image& img : _imageTimes) { RenderablePlanetProjection::attitudeParameters(img.startTime); - imageProjectGPU(loadProjectionTexture(img.path)); + imageProjectGPU(_projectionComponent.loadProjectionTexture(img.path)); } _capture = false; } @@ -301,7 +323,7 @@ void RenderablePlanetProjection::render(const RenderData& data) { double lt; glm::dvec3 p = - SpiceManager::ref().targetPosition("SUN", _projecteeID, "GALACTIC", {}, _time, lt); + SpiceManager::ref().targetPosition("SUN", _projectionComponent.projecteeId(), "GALACTIC", {}, _time, lt); psc sun_pos = PowerScaledCoordinate::CreatePowerScaledCoordinate(p.x, p.y, p.z); // Main renderpass @@ -312,7 +334,7 @@ void RenderablePlanetProjection::render(const RenderData& data) { _programObject->setUniform("_hasHeightMap", _heightMapTexture != nullptr); _programObject->setUniform("_heightExaggeration", _heightExaggeration); - _programObject->setUniform("_projectionFading", _projectionFading); + _programObject->setUniform("_projectionFading", _projectionComponent.projectionFading()); //_programObject->setUniform("debug_projectionTextureRotation", glm::radians(_debugProjectionTextureRotation.value())); @@ -324,7 +346,7 @@ void RenderablePlanetProjection::render(const RenderData& data) { _programObject->setUniform("baseTexture", unit[0]); unit[1].activate(); - _projectionTexture->bind(); + _projectionComponent.projectionTexture().bind(); _programObject->setUniform("projectionTexture", unit[1]); if (_heightMapTexture) { @@ -348,11 +370,15 @@ void RenderablePlanetProjection::update(const UpdateData& data) { _time = Time::ref().currentTime(); _capture = false; - if (openspace::ImageSequencer::ref().isReady() && _performProjection){ + if (openspace::ImageSequencer::ref().isReady()){ openspace::ImageSequencer::ref().updateSequencer(_time); - _capture = openspace::ImageSequencer::ref().getImagePaths( - _imageTimes, _projecteeID, _instrumentID - ); + if (_projectionComponent.doesPerformProjection()) { + _capture = openspace::ImageSequencer::ref().getImagePaths( + _imageTimes, + _projectionComponent.projecteeId(), + _projectionComponent.instrumentId() + ); + } } } diff --git a/modules/newhorizons/rendering/renderableplanetprojection.h b/modules/newhorizons/rendering/renderableplanetprojection.h index 404b0a452e..b87d8922b2 100644 --- a/modules/newhorizons/rendering/renderableplanetprojection.h +++ b/modules/newhorizons/rendering/renderableplanetprojection.h @@ -43,7 +43,7 @@ namespace planetgeometry { class PlanetGeometry; } -class RenderablePlanetProjection : public Renderable, private ProjectionComponent { +class RenderablePlanetProjection : public Renderable { public: RenderablePlanetProjection(const ghoul::Dictionary& dictionary); ~RenderablePlanetProjection(); @@ -54,7 +54,7 @@ public: void render(const RenderData& data) override; void update(const UpdateData& data) override; - ghoul::opengl::Texture* baseTexture() { return _projectionTexture.get(); }; + ghoul::opengl::Texture& baseTexture() const; protected: bool loadTextures(); @@ -64,6 +64,8 @@ protected: private: void imageProjectGPU(std::shared_ptr projectionTexture); + ProjectionComponent _projectionComponent; + properties::StringProperty _colorTexturePath; properties::StringProperty _heightMapTexturePath; diff --git a/modules/newhorizons/shaders/renderableModelProjection_fs.glsl b/modules/newhorizons/shaders/renderableModelProjection_fs.glsl index 9b3c4975b7..0d0bcbec89 100644 --- a/modules/newhorizons/shaders/renderableModelProjection_fs.glsl +++ b/modules/newhorizons/shaders/renderableModelProjection_fs.glsl @@ -55,8 +55,11 @@ void main() { //invert gl coordinates projected.x = 1 - projected.x; - if((inRange(projected.x, 0, 1) && inRange(projected.y, 0, 1)) && (dot(n, boresight) < 0)) { + if ((inRange(projected.x, 0, 1) && inRange(projected.y, 0, 1)) && (dot(n, boresight) < 0)) { color = texture(projectionTexture, projected.xy); color.a = 1.0; } + else { + color = vec4(vec3(0.0), 1.0); + } } diff --git a/modules/newhorizons/shaders/renderablePlanetProjection_fs.glsl b/modules/newhorizons/shaders/renderablePlanetProjection_fs.glsl index c9772d724a..3f6e2be3ba 100644 --- a/modules/newhorizons/shaders/renderablePlanetProjection_fs.glsl +++ b/modules/newhorizons/shaders/renderablePlanetProjection_fs.glsl @@ -54,8 +54,6 @@ vec4 uvToModel(vec2 uv, vec4 radius, float segments){ float z = radius[2] * cos(phi) * sin(theta); // return vec4(x, y, z, radius[3]); - - return vec4(0.0); } bool inRange(float x, float a, float b){ @@ -85,4 +83,7 @@ void main() { // to be fixed soon ---abock color = texture(projectionTexture, vec2(projected.x, 1-projected.y)); } + else { + color = vec4(0.0); + } } \ No newline at end of file diff --git a/modules/newhorizons/util/projectioncomponent.cpp b/modules/newhorizons/util/projectioncomponent.cpp index 6f9004afa3..56548b1d88 100644 --- a/modules/newhorizons/util/projectioncomponent.cpp +++ b/modules/newhorizons/util/projectioncomponent.cpp @@ -67,11 +67,18 @@ namespace openspace { using ghoul::Dictionary; ProjectionComponent::ProjectionComponent() - : _performProjection("performProjection", "Perform Projections", true) + : properties::PropertyOwner() + , _performProjection("performProjection", "Perform Projections", true) , _clearAllProjections("clearAllProjections", "Clear Projections", false) , _projectionFading("projectionFading", "Projection Fading", 1.f, 0.f, 1.f) , _projectionTexture(nullptr) -{} +{ + setName("ProjectionComponent"); + + addProperty(_performProjection); + addProperty(_clearAllProjections); + addProperty(_projectionFading); +} bool ProjectionComponent::initialize() { bool a = generateProjectionLayerTexture(); @@ -102,6 +109,10 @@ bool ProjectionComponent::deinitialize() { return true; } +bool ProjectionComponent::isReady() const { + return (_projectionTexture != nullptr); +} + bool ProjectionComponent::initializeProjectionSettings(const Dictionary& dictionary) { bool completeSuccess = true; completeSuccess &= dictionary.getValue(keyInstrument, _instrumentID); @@ -277,6 +288,54 @@ glm::mat4 ProjectionComponent::computeProjectorMatrix(const glm::vec3 loc, glm:: return projNormalizationMatrix*projProjectionMatrix*projViewMatrix; } +bool ProjectionComponent::doesPerformProjection() const { + return _performProjection; +} + +bool ProjectionComponent::needsClearProjection() const { + return _clearAllProjections; +} + +float ProjectionComponent::projectionFading() const { + return _projectionFading; +} + +ghoul::opengl::Texture& ProjectionComponent::projectionTexture() const { + return *_projectionTexture; +} + +std::string ProjectionComponent::projectorId() const { + return _projectorID; +} + +std::string ProjectionComponent::projecteeId() const { + return _projecteeID; +} + +std::string ProjectionComponent::instrumentId() const { + return _instrumentID; +} + +SpiceManager::AberrationCorrection ProjectionComponent::aberration() const { + return _aberration; +} + +float ProjectionComponent::fieldOfViewY() const { + return _fovy; +} + +float ProjectionComponent::aspectRatio() const { + return _aspectRatio; +} + +float ProjectionComponent::nearPlane() const { + return _nearPlane; +} + +float ProjectionComponent::farPlane() const { + return _farPlane; +} + void ProjectionComponent::clearAllProjections() { // keep handle to the current bound FBO GLint defaultFBO; diff --git a/modules/newhorizons/util/projectioncomponent.h b/modules/newhorizons/util/projectioncomponent.h index 88ec3c5ce6..197a886dc4 100644 --- a/modules/newhorizons/util/projectioncomponent.h +++ b/modules/newhorizons/util/projectioncomponent.h @@ -25,6 +25,7 @@ #ifndef __PROJECTIONCOMPONENT_H__ #define __PROJECTIONCOMPONENT_H__ +#include #include #include @@ -33,14 +34,15 @@ namespace openspace { -class ProjectionComponent { +class ProjectionComponent : public properties::PropertyOwner { public: ProjectionComponent(); -protected: bool initialize(); bool deinitialize(); + bool isReady() const; + bool initializeProjectionSettings(const ghoul::Dictionary& dictionary); bool initializeParser(const ghoul::Dictionary& dictionary); @@ -65,9 +67,25 @@ protected: glm::vec3& boreSight ); + bool doesPerformProjection() const; + bool needsClearProjection() const; + float projectionFading() const; + void clearAllProjections(); + ghoul::opengl::Texture& projectionTexture() const; + std::string projectorId() const; + std::string projecteeId() const; + std::string instrumentId() const; + SpiceManager::AberrationCorrection aberration() const; + + float fieldOfViewY() const; + float aspectRatio() const; + float nearPlane() const; + float farPlane() const; + +protected: properties::BoolProperty _performProjection; properties::BoolProperty _clearAllProjections; properties::FloatProperty _projectionFading; @@ -86,7 +104,6 @@ protected: float _nearPlane; float _farPlane; - GLuint _fboID; GLint _defaultFBO; diff --git a/modules/onscreengui/CMakeLists.txt b/modules/onscreengui/CMakeLists.txt index 2f57a7264f..2487474370 100644 --- a/modules/onscreengui/CMakeLists.txt +++ b/modules/onscreengui/CMakeLists.txt @@ -39,6 +39,7 @@ source_group("Header Files" FILES ${HEADER_FILES}) set(SOURCE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/src/gui.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/gui_lua.inl ${CMAKE_CURRENT_SOURCE_DIR}/src/guicomponent.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/guihelpcomponent.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/guiorigincomponent.cpp diff --git a/modules/onscreengui/include/gui.h b/modules/onscreengui/include/gui.h index 7bd37b0f85..7f36048b33 100644 --- a/modules/onscreengui/include/gui.h +++ b/modules/onscreengui/include/gui.h @@ -25,6 +25,7 @@ #ifndef __GUI_H__ #define __GUI_H__ +#include #include #include #include @@ -39,14 +40,11 @@ namespace openspace { namespace gui { -class GUI { +class GUI : public GuiComponent { public: GUI(); ~GUI(); - bool isEnabled() const; - void setEnabled(bool enabled); - void initialize(); void deinitialize(); @@ -54,16 +52,14 @@ public: void deinitializeGL(); bool mouseButtonCallback(MouseButton button, MouseAction action); -// bool mouseButtonCallback(int key, int action); bool mouseWheelCallback(double position); bool keyCallback(Key key, KeyModifier modifier, KeyAction action); -// bool keyCallback(int key, int 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 endFrame(); - void renderMainWindow(); + void render(); static openspace::scripting::ScriptEngine::LuaLibrary luaLibrary(); @@ -71,15 +67,11 @@ public: GuiHelpComponent _help; GuiOriginComponent _origin; GuiPerformanceComponent _performance; + GuiPropertyComponent _globalProperty; GuiPropertyComponent _property; - // GuiPropertyComponent _iSWAproperty; GuiPropertyComponent _screenSpaceProperty; GuiTimeComponent _time; GuiIswaComponent _iswa; - - bool _isEnabled; - - bool _showHelp; }; } // namespace gui diff --git a/modules/onscreengui/include/guihelpcomponent.h b/modules/onscreengui/include/guihelpcomponent.h index dcaf9284d8..8f6e82e2c0 100644 --- a/modules/onscreengui/include/guihelpcomponent.h +++ b/modules/onscreengui/include/guihelpcomponent.h @@ -32,7 +32,7 @@ namespace gui { class GuiHelpComponent : public GuiComponent { public: - void render(); + void render() override; }; } // namespace gui diff --git a/modules/onscreengui/include/guiiswacomponent.h b/modules/onscreengui/include/guiiswacomponent.h index 91d7fdef04..a6d831f788 100644 --- a/modules/onscreengui/include/guiiswacomponent.h +++ b/modules/onscreengui/include/guiiswacomponent.h @@ -25,33 +25,27 @@ #ifndef __GUIISWACOMPONENT_H__ #define __GUIISWACOMPONENT_H__ -#include #include +#include + namespace openspace { namespace gui { -struct RadioOption { - int value; - std::string path; - std::string date; -}; - class GuiIswaComponent : public GuiPropertyComponent { public: GuiIswaComponent(); - virtual void render() override; + void render() override; private: - bool _gmdata; - bool _gmimage; - bool _iondata; + bool _gmData; + bool _gmImage; + bool _ionData; std::vector _cdfOptions; std::map _cdfOptionsMap; }; - } // namespace gui } // namespace openspace diff --git a/modules/onscreengui/include/guiorigincomponent.h b/modules/onscreengui/include/guiorigincomponent.h index d3507acaf4..8598b784e4 100644 --- a/modules/onscreengui/include/guiorigincomponent.h +++ b/modules/onscreengui/include/guiorigincomponent.h @@ -28,7 +28,6 @@ #include namespace openspace { - namespace gui { class GuiOriginComponent : public GuiComponent { @@ -36,61 +35,6 @@ public: void render() override; }; -// -//class GuiPropertyComponent : public GuiComponent { -//public: -// //void registerProperty(const std::string& propertyDescription); -// void registerProperty(properties::Property* prop); -// void render(); -// -//protected: -// enum class PropertyType { -// BoolProperty = 0, -// IntProperty, -// FloatProperty, -// Vec2Property, -// Vec3Property, -// StringProperty, -// OptionProperty, -// SelectionProperty, -// TriggerProperty, -// InvalidPropertyType -// }; -// -// struct PropertyInfo { -// PropertyType type; -// std::string identifier; -// std::string name; -// std::string group; -// }; -// typedef std::string PropertyOwner; -// -// struct Property { -// PropertyOwner owner; -// std::vector properties; -// }; -// -// void handleProperty(const ghoul::Dictionary& value); -// -// PropertyType toPropertyType(const std::string& name) const; -// -// void renderProperty(const PropertyInfo& info) const; -// -// std::set _boolProperties; -// std::set _intProperties; -// std::set _floatProperties; -// std::set _vec2Properties; -// std::set _vec3Properties; -// std::set _vec4Properties; -// std::set _stringProperties; -// std::set _optionProperties; -// std::set _selectionProperties; -// std::set _triggerProperties; -// std::map> _propertiesByOwner; -// -// //std::vector _properties; -//}; - } // namespace gui } // namespace openspace diff --git a/modules/onscreengui/include/guiperformancecomponent.h b/modules/onscreengui/include/guiperformancecomponent.h index 882c277fe4..f5beabd38a 100644 --- a/modules/onscreengui/include/guiperformancecomponent.h +++ b/modules/onscreengui/include/guiperformancecomponent.h @@ -27,6 +27,8 @@ #include +#include + namespace ghoul { class SharedMemory; } @@ -36,17 +38,14 @@ namespace gui { class GuiPerformanceComponent : public GuiComponent { public: - void initialize(); - void deinitialize(); - - void render(); + void render() override; protected: - ghoul::SharedMemory* _performanceMemory = nullptr; - int _sortingSelection; + std::unique_ptr _performanceMemory; + int _sortingSelection = -1; - bool _sceneGraphIsEnabled; - bool _functionsIsEnabled; + bool _sceneGraphIsEnabled = false; + bool _functionsIsEnabled = false; }; } // namespace gui diff --git a/modules/onscreengui/include/guipropertycomponent.h b/modules/onscreengui/include/guipropertycomponent.h index a763999fcf..2be19af00a 100644 --- a/modules/onscreengui/include/guipropertycomponent.h +++ b/modules/onscreengui/include/guipropertycomponent.h @@ -27,73 +27,37 @@ #include -#include +#include #include #include -#include namespace openspace { namespace properties { class Property; + class PropertyOwner; } namespace gui { class GuiPropertyComponent : public GuiComponent { public: - //void registerProperty(const std::string& propertyDescription); - void registerProperty(properties::Property* prop, properties::Property* sibling = nullptr); - void unregisterProperty(properties::Property* prop); - void unregisterProperties(std::string owner); + using SourceFunction = std::function()>; + + GuiPropertyComponent(std::string name); + + // This is the function that evaluates to the list of Propertyowners that this + // component should render + void setSource(SourceFunction func); + void render(); protected: - enum class PropertyType { - BoolProperty = 0, - IntProperty, - FloatProperty, - Vec2Property, - Vec3Property, - StringProperty, - OptionProperty, - SelectionProperty, - TriggerProperty, - InvalidPropertyType - }; + void renderPropertyOwner(properties::PropertyOwner* owner); + void renderProperty(properties::Property* prop, properties::PropertyOwner* owner); - struct PropertyInfo { - PropertyType type; - std::string identifier; - std::string name; - std::string group; - }; - typedef std::string PropertyOwner; - - struct Property { - PropertyOwner owner; - std::vector properties; - }; - - void handleProperty(const ghoul::Dictionary& value); - - PropertyType toPropertyType(const std::string& name) const; - - void renderProperty(const PropertyInfo& info) const; - - std::set _boolProperties; - std::set _intProperties; - std::set _floatProperties; - std::set _vec2Properties; - std::set _vec3Properties; - std::set _vec4Properties; - std::set _stringProperties; - std::set _optionProperties; - std::set _selectionProperties; - std::set _triggerProperties; - std::map> _propertiesByOwner; - - //std::vector _properties; + std::string _name; + SourceFunction _function; }; } // namespace gui diff --git a/modules/onscreengui/include/guitimecomponent.h b/modules/onscreengui/include/guitimecomponent.h index 4d6f5d1f4e..dcdb9f78ab 100644 --- a/modules/onscreengui/include/guitimecomponent.h +++ b/modules/onscreengui/include/guitimecomponent.h @@ -28,7 +28,6 @@ #include namespace openspace { - namespace gui { class GuiTimeComponent : public GuiComponent { @@ -36,61 +35,6 @@ public: void render() override; }; -// -//class GuiPropertyComponent : public GuiComponent { -//public: -// //void registerProperty(const std::string& propertyDescription); -// void registerProperty(properties::Property* prop); -// void render(); -// -//protected: -// enum class PropertyType { -// BoolProperty = 0, -// IntProperty, -// FloatProperty, -// Vec2Property, -// Vec3Property, -// StringProperty, -// OptionProperty, -// SelectionProperty, -// TriggerProperty, -// InvalidPropertyType -// }; -// -// struct PropertyInfo { -// PropertyType type; -// std::string identifier; -// std::string name; -// std::string group; -// }; -// typedef std::string PropertyOwner; -// -// struct Property { -// PropertyOwner owner; -// std::vector properties; -// }; -// -// void handleProperty(const ghoul::Dictionary& value); -// -// PropertyType toPropertyType(const std::string& name) const; -// -// void renderProperty(const PropertyInfo& info) const; -// -// std::set _boolProperties; -// std::set _intProperties; -// std::set _floatProperties; -// std::set _vec2Properties; -// std::set _vec3Properties; -// std::set _vec4Properties; -// std::set _stringProperties; -// std::set _optionProperties; -// std::set _selectionProperties; -// std::set _triggerProperties; -// std::map> _propertiesByOwner; -// -// //std::vector _properties; -//}; - } // namespace gui } // namespace openspace diff --git a/modules/onscreengui/include/renderproperties.h b/modules/onscreengui/include/renderproperties.h index 6148c36046..d54087bb95 100644 --- a/modules/onscreengui/include/renderproperties.h +++ b/modules/onscreengui/include/renderproperties.h @@ -25,22 +25,26 @@ #ifndef __RENDERPROPERTIES_H__ #define __RENDERPROPERTIES_H__ -#include -#include +#include +namespace openspace { -using namespace openspace::properties; +namespace properties { + class Property; +} void executeScript(const std::string& id, const std::string& value); -void renderBoolProperty(Property* prop, const std::string& ownerName); -void renderOptionProperty(Property* prop, const std::string& ownerName); -void renderSelectionProperty(Property* prop, const std::string& ownerName); -void renderStringProperty(Property* prop, const std::string& ownerName); -void renderIntProperty(Property* prop, const std::string& ownerName); -void renderFloatProperty(Property* prop, const std::string& ownerName); -void renderVec2Property(Property* prop, const std::string& ownerName); -void renderVec3Property(Property* prop, const std::string& ownerName); -void renderVec4Property(Property* prop, const std::string& ownerName); -void renderTriggerProperty(Property* prop, const std::string& ownerName); +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 renderIntProperty(properties::Property* prop, const std::string& ownerName); +void renderFloatProperty(properties::Property* prop, const std::string& ownerName); +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 renderTriggerProperty(properties::Property* prop, const std::string& ownerName); -#endif __RENDERPROPERTIES_H__ \ No newline at end of file +} // namespace openspace + +#endif __RENDERPROPERTIES_H__ diff --git a/modules/onscreengui/shaders/gui_vs.glsl b/modules/onscreengui/shaders/gui_vs.glsl index 1a4a2d8e23..1b3b67d860 100644 --- a/modules/onscreengui/shaders/gui_vs.glsl +++ b/modules/onscreengui/shaders/gui_vs.glsl @@ -24,8 +24,6 @@ #version __CONTEXT__ -uniform mat4 ortho; - in vec2 in_position; in vec2 in_uv; in vec4 in_color; @@ -33,8 +31,10 @@ in vec4 in_color; out vec2 out_uv; out vec4 out_color; +uniform mat4 ortho; + void main() { out_uv = in_uv; out_color = in_color; gl_Position = ortho * vec4(in_position.xy, 0.0, 1.0); -} \ No newline at end of file +} diff --git a/modules/onscreengui/src/gui.cpp b/modules/onscreengui/src/gui.cpp index 4353468086..ae57b6d9b5 100644 --- a/modules/onscreengui/src/gui.cpp +++ b/modules/onscreengui/src/gui.cpp @@ -24,164 +24,171 @@ #include -#include - +#include +#include #include - -#include -#include #include -#include -#include -#include -#include -// #include - +#include #include #include +#include #include #include +#include "gui_lua.inl" + +//#define SHOW_IMGUI_HELPERS + namespace { - const std::string _loggerCat = "GUI"; - const std::string configurationFile = "imgui.ini"; - const ImVec2 size = ImVec2(350, 500); - GLuint fontTex = 0; - GLint positionLocation = 0; - GLint uvLocation = 0; - GLint colorLocation = 0; - size_t vboMaxSize = 20000; - GLuint vao = 0; - GLuint vbo = 0; - std::unique_ptr _program; +const std::string _loggerCat = "GUI"; +const std::string configurationFile = "imgui.ini"; +const std::string GuiFont = "${FONTS}/Roboto/Roboto-Regular.ttf"; +const ImVec2 size = ImVec2(350, 500); - static void ImImpl_RenderDrawLists(ImDrawList** const commandLists, int nCommandLists) { - if (nCommandLists == 0) - return; +//GLuint fontTex = 0; +// A VBO max size of 0 will cause a lazy instantiation of the buffer +size_t vboMaxSize = 0; +GLuint vao = 0; +GLuint vbo = 0; +std::unique_ptr _program; +std::unique_ptr _fontTexture; +char* iniFileBuffer = nullptr; - // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled - glEnable(GL_BLEND); - glBlendEquation(GL_FUNC_ADD); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDisable(GL_CULL_FACE); - glDisable(GL_DEPTH_TEST); - glEnable(GL_SCISSOR_TEST); +static void RenderDrawLists(ImDrawList** const commandLists, int nCommandLists) { + if (nCommandLists == 0) + return; - ghoul::opengl::TextureUnit unit; - unit.activate(); - glBindTexture(GL_TEXTURE_2D, fontTex); + // Setup render state: + // alpha-blending enabled, no face culling, no depth testing, scissor enabled + glEnable(GL_BLEND); + glBlendEquation(GL_FUNC_ADD); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDisable(GL_CULL_FACE); + glDisable(GL_DEPTH_TEST); + glEnable(GL_SCISSOR_TEST); - // Setup orthographic projection matrix - const float width = ImGui::GetIO().DisplaySize.x; - const float height = ImGui::GetIO().DisplaySize.y; - const glm::mat4 ortho( - 2.f / width, 0.0f, 0.0f, 0.0f, - 0.0f, 2.0f / -height, 0.0f, 0.0f, - 0.0f, 0.0f, -1.0f, 0.0f, - -1.0f, 1.0f, 0.0f, 1.0f - ); - _program->activate(); - _program->setUniform("tex", unit); - _program->setUniform("ortho", ortho); + ghoul::opengl::TextureUnit unit; + unit.activate(); + _fontTexture->bind(); - // Grow our buffer according to what we need - size_t total_vtx_count = 0; - for (int n = 0; n < nCommandLists; n++) - total_vtx_count += commandLists[n]->vtx_buffer.size(); - glBindBuffer(GL_ARRAY_BUFFER, vbo); - // @BUGFIX @HACK The imgui crashes on complex scenes without the * 2 ---abock - size_t neededBufferSize = total_vtx_count * sizeof(ImDrawVert) * 2; - if (neededBufferSize > vboMaxSize) { - vboMaxSize = neededBufferSize + 5000; // Grow buffer - glBufferData(GL_ARRAY_BUFFER, neededBufferSize, NULL, GL_STREAM_DRAW); - } + // Setup orthographic projection matrix + const float width = ImGui::GetIO().DisplaySize.x; + const float height = ImGui::GetIO().DisplaySize.y; + const glm::mat4 ortho( + 2.f / width, 0.0f, 0.0f, 0.f, + 0.0f, 2.0f / -height, 0.0f, 0.f, + 0.0f, 0.0f, -1.0f, 0.0f, + -1.0f, 1.0f, 0.0f, 1.0f + ); + _program->activate(); - // Copy and convert all vertices into a single contiguous buffer - unsigned char* buffer_data = (unsigned char*)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); - if (!buffer_data) - return; - for (int n = 0; n < nCommandLists; ++n) { - const ImDrawList* cmd_list = commandLists[n]; - memcpy(buffer_data, &cmd_list->vtx_buffer[0], cmd_list->vtx_buffer.size() * sizeof(ImDrawVert)); - buffer_data += cmd_list->vtx_buffer.size() * sizeof(ImDrawVert); - } - glUnmapBuffer(GL_ARRAY_BUFFER); - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(vao); + _program->setUniform("tex", unit); + _program->setUniform("ortho", ortho); - int cmd_offset = 0; - for (int n = 0; n < nCommandLists; ++n) { - const ImDrawList* cmd_list = commandLists[n]; - int vtx_offset = cmd_offset; - for (auto pcmd : cmd_list->commands) { - glScissor((int)pcmd.clip_rect.x, (int)(height - pcmd.clip_rect.w), (int)(pcmd.clip_rect.z - pcmd.clip_rect.x), (int)(pcmd.clip_rect.w - pcmd.clip_rect.y)); - glDrawArrays(GL_TRIANGLES, vtx_offset, pcmd.vtx_count); - vtx_offset += pcmd.vtx_count; - } - cmd_offset = vtx_offset; - } + // 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(); - glBindVertexArray(0); - _program->deactivate(); - glDisable(GL_SCISSOR_TEST); - glBindTexture(GL_TEXTURE_2D, 0); + 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); } -namespace openspace { - void addScreenSpaceRenderable(std::string texturePath){ - std::string filepath ="${OPENSPACE_DATA}/"+texturePath; - if( ! FileSys.fileExists(filepath)) { - LWARNING("Could not find image '" << filepath << "'"); - return; - } - std::string luaTable = "{Type = 'ScreenSpaceImage', TexturePath = '+" + filepath + " ' }"; - std::string script = "openspace.registerScreenSpaceRenderable(" + luaTable + ");"; - OsEng.scriptEngine().queueScript(script); - // OsEng.renderEngine().registerScreenSpaceRenderable(std::make_shared(filepath)); - } +void addScreenSpaceRenderable(std::string texturePath) { + if (!FileSys.fileExists(texturePath)) { + LWARNING("Could not find image '" << texturePath << "'"); + return; + } + std::string luaTable = + "{Type = 'ScreenSpaceImage', TexturePath = '+" + absPath(texturePath) + " ' }"; + std::string script = "openspace.registerScreenSpaceRenderable(" + luaTable + ");"; + OsEng.scriptEngine().queueScript(script); +} +} // namespace + +namespace openspace { namespace gui { GUI::GUI() - : _isEnabled(false) - , _showHelp(false) -{ -} + : GuiComponent() + , _globalProperty("Global") + , _property("Properties") + , _screenSpaceProperty("ScreenSpace Properties") +{} GUI::~GUI() { ImGui::Shutdown(); } -bool GUI::isEnabled() const { - return _isEnabled; -} - -void GUI::setEnabled(bool enabled) { - _isEnabled = enabled; -} - void GUI::initialize() { std::string cachedFile = FileSys.cacheManager()->cachedFilename( configurationFile, "", ghoul::filesystem::CacheManager::Persistent::Yes ); - char* buffer = new char[cachedFile.size() + 1]; + iniFileBuffer = new char[cachedFile.size() + 1]; #ifdef WIN32 - strcpy_s(buffer, cachedFile.size() + 1, cachedFile.c_str()); + strcpy_s(iniFileBuffer, cachedFile.size() + 1, cachedFile.c_str()); #else - strcpy(buffer, cachedFile.c_str()); + strcpy(iniFileBuffer, cachedFile.c_str()); #endif ImGuiIO& io = ImGui::GetIO(); - io.IniFilename = buffer; - //io.IniSavingRate = 5.f; + io.IniFilename = iniFileBuffer; io.DeltaTime = 1.f / 60.f; - //io.PixelCenterOffset = 0.5f; io.KeyMap[ImGuiKey_Tab] = static_cast(Key::Tab); io.KeyMap[ImGuiKey_LeftArrow] = static_cast(Key::Left); io.KeyMap[ImGuiKey_RightArrow] = static_cast(Key::Right); @@ -200,15 +207,61 @@ void GUI::initialize() { io.KeyMap[ImGuiKey_Y] = static_cast(Key::Y); io.KeyMap[ImGuiKey_Z] = static_cast(Key::Z); - io.RenderDrawListsFn = ImImpl_RenderDrawLists; - //io.SetClipboardTextFn = ImImpl_SetClipboardTextFn; // @TODO implement? ---abock - //io.GetClipboardTextFn = ImImpl_GetClipboardTextFn; // @TODO implement? ---abock + io.RenderDrawListsFn = RenderDrawLists; + io.Fonts->AddFontFromFileTTF( + absPath(GuiFont).c_str(), + 16.f + ); + + ImGuiStyle& style = ImGui::GetStyle(); + style.WindowPadding = { 4.f, 4.f }; + style.WindowRounding = 0.f; + style.FramePadding = { 3.f, 3.f }; + style.FrameRounding = 0.f; + style.ScrollbarWidth = 15.f; + style.ScrollbarRounding = 0.f; + style.IndentSpacing = 25; + style.ItemSpacing = { 4.f, 2.f }; + + style.Colors[ImGuiCol_WindowBg] = ImVec4(0.0f, 0.21f, 0.24f, 1.0f); + style.Colors[ImGuiCol_Border] = ImVec4(0.1f, 0.39f, 0.42f, 0.59f); + style.Colors[ImGuiCol_BorderShadow] = ImVec4(0.0f, 0.0f, 0.0f, 0.0f); + style.Colors[ImGuiCol_TitleBg] = ImVec4(0.5f, 0.94f, 1.0f, 0.45f); + style.Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.5f, 0.94f, 1.0f, 0.45f); + style.Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.0f, 0.0f, 0.0f, 0.0f); + style.Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.12f, 0.71f, 0.8f, 0.43f); + style.Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.4f, 0.75f, 0.8f, 0.65f); + style.Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.4f, 0.75f, 0.8f, 0.65f); + style.Colors[ImGuiCol_ComboBg] = ImVec4(0.18f, 0.51f, 0.78f, 1.f); + style.Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.5f, 0.8f, 0.76f, 1.0f); + style.Colors[ImGuiCol_Button] = ImVec4(0.0f, 0.36f, 0.67f, 0.6f); + style.Colors[ImGuiCol_ButtonHovered] = ImVec4(0.0f, 0.51f, 0.94f, 1.0f); + style.Colors[ImGuiCol_ButtonActive] = ImVec4(0.0f, 0.43f, 0.8f, 1.0f); + style.Colors[ImGuiCol_Header] = ImVec4(0.f, 0.36f, 0.67f, 0.45f); + style.Colors[ImGuiCol_HeaderHovered] = ImVec4(0.f, 0.54f, 1.0f, 0.8f); + style.Colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.63f, 0.87f, 0.8f); + style.Colors[ImGuiCol_ResizeGrip] = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); + style.Colors[ImGuiCol_CloseButton] = ImVec4(0.75f, 0.75f, 0.75f, 1.0f); + style.Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.52f, 0.52f, 0.52f, 0.6f); + style.Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.52f, 0.52f, 0.52f, 1.0f); _property.initialize(); _screenSpaceProperty.initialize(); + _globalProperty.initialize(); _performance.initialize(); _help.initialize(); - _iswa.initialize(); + _iswa.initialize(); +} + +void GUI::deinitialize() { + _iswa.deinitialize(); + _help.deinitialize(); + _performance.deinitialize(); + _globalProperty.deinitialize(); + _screenSpaceProperty.deinitialize(); + _property.deinitialize(); + + delete iniFileBuffer; } void GUI::initializeGL() { @@ -220,40 +273,59 @@ void GUI::initializeGL() { if (!_program) return; - positionLocation = glGetAttribLocation(*_program, "in_position"); - uvLocation = glGetAttribLocation(*_program, "in_uv"); - colorLocation = glGetAttribLocation(*_program, "in_color"); - - glGenTextures(1, &fontTex); - glBindTexture(GL_TEXTURE_2D, fontTex); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - unsigned char* png_data; - int tex_x, tex_y; - ImGui::GetIO().Fonts->GetTexDataAsRGBA32(&png_data, &tex_x, &tex_y); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_x, tex_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, png_data); - //stbi_image_free(tex_data); + unsigned char* pngData; + glm::ivec2 textureSize; + ImGui::GetIO().Fonts->GetTexDataAsRGBA32(&pngData, &textureSize.x, &textureSize.y); + + _fontTexture = std::make_unique( + pngData, + glm::uvec3(textureSize.x, textureSize.y, 1) + ); + _fontTexture->setName("Gui Text"); + _fontTexture->setDataOwnership(ghoul::opengl::Texture::TakeOwnership::No); + _fontTexture->uploadTexture(); glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, vboMaxSize, NULL, GL_DYNAMIC_DRAW); - + glGenVertexArrays(1, &vao); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); - glEnableVertexAttribArray(positionLocation); - glEnableVertexAttribArray(uvLocation); - glEnableVertexAttribArray(colorLocation); + glEnableVertexAttribArray(_program->attributeLocation("in_position")); + glEnableVertexAttribArray(_program->attributeLocation("in_uv")); + glEnableVertexAttribArray(_program->attributeLocation("in_color")); - glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, pos)); - glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, uv)); - glVertexAttribPointer(colorLocation, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, col)); + glVertexAttribPointer( + _program->attributeLocation("in_position"), + 2, + GL_FLOAT, + GL_FALSE, + sizeof(ImDrawVert), + reinterpret_cast(offsetof(ImDrawVert, pos)) + ); + glVertexAttribPointer( + _program->attributeLocation("in_uv"), + 2, + GL_FLOAT, + GL_FALSE, + sizeof(ImDrawVert), + reinterpret_cast(offsetof(ImDrawVert, uv)) + ); + glVertexAttribPointer( + _program->attributeLocation("in_color"), + 4, + GL_UNSIGNED_BYTE, + GL_TRUE, + sizeof(ImDrawVert), + reinterpret_cast(offsetof(ImDrawVert, col)) + ); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); - _property.initializeGL(); _screenSpaceProperty.initializeGL(); + _globalProperty.initializeGL(); _performance.initializeGL(); _help.initializeGL(); _iswa.initializeGL(); @@ -261,15 +333,17 @@ void GUI::initializeGL() { void GUI::deinitializeGL() { _program = nullptr; + _fontTexture = nullptr; glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vbo); - _property.deinitializeGL(); - _screenSpaceProperty.deinitializeGL(); - _performance.deinitializeGL(); - _help.deinitializeGL(); _iswa.deinitializeGL(); + _help.deinitializeGL(); + _performance.deinitializeGL(); + _globalProperty.deinitializeGL(); + _screenSpaceProperty.deinitializeGL(); + _property.deinitializeGL(); } void GUI::startFrame(float deltaTime, const glm::vec2& windowSize, @@ -277,18 +351,15 @@ void GUI::startFrame(float deltaTime, const glm::vec2& windowSize, const glm::vec2& mousePos, uint32_t mouseButtonsPressed) { - ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2(windowSize.x, windowSize.y); io.DeltaTime = deltaTime; - io.MousePos = ImVec2(mousePos.x * mousePosCorrectionFactor.x, mousePos.y * mousePosCorrectionFactor.y); + io.MousePos = ImVec2( + mousePos.x * mousePosCorrectionFactor.x, + mousePos.y * mousePosCorrectionFactor.y + ); -//#ifdef __APPLE__ -// io.MousePos = ImVec2(mousePos.x * 2, mousePos.y * 2); -//#else -// io.MousePos = ImVec2(mousePos.x, mousePos.y); -//#endif io.MouseDown[0] = mouseButtonsPressed & (1 << 0); io.MouseDown[1] = mouseButtonsPressed & (1 << 1); @@ -296,8 +367,10 @@ void GUI::startFrame(float deltaTime, const glm::vec2& windowSize, } void GUI::endFrame() { - renderMainWindow(); + render(); + if (_globalProperty.isEnabled()) + _globalProperty.render(); if (_property.isEnabled()) _property.render(); if (_screenSpaceProperty.isEnabled()) @@ -313,7 +386,6 @@ void GUI::endFrame() { } bool GUI::mouseButtonCallback(MouseButton button, MouseAction action) { -//bool GUI::mouseButtonCallback(int key, int action) { ImGuiIO& io = ImGui::GetIO(); bool consumeEvent = io.WantCaptureMouse; return consumeEvent; @@ -322,14 +394,14 @@ bool GUI::mouseButtonCallback(MouseButton button, MouseAction action) { bool GUI::mouseWheelCallback(double position) { ImGuiIO& io = ImGui::GetIO(); bool consumeEvent = io.WantCaptureMouse; - if (consumeEvent) + if (consumeEvent) { io.MouseWheel = static_cast(position); + } return consumeEvent; } bool GUI::keyCallback(Key key, KeyModifier modifier, KeyAction action) { -//bool GUI::keyCallback(int key, int action) { ImGuiIO& io = ImGui::GetIO(); bool consumeEvent = io.WantCaptureKeyboard; if (consumeEvent) { @@ -342,6 +414,10 @@ bool GUI::keyCallback(Key key, KeyModifier modifier, KeyAction action) { if (action == KeyAction::Release) io.KeysDown[keyIndex] = false; } + + io.KeyShift = hasKeyModifier(modifier, KeyModifier::Shift); + io.KeyCtrl = hasKeyModifier(modifier, KeyModifier::Control); + io.KeyAlt = hasKeyModifier(modifier, KeyModifier::Alt); } return consumeEvent; } @@ -356,54 +432,12 @@ bool GUI::charCallback(unsigned int character, KeyModifier modifier) { return consumeEvent; } -//void GUI::registerProperty(properties::Property* prop) { -// using namespace properties; -// -// std::string className = prop->className(); -// -// if (className == "BoolProperty") -// _boolProperties.insert(prop); -// else if (className == "IntProperty") -// _intProperties.insert(prop); -// else if (className == "FloatProperty") -// _floatProperties.insert(prop); -// else if (className == "StringProperty") -// _stringProperties.insert(prop); -// else if (className == "Vec2Property") -// _vec2Properties.insert(prop); -// else if (className == "Vec3Property") -// _vec3Properties.insert(prop); -// else if (className == "Vec4Property") -// _vec4Properties.insert(prop); -// else if (className == "OptionProperty") -// _optionProperty.insert(prop); -// else if (className == "TriggerProperty") -// _triggerProperty.insert(prop); -// else if (className == "SelectionProperty") -// _selectionProperty.insert(prop); -// else { -// LWARNING("Class name '" << className << "' not handled in GUI generation"); -// return; -// } -// -// std::string fullyQualifiedId = prop->fullyQualifiedIdentifier(); -// size_t pos = fullyQualifiedId.find('.'); -// std::string owner = fullyQualifiedId.substr(0, pos); -// -// auto it =_propertiesByOwner.find(owner); -// if (it == _propertiesByOwner.end()) -// _propertiesByOwner[owner] = { prop }; -// else -// it->second.push_back(prop); -// -//} - -//>>>>>>> develop -void GUI::renderMainWindow() { +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); #ifdef OPENSPACE_MODULE_ISWA_ENABLED ImGui::Checkbox("iSWA", &_iswa._isEnabled); #endif @@ -417,14 +451,26 @@ void GUI::renderMainWindow() { bool toJupiter = ImGui::Button("Coordinate System to Jupiter"); bool to67P = ImGui::Button("Coordinate System to 67P"); - 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');"); + 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); @@ -432,217 +478,46 @@ void GUI::renderMainWindow() { static char addImageBuffer[addImageBufferSize]; ImGui::InputText("addImage", addImageBuffer, addImageBufferSize); - if(ImGui::SmallButton("Add Image")){ + if (ImGui::SmallButton("Add Image")) { addScreenSpaceRenderable(std::string(addImageBuffer)); } -// #ifdef OPENSPACE_MODULE_ISWA_ENABLED -// static const int addCygnetBufferSize = 256; -// static char addCygnetBuffer[addCygnetBufferSize]; -// ImGui::InputText("addCynget", addCygnetBuffer, addCygnetBufferSize); +#ifdef SHOW_IMGUI_HELPERS + ImGui::Begin("Style Editor"); + ImGui::ShowStyleEditor(); + ImGui::End(); -// if(ImGui::SmallButton("Add Cygnet")) -// OsEng.scriptEngine().queueScript("openspace.iswa.addCygnet('"+std::string(addCygnetBuffer)+"');"); - -// #endif + ImGui::Begin("Test Window"); + ImGui::ShowTestWindow(); + ImGui::End(); + + ImGui::Begin("Metrics Window"); + ImGui::ShowMetricsWindow(); + ImGui::End(); +#endif ImGui::End(); } - -//<<<<<<< HEAD -namespace { -//======= -//void GUI::renderPropertyWindow() { -// using namespace properties; -// -// ImGui::Begin("Properties", &_showPropertyWindow, size, 0.5f); -// -// //ImGui::ShowUserGuide(); -// ImGui::Spacing(); -// -// for (const auto& p : _propertiesByOwner) { -// if (ImGui::CollapsingHeader(p.first.c_str())) { -// for (properties::Property* prop : p.second) { -// if (_boolProperties.find(prop) != _boolProperties.end()) { -// renderBoolProperty(prop, p.first); -// continue; -// } -// -// if (_intProperties.find(prop) != _intProperties.end()) { -// renderIntProperty(prop, p.first); -// continue; -// } -// -// if (_floatProperties.find(prop) != _floatProperties.end()) { -// renderFloatProperty(prop, p.first); -// continue; -// } -// -// if (_vec2Properties.find(prop) != _vec2Properties.end()) { -// renderVec2Property(prop, p.first); -// continue; -// } -// -// if (_vec3Properties.find(prop) != _vec3Properties.end()) { -// renderVec3Property(prop, p.first); -// continue; -// } -// -// if (_vec4Properties.find(prop) != _vec4Properties.end()) { -// renderVec4Property(prop, p.first); -// continue; -// } -// -// if (_optionProperty.find(prop) != _optionProperty.end()) { -// renderOptionProperty(prop, p.first); -// continue; -// } -// -// if (_triggerProperty.find(prop) != _triggerProperty.end()) { -// renderTriggerProperty(prop, p.first); -// continue; -// } -// -// if (_selectionProperty.find(prop) != _selectionProperty.end()) { -// renderSelectionProperty(prop, p.first); -// continue; -// } -// } -// } -// } -// -// ImGui::End(); -//} -// -//void GUI::renderPerformanceWindow() { -// // Copy and paste from renderengine.cpp::storePerformanceMeasurements method -// const int8_t Version = 0; -// const int nValues = 250; -// const int lengthName = 256; -// const int maxValues = 50; -// -// struct PerformanceLayout { -// int8_t version; -// int32_t nValuesPerEntry; -// int32_t nEntries; -// int32_t maxNameLength; -// int32_t maxEntries; -// -// struct PerformanceLayoutEntry { -// char name[lengthName]; -// float renderTime[nValues]; -// float updateRenderable[nValues]; -// float updateEphemeris[nValues]; -// -// int32_t currentRenderTime; -// int32_t currentUpdateRenderable; -// int32_t currentUpdateEphemeris; -// }; -// -// PerformanceLayoutEntry entries[maxValues]; -// }; -// -// ImGui::Begin("Performance", &_showPerformanceWindow); -// if (OsEng.renderEngine()->doesPerformanceMeasurements() && -// ghoul::SharedMemory::exists(RenderEngine::PerformanceMeasurementSharedData)) -// { -// ImGui::SliderFloat2("Min values, max Value", _minMaxValues, 0.f, 10000.f); -// _minMaxValues[1] = std::max(_minMaxValues[0], _minMaxValues[1]); -// -// if (!_performanceMemory) -// _performanceMemory = new ghoul::SharedMemory(RenderEngine::PerformanceMeasurementSharedData); -// -// PerformanceLayout* layout = reinterpret_cast(_performanceMemory->pointer()); -// -// for (int i = 0; i < layout->nEntries; ++i) { -// const PerformanceLayout::PerformanceLayoutEntry& entry = layout->entries[i]; -// -// if (ImGui::CollapsingHeader(entry.name)) { -// std::string updateEphemerisTime = std::to_string(entry.updateEphemeris[entry.currentUpdateEphemeris - 1]) + "us"; -// ImGui::PlotLines("UpdateEphemeris", &entry.updateEphemeris[0], layout->nValuesPerEntry, 0, updateEphemerisTime.c_str(), _minMaxValues[0], _minMaxValues[1], ImVec2(0, 40)); -// -// std::string updateRenderableTime = std::to_string(entry.updateRenderable[entry.currentUpdateRenderable - 1]) + "us"; -// ImGui::PlotLines("UpdateRender", &entry.updateRenderable[0], layout->nValuesPerEntry, 0, updateRenderableTime.c_str(), _minMaxValues[0], _minMaxValues[1], ImVec2(0, 40)); -// -// std::string renderTime = std::to_string(entry.renderTime[entry.currentRenderTime - 1]) + "us"; -// ImGui::PlotLines("RenderTime", &entry.renderTime[0], layout->nValuesPerEntry, 0, renderTime.c_str(), _minMaxValues[0], _minMaxValues[1], ImVec2(0, 40)); -// } -// } -// } -// else { -// ImGui::TextWrapped("Performance monitoring is disabled. Enable with " -// "'openspace.setPerformanceMeasurement(true)'"); -// } -// -// ImGui::End(); -//} -// -//namespace { -//>>>>>>> develop - -/** - * \ingroup LuaScripts - * show(): - * Shows the GUI - */ -int show(lua_State* L) { - int nArguments = lua_gettop(L); - if (nArguments != 0) - return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments); - - OsEng.gui().setEnabled(true); - return 0; -} - -/** - * \ingroup LuaScripts - * hide(): - * Hides the console - */ -int hide(lua_State* L) { - int nArguments = lua_gettop(L); - if (nArguments != 0) - return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments); - - OsEng.gui().setEnabled(false); - return 0; -} - -/** - * \ingroup LuaScripts - * toggle(): - * Toggles the console - */ -int toggle(lua_State* L) { - int nArguments = lua_gettop(L); - if (nArguments != 0) - return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments); - - OsEng.gui().setEnabled(!OsEng.gui().isEnabled()); - return 0; -} - -} - + scripting::ScriptEngine::LuaLibrary GUI::luaLibrary() { return { "gui", { { "show", - &show, + &luascriptfunctions::gui::show, "", "Shows the console" }, { "hide", - &hide, + &luascriptfunctions::gui::hide, "", "Hides the console" }, { "toggle", - &toggle, + &luascriptfunctions::gui::toggle, "", "Toggles the console" } @@ -650,409 +525,5 @@ scripting::ScriptEngine::LuaLibrary GUI::luaLibrary() { }; } - } // namespace gui } // namespace openspace - -// -// -// -// -// -// -// -// -// -// -// -// -// -// -//#include -// -//#include -//#include -// -//#include -//#include -//#include -//#include -//#include -//#include -// -//#include -//#include -//#include -//#include -//#include -//#include -// -//#include -//#include -// -//#include -//#include -//#define STB_IMAGE_IMPLEMENTATION -//#include -// -//namespace { -// const std::string _loggerCat = "GUI"; -// const std::string configurationFile = "imgui.ini"; -// -// -//namespace openspace { -// namespace gui { -// -//GUI::GUI() -// : _isEnabled(false) -// , _showPropertyWindow(false) -// , _showHelp(false) -// , _performanceMemory(nullptr) -//{ -// _minMaxValues[0] = 100.f; -// _minMaxValues[1] = 1000.f; -//} -// -//GUI::~GUI() { -// delete _performanceMemory; -// ImGui::Shutdown(); -//} -// -//bool GUI::isEnabled() const { -// return _isEnabled; -//} -// -//void GUI::setEnabled(bool enabled) { -// _isEnabled = enabled; -//} -// -//void GUI::initialize() { -// std::string cachedFile; -// FileSys.cacheManager()->getCachedFile(configurationFile, "", cachedFile, true); -// -// char* buffer = new char[cachedFile.size() + 1]; -// -//#ifdef WIN32 -// strcpy_s(buffer, cachedFile.size() + 1, cachedFile.c_str()); -//#else -// strcpy(buffer, cachedFile.c_str()); -//#endif -// -// ImGuiIO& io = ImGui::GetIO(); -// io.IniFilename = buffer; -// //io.IniSavingRate = 5.f; -// io.DeltaTime = 1.f / 60.f; -// io.PixelCenterOffset = 0.5f; -// io.KeyMap[ImGuiKey_Tab] = SGCT_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array. -// io.KeyMap[ImGuiKey_LeftArrow] = SGCT_KEY_LEFT; -// io.KeyMap[ImGuiKey_RightArrow] = SGCT_KEY_RIGHT; -// io.KeyMap[ImGuiKey_UpArrow] = SGCT_KEY_UP; -// io.KeyMap[ImGuiKey_DownArrow] = SGCT_KEY_DOWN; -// io.KeyMap[ImGuiKey_Home] = SGCT_KEY_HOME; -// io.KeyMap[ImGuiKey_End] = SGCT_KEY_END; -// io.KeyMap[ImGuiKey_Delete] = SGCT_KEY_DELETE; -// io.KeyMap[ImGuiKey_Backspace] = SGCT_KEY_BACKSPACE; -// io.KeyMap[ImGuiKey_Enter] = SGCT_KEY_ENTER; -// io.KeyMap[ImGuiKey_Escape] = SGCT_KEY_ESCAPE; -// io.KeyMap[ImGuiKey_A] = SGCT_KEY_A; -// io.KeyMap[ImGuiKey_C] = SGCT_KEY_C; -// io.KeyMap[ImGuiKey_V] = SGCT_KEY_V; -// io.KeyMap[ImGuiKey_X] = SGCT_KEY_X; -// io.KeyMap[ImGuiKey_Y] = SGCT_KEY_Y; -// io.KeyMap[ImGuiKey_Z] = SGCT_KEY_Z; -// -// io.RenderDrawListsFn = ImImpl_RenderDrawLists; -// //io.SetClipboardTextFn = ImImpl_SetClipboardTextFn; // @TODO implement? ---abock -// //io.GetClipboardTextFn = ImImpl_GetClipboardTextFn; // @TODO implement? ---abock -//} -// -//void GUI::initializeGL() { -// _program = ghoul::opengl::ProgramObject::Build("GUI", -// "${SHADERS}/gui_vs.glsl", "${SHADERS}/gui_fs.glsl"); -// -// positionLocation = glGetAttribLocation(*_program, "in_position"); -// uvLocation = glGetAttribLocation(*_program, "in_uv"); -// colorLocation = glGetAttribLocation(*_program, "in_color"); -// -// glGenTextures(1, &fontTex); -// glBindTexture(GL_TEXTURE_2D, fontTex); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); -// const void* png_data; -// unsigned int png_size; -// ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); -// int tex_x, tex_y, tex_comp; -// void* tex_data = stbi_load_from_memory((const unsigned char*)png_data, (int)png_size, &tex_x, &tex_y, &tex_comp, 0); -// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_x, tex_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_data); -// stbi_image_free(tex_data); -// -// glGenBuffers(1, &vbo); -// glBindBuffer(GL_ARRAY_BUFFER, vbo); -// glBufferData(GL_ARRAY_BUFFER, vboMaxSize, NULL, GL_DYNAMIC_DRAW); -// -// glGenVertexArrays(1, &vao); -// glBindVertexArray(vao); -// glBindBuffer(GL_ARRAY_BUFFER, vbo); -// glEnableVertexAttribArray(positionLocation); -// glEnableVertexAttribArray(uvLocation); -// glEnableVertexAttribArray(colorLocation); -// -// glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*) offsetof(ImDrawVert, pos)); -// glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*) offsetof(ImDrawVert, uv)); -// glVertexAttribPointer(colorLocation, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*) offsetof(ImDrawVert, col)); -// glBindVertexArray(0); -// glBindBuffer(GL_ARRAY_BUFFER, 0); -//} -// -//void GUI::deinitializeGL() { -// if(_program) -// delete _program; -// _program = nullptr; -// -// if (vao) glDeleteVertexArrays(1, &vao); -// if (vbo) glDeleteBuffers(1, &vbo); -//} -// -//void GUI::startFrame(float deltaTime, -// const glm::vec2& windowSize, -// const glm::vec2& mousePos, -// bool mouseButtonsPressed[2]) -//{ -// ImGuiIO& io = ImGui::GetIO(); -// io.DisplaySize = ImVec2(windowSize.x, windowSize.y); -// io.DeltaTime = deltaTime; -// io.MousePos = ImVec2(mousePos.x, mousePos.y); -// io.MouseDown[0] = mouseButtonsPressed[0]; -// io.MouseDown[1] = mouseButtonsPressed[1]; -// -// ImGui::NewFrame(); -//} -// -//void GUI::endFrame() { -// static bool show = true; -// //ImGui::ShowTestWindow(&show); -// renderMainWindow(); -// if (_showPropertyWindow) -// renderPropertyWindow(); -// if (_showPerformanceWindow) -// renderPerformanceWindow(); -// -// ImGui::Render(); -//} -// -//bool GUI::mouseButtonCallback(int key, int action) { -// ImGuiIO& io = ImGui::GetIO(); -// bool consumeEvent = io.WantCaptureMouse; -// return consumeEvent; -//} -// -//bool GUI::mouseWheelCallback(int position) { -// ImGuiIO& io = ImGui::GetIO(); -// bool consumeEvent = io.WantCaptureMouse; -// if (consumeEvent) -// io.MouseWheel = static_cast(position); -// -// return consumeEvent; -//} -// -//bool GUI::keyCallback(int key, int action) { -// ImGuiIO& io = ImGui::GetIO(); -// bool consumeEvent = io.WantCaptureKeyboard; -// if (consumeEvent) { -// if (action == SGCT_PRESS) -// io.KeysDown[key] = true; -// if (action == SGCT_RELEASE) -// io.KeysDown[key] = false; -// } -// return consumeEvent; -//} -// -//bool GUI::charCallback(unsigned int character) { -// ImGuiIO& io = ImGui::GetIO(); -// bool consumeEvent = io.WantCaptureKeyboard; -// -// if (consumeEvent) -// io.AddInputCharacter((unsigned short)character); -// -// return consumeEvent; -//} -// -//void GUI::registerProperty(properties::Property* prop) { -// using namespace openspace::properties; -// -// std::string className = prop->className(); -// -// if (className == "BoolProperty") -// _boolProperties.insert(prop); -// else if (className == "IntProperty") -// _intProperties.insert(prop); -// else if (className == "FloatProperty") -// _floatProperties.insert(prop); -// else if (className == "StringProperty") -// _stringProperties.insert(prop); -// else if (className == "Vec2Property") -// _vec2Properties.insert(prop); -// else if (className == "Vec3Property") -// _vec3Properties.insert(prop); -// else if (className == "OptionProperty") -// _optionProperty.insert(prop); -// else if (className == "TriggerProperty") -// _triggerProperty.insert(prop); -// else if (className == "SelectionProperty") -// _selectionProperty.insert(prop); -// else { -// LWARNING("Class name '" << className << "' not handled in GUI generation"); -// return; -// } -// -// std::string fullyQualifiedId = prop->fullyQualifiedIdentifier(); -// size_t pos = fullyQualifiedId.find('.'); -// std::string owner = fullyQualifiedId.substr(0, pos); -// -// auto it =_propertiesByOwner.find(owner); -// if (it == _propertiesByOwner.end()) -// _propertiesByOwner[owner] = { prop }; -// else -// it->second.push_back(prop); -// -//} -// -//void GUI::renderMainWindow() { -// ImGui::Begin("OpenSpace GUI", nullptr); -// -// ImGui::Checkbox("Properties", &_showPropertyWindow); -// ImGui::Checkbox("Performance", &_showPerformanceWindow); -// ImGui::Checkbox("Help", &_showHelp); -// -// if (_showHelp) { -// ImGui::Separator(); -// ImGui::ShowUserGuide(); -// ImGui::ShowTestWindow(); -// } -// -// ImGui::End(); -//} -// -//void GUI::renderPropertyWindow() { -// using namespace properties; -// -// ImGui::Begin("Properties", &_showPropertyWindow, size, 0.5f); -// -// //ImGui::ShowUserGuide(); -// ImGui::Spacing(); -// -// for (const auto& p : _propertiesByOwner) { -// if (ImGui::CollapsingHeader(p.first.c_str())) { -// for (properties::Property* prop : p.second) { -// if (_boolProperties.find(prop) != _boolProperties.end()) { -// renderBoolProperty(prop, p.first); -// continue; -// } -// -// if (_intProperties.find(prop) != _intProperties.end()) { -// renderIntProperty(prop, p.first); -// continue; -// } -// -// if (_floatProperties.find(prop) != _floatProperties.end()) { -// renderFloatProperty(prop, p.first); -// continue; -// } -// -// if (_vec2Properties.find(prop) != _vec2Properties.end()) { -// renderVec2Property(prop, p.first); -// continue; -// } -// -// if (_vec3Properties.find(prop) != _vec3Properties.end()) { -// renderVec3Property(prop, p.first); -// continue; -// } -// -// if (_optionProperty.find(prop) != _optionProperty.end()) { -// renderOptionProperty(prop, p.first); -// continue; -// } -// -// if (_triggerProperty.find(prop) != _triggerProperty.end()) { -// renderTriggerProperty(prop, p.first); -// continue; -// } -// -// if (_selectionProperty.find(prop) != _selectionProperty.end()) { -// renderSelectionProperty(prop, p.first); -// continue; -// } -// } -// } -// } -// -// ImGui::End(); -//} -// -//void GUI::renderPerformanceWindow() { -// // Copy and paste from renderengine.cpp::storePerformanceMeasurements method -// const int8_t Version = 0; -// const int nValues = 250; -// const int lengthName = 256; -// const int maxValues = 50; -// -// struct PerformanceLayout { -// int8_t version; -// int32_t nValuesPerEntry; -// int32_t nEntries; -// int32_t maxNameLength; -// int32_t maxEntries; -// -// struct PerformanceLayoutEntry { -// char name[lengthName]; -// float renderTime[nValues]; -// float updateRenderable[nValues]; -// float updateEphemeris[nValues]; -// -// int32_t currentRenderTime; -// int32_t currentUpdateRenderable; -// int32_t currentUpdateEphemeris; -// }; -// -// PerformanceLayoutEntry entries[maxValues]; -// }; -// -// ImGui::Begin("Performance", &_showPerformanceWindow); -// if (OsEng.renderEngine().doesPerformanceMeasurements() && -// ghoul::SharedMemory::exists(RenderEngine::PerformanceMeasurementSharedData)) -// { -// ImGui::SliderFloat2("Min values, max Value", _minMaxValues, 0.f, 10000.f); -// _minMaxValues[1] = std::max(_minMaxValues[0], _minMaxValues[1]); -// -// if (!_performanceMemory) -// _performanceMemory = new ghoul::SharedMemory(RenderEngine::PerformanceMeasurementSharedData); -// -// PerformanceLayout* layout = reinterpret_cast(_performanceMemory->pointer()); -// -// for (int i = 0; i < layout->nEntries; ++i) { -// const PerformanceLayout::PerformanceLayoutEntry& entry = layout->entries[i]; -// -// if (ImGui::CollapsingHeader(entry.name)) { -// std::string updateEphemerisTime = std::to_string(entry.updateEphemeris[entry.currentUpdateEphemeris - 1]) + "us"; -// ImGui::PlotLines("UpdateEphemeris", &entry.updateEphemeris[0], layout->nValuesPerEntry, 0, updateEphemerisTime.c_str(), _minMaxValues[0], _minMaxValues[1], ImVec2(0, 40)); -// -// std::string updateRenderableTime = std::to_string(entry.updateRenderable[entry.currentUpdateRenderable - 1]) + "us"; -// ImGui::PlotLines("UpdateRender", &entry.updateRenderable[0], layout->nValuesPerEntry, 0, updateRenderableTime.c_str(), _minMaxValues[0], _minMaxValues[1], ImVec2(0, 40)); -// -// std::string renderTime = std::to_string(entry.renderTime[entry.currentRenderTime - 1]) + "us"; -// ImGui::PlotLines("RenderTime", &entry.renderTime[0], layout->nValuesPerEntry, 0, renderTime.c_str(), _minMaxValues[0], _minMaxValues[1], ImVec2(0, 40)); -// } -// } -// } -// else { -// ImGui::TextWrapped("Performance monitoring is disabled. Enable with " -// "'openspace.setPerformanceMeasurement(true)'"); -// } -// -// ImGui::End(); -//} -// -// -//} // namespace openspace -//} // namespace gui diff --git a/modules/onscreengui/src/gui_lua.inl b/modules/onscreengui/src/gui_lua.inl new file mode 100644 index 0000000000..d84ea0defd --- /dev/null +++ b/modules/onscreengui/src/gui_lua.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 luascriptfunctions { + +namespace gui { + +/** + * \ingroup LuaScripts + * show(): + * Shows the GUI + */ +int show(lua_State* L) { + int nArguments = lua_gettop(L); + if (nArguments != 0) + return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments); + + OsEng.gui().setEnabled(true); + return 0; +} + +/** + * \ingroup LuaScripts + * hide(): + * Hides the console + */ +int hide(lua_State* L) { + int nArguments = lua_gettop(L); + if (nArguments != 0) + return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments); + + OsEng.gui().setEnabled(false); + return 0; +} + +/** + * \ingroup LuaScripts + * toggle(): + * Toggles the console + */ +int toggle(lua_State* L) { + int nArguments = lua_gettop(L); + if (nArguments != 0) + return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments); + + OsEng.gui().setEnabled(!OsEng.gui().isEnabled()); + return 0; +} + +} // namespace gui +} // namespace luascriptfunctions +} // namespace openspace diff --git a/modules/onscreengui/src/guihelpcomponent.cpp b/modules/onscreengui/src/guihelpcomponent.cpp index 4530891a18..c38e2ebe38 100644 --- a/modules/onscreengui/src/guihelpcomponent.cpp +++ b/modules/onscreengui/src/guihelpcomponent.cpp @@ -39,5 +39,5 @@ void GuiHelpComponent::render() { ImGui::End(); } -} // gui -} // openspace +} // namespace gui +} // namespace openspace diff --git a/modules/onscreengui/src/guiiswacomponent.cpp b/modules/onscreengui/src/guiiswacomponent.cpp index 853dac4d87..e09a294a85 100644 --- a/modules/onscreengui/src/guiiswacomponent.cpp +++ b/modules/onscreengui/src/guiiswacomponent.cpp @@ -23,29 +23,16 @@ ****************************************************************************************/ #include -#include +#include + +#include #include -#include #include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include -#include #include - -#include +#include #include "imgui.h" @@ -57,86 +44,96 @@ namespace { namespace openspace { namespace gui { + GuiIswaComponent::GuiIswaComponent() - :GuiPropertyComponent() - ,_gmdata(false) - ,_gmimage(false) - ,_iondata(false) + : GuiPropertyComponent("iSWA") + , _gmData(false) + , _gmImage(false) + , _ionData(false) {} void GuiIswaComponent::render() { - bool gmdatavalue = _gmdata; - bool gmimagevalue = _gmimage; - bool iondatavalue = _iondata; +#ifdef OPENSPACE_MODULE_ISWA_ENABLED + bool oldGmDataValue = _gmData; + bool oldGmImageValue = _gmImage; + bool oldIonDataValue = _ionData; ImGui::Begin("ISWA", &_isEnabled, size, 0.5f); - // ImGui::Text("Global Magnetosphere"); - // ImGui::Checkbox("Gm From Data", &_gmdata); ImGui::SameLine(); - // ImGui::Checkbox("Gm From Images", &_gmimage); + + ImGui::Text("Global Magnetosphere"); + ImGui::Checkbox("Gm From Data", &_gmData); ImGui::SameLine(); + ImGui::Checkbox("Gm From Images", &_gmImage); - // ImGui::Text("Ionosphere"); - // ImGui::Checkbox("Ion From Data", &_iondata); + ImGui::Text("Ionosphere"); + ImGui::Checkbox("Ion From Data", &_ionData); + ImGui::Spacing(); + static const int addCygnetBufferSize = 256; + static char addCygnetBuffer[addCygnetBufferSize]; + ImGui::InputText("addCynget", addCygnetBuffer, addCygnetBufferSize); - // ImGui::Spacing(); - // static const int addCygnetBufferSize = 256; - // static char addCygnetBuffer[addCygnetBufferSize]; - // ImGui::InputText("addCynget", addCygnetBuffer, addCygnetBufferSize); + if (ImGui::SmallButton("Add Cygnet")) { + OsEng.scriptEngine().queueScript( + "openspace.iswa.addCygnet(" + std::string(addCygnetBuffer) + ");" + ); + } - // if(ImGui::SmallButton("Add Cygnet")) - // OsEng.scriptEngine().queueScript("openspace.iswa.addCygnet("+std::string(addCygnetBuffer)+");"); - - if(_gmdata != gmdatavalue){ - if(_gmdata){ - std::string x = "openspace.iswa.addCygnet(-1,'Data','GMData');"; - std::string y = "openspace.iswa.addCygnet(-2,'Data','GMData');"; - std::string z = "openspace.iswa.addCygnet(-3,'Data','GMData');"; - OsEng.scriptEngine().queueScript(x+y+z); - }else{ + if (_gmData != oldGmDataValue) { + if (_gmData) { + 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); + } else { OsEng.scriptEngine().queueScript("openspace.iswa.removeGroup('GMData');"); } } - if(_gmimage != gmimagevalue){ - if(_gmimage){ - std::string x = "openspace.iswa.addCygnet(-1,'Texture','GMImage');"; - std::string y = "openspace.iswa.addCygnet(-2,'Texture','GMImage');"; - std::string z = "openspace.iswa.addCygnet(-3,'Texture','GMImage');"; - OsEng.scriptEngine().queueScript(x+y+z); - }else{ + if (_gmImage != oldGmImageValue) { + if (_gmImage) { + 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); + } else { OsEng.scriptEngine().queueScript("openspace.iswa.removeGroup('GMImage');"); } } - if(_iondata != iondatavalue){ - if(_iondata){ - OsEng.scriptEngine().queueScript("openspace.iswa.addCygnet(-4,'Data','Ionosphere');"); - }else{ + if(_ionData != oldIonDataValue) { + if(_ionData) { + OsEng.scriptEngine().queueScript( + "openspace.iswa.addCygnet(-10,'Data','Ionosphere');" + ); + } else { OsEng.scriptEngine().queueScript("openspace.iswa.removeGroup('Ionosphere');"); } } -#ifdef OPENSPACE_MODULE_ISWA_ENABLED - if(ImGui::CollapsingHeader("Cdf files")){ - auto cdfInfo = IswaManager::ref().cdfInformation(); + if (ImGui::CollapsingHeader("Cdf files")) { + const auto& cdfInfo = IswaManager::ref().cdfInformation(); - for(auto group : cdfInfo){ + for (const auto& group : cdfInfo) { std::string groupName = group.first; - if(_cdfOptionsMap.find(groupName) == _cdfOptionsMap.end()){ + if (_cdfOptionsMap.find(groupName) == _cdfOptionsMap.end()){ _cdfOptionsMap[groupName] = -1; } - if(ImGui::CollapsingHeader(groupName.c_str())){ + if (ImGui::CollapsingHeader(groupName.c_str())) { int cdfOptionValue = _cdfOptionsMap[groupName]; - auto cdfs = group.second; + const auto& cdfs = group.second; - for(int i=0; i= 0){ + if (cdfOptionValue != cdfOption) { + if (cdfOptionValue >= 0) { groupName = cdfs[cdfOptionValue].group; // std::cout << groupName << std::endl; // OsEng.scriptEngine().queueScript("openspace.iswa.removeGroup('"+groupName+"');"); @@ -145,77 +142,29 @@ void GuiIswaComponent::render() { std::string path = cdfs[cdfOption].path; std::string date = cdfs[cdfOption].date; groupName = cdfs[cdfOption].group; - OsEng.scriptEngine().queueScript("openspace.iswa.addKameleonPlanes('"+groupName+"',"+std::to_string(cdfOption)+");"); - OsEng.scriptEngine().queueScript("openspace.time.setTime('"+date+"');"); - OsEng.scriptEngine().queueScript("openspace.time.setDeltaTime(0);"); - } - } - } - } -#endif - - for (const auto& p : _propertiesByOwner) { - if (ImGui::CollapsingHeader(p.first.c_str())) { - for (properties::Property* prop : p.second) { - if (_boolProperties.find(prop) != _boolProperties.end()) { - renderBoolProperty(prop, p.first); - continue; - } - - if (_intProperties.find(prop) != _intProperties.end()) { - renderIntProperty(prop, p.first); - continue; - } - - if (_floatProperties.find(prop) != _floatProperties.end()) { - renderFloatProperty(prop, p.first); - continue; - } - - if (_vec2Properties.find(prop) != _vec2Properties.end()) { - renderVec2Property(prop, p.first); - continue; - } - - if (_vec3Properties.find(prop) != _vec3Properties.end()) { - renderVec3Property(prop, p.first); - continue; - } - - if (_vec4Properties.find(prop) != _vec4Properties.end()) { - renderVec4Property(prop, p.first); - continue; - } - - if (_optionProperties.find(prop) != _optionProperties.end()) { - renderOptionProperty(prop, p.first); - continue; - } - - if (_triggerProperties.find(prop) != _triggerProperties.end()) { - renderTriggerProperty(prop, p.first); - continue; - } - - if (_selectionProperties.find(prop) != _selectionProperties.end()) { - renderSelectionProperty(prop, p.first); - continue; - } - - if (_stringProperties.find(prop) != _stringProperties.end()) { - renderStringProperty(prop, p.first); - continue; + OsEng.scriptEngine().queueScript( + "openspace.iswa.addKameleonPlanes('" + + groupName + + "'," + + std::to_string(cdfOption) + + ");" + ); + OsEng.scriptEngine().queueScript( + "openspace.time.setTime('" + date + "');" + ); + OsEng.scriptEngine().queueScript( + "openspace.time.setDeltaTime(0);" + ); } } } } + GuiPropertyComponent::render(); -#ifdef OPENSPACE_MODULE_ISWA_ENABLED if (ImGui::CollapsingHeader("iSWA screen space cygntes")) { - - auto map = IswaManager::ref().cygnetInformation(); - for(auto cygnetInfo : map){ + const auto& map = IswaManager::ref().cygnetInformation(); + for (const auto& cygnetInfo : map) { int id = cygnetInfo.first; auto info = cygnetInfo.second; @@ -223,27 +172,31 @@ void GuiIswaComponent::render() { ImGui::Checkbox(info->name.c_str(), &info->selected); ImGui::SameLine(); - if(ImGui::CollapsingHeader(("Description" + std::to_string(id)).c_str())){ + if (ImGui::CollapsingHeader(("Description" + std::to_string(id)).c_str())) { ImGui::TextWrapped(info->description.c_str()); ImGui::Spacing(); } - if(selected != info->selected){ - if(info->selected){ - OsEng.scriptEngine().queueScript("openspace.iswa.addScreenSpaceCygnet(" - "{CygnetId = "+std::to_string(id)+" });"); - }else{ - OsEng.scriptEngine().queueScript("openspace.iswa.removeScreenSpaceCygnet("+std::to_string(id)+");"); - + if (selected != info->selected) { + if (info->selected) { + OsEng.scriptEngine().queueScript( + "openspace.iswa.addScreenSpaceCygnet(" + "{CygnetId = " + std::to_string(id) + " });" + ); + } else { + OsEng.scriptEngine().queueScript( + "openspace.iswa.removeScreenSpaceCygnet(" + + std::to_string(id) + + ");" + ); } } - } } -#endif ImGui::End(); +#endif } -} // gui -} // openspace \ No newline at end of file +} // namespace gui +} // namespace openspace diff --git a/modules/onscreengui/src/guiorigincomponent.cpp b/modules/onscreengui/src/guiorigincomponent.cpp index 9a0f72564a..07bf244161 100644 --- a/modules/onscreengui/src/guiorigincomponent.cpp +++ b/modules/onscreengui/src/guiorigincomponent.cpp @@ -25,10 +25,12 @@ #include #include +#include #include #include -#include + #include + #include "imgui.h" namespace { @@ -39,144 +41,34 @@ namespace openspace { namespace gui { void GuiOriginComponent::render() { - const SceneGraphNode* currentFocus = OsEng.interactionHandler().focusNode(); + SceneGraphNode* currentFocus = OsEng.interactionHandler().focusNode(); - std::vector nodes = OsEng.renderEngine().scene()->allSceneGraphNodes(); - std::sort(nodes.begin(), nodes.end(), [](SceneGraphNode* lhs, SceneGraphNode* rhs) { return lhs->name() < rhs->name(); }); - auto it = std::find(nodes.begin(), nodes.end(), currentFocus); - ghoul_assert(it != nodes.end(), "Focus node not found"); + std::vector nodes = + OsEng.renderEngine().scene()->allSceneGraphNodes(); + std::sort( + nodes.begin(), + nodes.end(), + [](SceneGraphNode* lhs, SceneGraphNode* rhs) { + return lhs->name() < rhs->name(); + } + ); std::string nodeNames = ""; 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"); + int currentPosition = static_cast(std::distance(iCurrentFocus, nodes.begin())); - int position = static_cast(std::distance(it, nodes.begin())); - - bool result = ImGui::Combo("Origin", &position, nodeNames.c_str()); - - if (result) { - LINFO("openspace.setPropertyValue('Interaction.origin', '" + nodes[position]->name() + "');"); - OsEng.scriptEngine().queueScript("openspace.setPropertyValue('Interaction.origin', '" + nodes[position]->name() + "');"); + bool hasChanged = ImGui::Combo("Origin", ¤tPosition, nodeNames.c_str()); + if (hasChanged) { + OsEng.scriptEngine().queueScript( + "openspace.setPropertyValue('Interaction.origin', '" + + nodes[currentPosition]->name() + "');" + ); } - } } // gui } // openspace - - - // ImGui::Begin("Properties", &_isEnabled, size, 0.5f); - - - // //ImGui::ShowUserGuide(); - // ImGui::Spacing(); - - // for (const auto& p : _propertiesByOwner) { - // if (ImGui::CollapsingHeader(p.first.c_str())) { - // for (properties::Property* prop : p.second) { - // if (_boolProperties.find(prop) != _boolProperties.end()) { - // renderBoolProperty(prop, p.first); - // continue; - // } - - // if (_intProperties.find(prop) != _intProperties.end()) { - // renderIntProperty(prop, p.first); - // continue; - // } - - // if (_floatProperties.find(prop) != _floatProperties.end()) { - // renderFloatProperty(prop, p.first); - // continue; - // } - - // if (_vec2Properties.find(prop) != _vec2Properties.end()) { - // renderVec2Property(prop, p.first); - // continue; - // } - - // if (_vec3Properties.find(prop) != _vec3Properties.end()) { - // renderVec3Property(prop, p.first); - // continue; - // } - - // if (_vec4Properties.find(prop) != _vec4Properties.end()) { - // renderVec4Property(prop, p.first); - // continue; - // } - - // if (_optionProperties.find(prop) != _optionProperties.end()) { - // renderOptionProperty(prop, p.first); - // continue; - // } - - // if (_triggerProperties.find(prop) != _triggerProperties.end()) { - // renderTriggerProperty(prop, p.first); - // continue; - // } - - // if (_selectionProperties.find(prop) != _selectionProperties.end()) { - // renderSelectionProperty(prop, p.first); - // continue; - // } - - // if (_stringProperties.find(prop) != _stringProperties.end()) { - // renderStringProperty(prop, p.first); - // continue; - // } - // } - // } - // } - - //ImGui::End(); -//} -// -//GuiPropertyComponent::PropertyType GuiPropertyComponent::toPropertyType( -// const std::string& name) const -//{ -// if (name == "BoolProperty") -// return PropertyType::BoolProperty; -// if (name == "IntProperty") -// return PropertyType::IntProperty; -// if (name == "FloatProperty") -// return PropertyType::FloatProperty; -// if (name == "Vec2Property") -// return PropertyType::Vec2Property; -// if (name == "Vec3Property") -// return PropertyType::Vec3Property; -// if (name == "StringProperty") -// return PropertyType::StringProperty; -// if (name == "OptionProperty") -// return PropertyType::OptionProperty; -// if (name == "SelectionProperty") -// return PropertyType::SelectionProperty; -// if (name == "TriggerProperty") -// return PropertyType::TriggerProperty; -// -// LWARNING("Unsupported property type '" << name << "'"); -// return PropertyType::InvalidPropertyType; -//} -// -//void GuiPropertyComponent::renderProperty(const PropertyInfo& info) const { -// switch (info.type) { -// case PropertyType::BoolProperty: -// { -// // BoolProperty* p = static_cast(prop); -// // std::string name = p->guiName(); -// -// // BoolProperty::ValueType value = *p; -// // ImGui::Checkbox((ownerName + "." + name).c_str(), &value); -// // p->set(value); -// -// -// -// -// break; -// } -// default: -// LERROR("Missing case statement: {" << int(info.type) << "," << info.identifier << "}"); -// //ghoul_assert(false, "Missing case statement"); -// } -// -//} - diff --git a/modules/onscreengui/src/guiperformancecomponent.cpp b/modules/onscreengui/src/guiperformancecomponent.cpp index 0bd4511ab3..7dcf7e48ed 100644 --- a/modules/onscreengui/src/guiperformancecomponent.cpp +++ b/modules/onscreengui/src/guiperformancecomponent.cpp @@ -32,37 +32,46 @@ #include #include -#include +#include #include #include namespace { const std::string _loggerCat = "GuiPerformanceComponent"; + + enum class Sorting { + NoSorting = -1, + UpdateEphemeris = 0, + UpdateRender = 1, + Render = 2, + Total = 3 + }; } namespace openspace { namespace gui { -void GuiPerformanceComponent::initialize() { - _sortingSelection = -1; - - _sceneGraphIsEnabled = false; - _functionsIsEnabled = false; -} - -void GuiPerformanceComponent::deinitialize() { - delete _performanceMemory; - _performanceMemory = nullptr; -} - void GuiPerformanceComponent::render() { + using ghoul::SharedMemory; using namespace performance; ImGui::Begin("Performance", &_isEnabled); - if (OsEng.renderEngine().doesPerformanceMeasurements() && - ghoul::SharedMemory::exists(PerformanceManager::PerformanceMeasurementSharedData)) - { + if (OsEng.renderEngine().doesPerformanceMeasurements()) { + ghoul_assert( + SharedMemory::exists(PerformanceManager::PerformanceMeasurementSharedData), + "Shared Memory block was not allocated" + ); + + if (!_performanceMemory) { + _performanceMemory = std::make_unique( + PerformanceManager::PerformanceMeasurementSharedData + ); + } + PerformanceLayout* layout = reinterpret_cast( + _performanceMemory->memory() + ); + ImGui::Checkbox("SceneGraph", &_sceneGraphIsEnabled); ImGui::Checkbox("Functions", &_functionsIsEnabled); @@ -77,18 +86,34 @@ void GuiPerformanceComponent::render() { // The indices correspond to the index into the average array further below ImGui::Text("Sorting"); - ImGui::RadioButton("No Sorting", &_sortingSelection, -1); - ImGui::RadioButton("UpdateEphemeris", &_sortingSelection, 0); - ImGui::RadioButton("UpdateRender", &_sortingSelection, 1); - ImGui::RadioButton("RenderTime", &_sortingSelection, 2); - - if (!_performanceMemory) - _performanceMemory = new ghoul::SharedMemory(PerformanceManager::PerformanceMeasurementSharedData); - - void* ptr = _performanceMemory->memory(); - - PerformanceLayout* layout = reinterpret_cast(ptr); + 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); @@ -96,36 +121,44 @@ void GuiPerformanceComponent::render() { // updateEphemeris // UpdateRender // RenderTime - std::vector> averages(layout->nScaleGraphEntries, { 0.f, 0.f, 0.f }); + 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]; - - int v[3] = { 0, 0, 0 }; + const PerformanceLayout::SceneGraphPerformanceLayout& entry = + layout->sceneGraphEntries[i]; + 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) - ++(v[0]); + ++(nValues[0]); averages[i][1] += entry.updateRenderable[j]; if (entry.updateRenderable[j] != 0.f) - ++(v[1]); + ++(nValues[1]); averages[i][2] += entry.renderTime[j]; if (entry.renderTime[j] != 0.f) - ++(v[2]); + ++(nValues[2]); } - if (v[0] != 0) - averages[i][0] /= static_cast(v[0]); - if (v[1] != 0) - averages[i][1] /= static_cast(v[1]); - if (v[2] != 0) - averages[i][2] /= static_cast(v[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) @@ -135,7 +168,6 @@ void GuiPerformanceComponent::render() { *(minmaxEphemeris.second) ); - auto minmaxUpdateRenderable = std::minmax_element( std::begin(entry.updateRenderable), std::end(entry.updateRenderable) @@ -145,7 +177,6 @@ void GuiPerformanceComponent::render() { *(minmaxUpdateRenderable.second) ); - auto minmaxRendering = std::minmax_element( std::begin(entry.renderTime), std::end(entry.renderTime) @@ -157,28 +188,66 @@ void GuiPerformanceComponent::render() { } + + // 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 (_sortingSelection != -1) { - int sortIndex = _sortingSelection; + 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(), - [sortIndex, &averages](size_t a, size_t b) { - return averages[a][sortIndex] > averages[b][sortIndex]; - } + sortFunc ); - } for (int i = 0; i < layout->nScaleGraphEntries; ++i) { - const PerformanceLayout::SceneGraphPerformanceLayout& entry = layout->sceneGraphEntries[indices[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"; - ; + + 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(), + fmt::format( + "UpdateEphemeris\nAverage: {}us", + averages[indices[i]][0] + ).c_str(), &entry.updateEphemeris[0], PerformanceLayout::NumberValues, 0, @@ -188,9 +257,15 @@ void GuiPerformanceComponent::render() { ImVec2(0, 40) ); - std::string updateRenderableTime = std::to_string(entry.updateRenderable[PerformanceLayout::NumberValues - 1]) + "us"; + 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(), + fmt::format( + "UpdateRender\nAverage: {}us", + averages[indices[i]][1] + ).c_str(), &entry.updateRenderable[0], PerformanceLayout::NumberValues, 0, @@ -200,9 +275,15 @@ void GuiPerformanceComponent::render() { ImVec2(0, 40) ); - std::string renderTime = std::to_string(entry.renderTime[PerformanceLayout::NumberValues - 1]) + "us"; + 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(), + fmt::format( + "RenderTime\nAverage: {}us", + averages[indices[i]][2] + ).c_str(), &entry.renderTime[0], PerformanceLayout::NumberValues, 0, @@ -220,15 +301,9 @@ void GuiPerformanceComponent::render() { ImGui::Begin("Functions", &_functionsIsEnabled); using namespace performance; - if (!_performanceMemory) - _performanceMemory = new ghoul::SharedMemory(PerformanceManager::PerformanceMeasurementSharedData); - - void* ptr = _performanceMemory->memory(); - - PerformanceLayout* layout = reinterpret_cast(ptr); - for (int i = 0; i < layout->nFunctionEntries; ++i) { - const PerformanceLayout::FunctionPerformanceLayout& entry = layout->functionEntries[i]; + const PerformanceLayout::FunctionPerformanceLayout& entry = + layout->functionEntries[i]; float avg = 0.f; int count = 0; @@ -244,9 +319,12 @@ void GuiPerformanceComponent::render() { std::end(layout->functionEntries[i].time) ); - const PerformanceLayout::FunctionPerformanceLayout& f = layout->functionEntries[i]; + const PerformanceLayout::FunctionPerformanceLayout& f = + layout->functionEntries[i]; - std::string renderTime = std::to_string(entry.time[PerformanceLayout::NumberValues - 1]) + "us"; + 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], diff --git a/modules/onscreengui/src/guipropertycomponent.cpp b/modules/onscreengui/src/guipropertycomponent.cpp index 30439a3117..8ee91c4ca4 100644 --- a/modules/onscreengui/src/guipropertycomponent.cpp +++ b/modules/onscreengui/src/guipropertycomponent.cpp @@ -23,21 +23,11 @@ ****************************************************************************************/ #include + #include -#include -#include -#include +#include -#include -#include -#include -#include -#include - -#include -#include -#include #include "imgui.h" namespace { @@ -48,406 +38,117 @@ namespace { namespace openspace { namespace gui { -//void GuiPropertyComponent::registerProperty(properties::Property* prop) { - //registerProperty(prop->description()); - //using namespace properties; +GuiPropertyComponent::GuiPropertyComponent(std::string name) + : _name(std::move(name)) +{} - //std::string className = prop->className(); +void GuiPropertyComponent::setSource(SourceFunction function) { + _function = std::move(function); +} - //if (className == "BoolProperty") - // _boolProperties.insert(prop); - //else if (className == "IntProperty") - // _intProperties.insert(prop); - //else if (className == "FloatProperty") - // _floatProperties.insert(prop); - //else if (className == "StringProperty") - // _stringProperties.insert(prop); - //else if (className == "Vec2Property") - // _vec2Properties.insert(prop); - //else if (className == "Vec3Property") - // _vec3Properties.insert(prop); - //else if (className == "OptionProperty") - // _optionProperty.insert(prop); - //else if (className == "TriggerProperty") - // _triggerProperty.insert(prop); - //else if (className == "SelectionProperty") - // _selectionProperty.insert(prop); - //else { - // LWARNING("Class name '" << className << "' not handled in GUI generation"); - // return; - //} - - //std::string fullyQualifiedId = prop->fullyQualifiedIdentifier(); - //size_t pos = fullyQualifiedId.find('.'); - //std::string owner = fullyQualifiedId.substr(0, pos); - - //auto it = _propertiesByOwner.find(owner); - //if (it == _propertiesByOwner.end()) - // _propertiesByOwner[owner] = { prop }; - //else - // it->second.push_back(prop); - -//} - -void GuiPropertyComponent::registerProperty(properties::Property* prop, properties::Property* sibling) { - //void GuiPropertyComponent::registerProperty(const std::string& propertyDescription) { - using namespace properties; - - std::string className = prop->className(); - - if (className == "BoolProperty") - _boolProperties.insert(prop); - else if (className == "IntProperty") - _intProperties.insert(prop); - else if (className == "FloatProperty") - _floatProperties.insert(prop); - else if (className == "StringProperty") - _stringProperties.insert(prop); - else if (className == "Vec2Property") - _vec2Properties.insert(prop); - else if (className == "Vec3Property") - _vec3Properties.insert(prop); - else if (className == "Vec4Property") - _vec4Properties.insert(prop); - else if (className == "OptionProperty") - _optionProperties.insert(prop); - else if (className == "TriggerProperty") - _triggerProperties.insert(prop); - else if (className == "SelectionProperty") - _selectionProperties.insert(prop); - else { - LWARNING("Class name '" << className << "' not handled in GUI generation"); - return; - } - - std::string fullyQualifiedId = prop->fullyQualifiedIdentifier(); - size_t pos = fullyQualifiedId.find('.'); - std::string owner = fullyQualifiedId.substr(0, pos); - - auto it = _propertiesByOwner.find(owner); - if (it == _propertiesByOwner.end()){ - _propertiesByOwner[owner] = { prop }; - } else { - std::vector::iterator position = std::find(it->second.begin(), it->second.end(), sibling); - if (position != it->second.end()){ - it->second.insert(++position, prop); - } else { - it->second.push_back(prop); +void GuiPropertyComponent::renderPropertyOwner(properties::PropertyOwner* owner) { + ImGui::PushID(owner->name().c_str()); + const auto& subOwners = owner->propertySubOwners(); + for (properties::PropertyOwner* subOwner : subOwners) { + if (subOwners.size() == 1) { + renderPropertyOwner(subOwner); } - } - - //ghoul::Dictionary dictionary; - //ghoul::lua::loadDictionaryFromString(propertyDescription, dictionary); - - //handleProperty(dictionary); -} - -void GuiPropertyComponent::unregisterProperty(properties::Property* prop) { - - using namespace properties; - - std::string className = prop->className(); - - if (className == "BoolProperty") - _boolProperties.erase(prop); - else if (className == "IntProperty") - _intProperties.erase(prop); - else if (className == "FloatProperty") - _floatProperties.erase(prop); - else if (className == "StringProperty") - _stringProperties.erase(prop); - else if (className == "Vec2Property") - _vec2Properties.erase(prop); - else if (className == "Vec3Property") - _vec3Properties.erase(prop); - else if (className == "Vec4Property") - _vec4Properties.erase(prop); - else if (className == "OptionProperty") - _optionProperties.erase(prop); - else if (className == "TriggerProperty") - _triggerProperties.erase(prop); - else if (className == "SelectionProperty") - _selectionProperties.erase(prop); - else { - LWARNING("Class name '" << className << "' not handled in GUI generation"); - return; - } - - std::string fullyQualifiedId = prop->fullyQualifiedIdentifier(); - size_t pos = fullyQualifiedId.find('.'); - std::string owner = fullyQualifiedId.substr(0, pos); - - auto it = _propertiesByOwner.find(owner); - if (it == _propertiesByOwner.end()){ - LWARNING("Cannot find owner for " + className); - } - else{ - std::vector::iterator position = std::find(it->second.begin(), it->second.end(), prop); - if (position != it->second.end()) - it->second.erase(position); - } -} - -void GuiPropertyComponent::unregisterProperties(std::string owner){ - auto it = _propertiesByOwner.find(owner); - if(it != _propertiesByOwner.end()){ - for(auto prop : it->second){ - std::string className = prop->className(); - if (className == "BoolProperty") - _boolProperties.erase(prop); - else if (className == "IntProperty") - _intProperties.erase(prop); - else if (className == "FloatProperty") - _floatProperties.erase(prop); - else if (className == "StringProperty") - _stringProperties.erase(prop); - else if (className == "Vec2Property") - _vec2Properties.erase(prop); - else if (className == "Vec3Property") - _vec3Properties.erase(prop); - else if (className == "Vec4Property") - _vec4Properties.erase(prop); - else if (className == "OptionProperty") - _optionProperties.erase(prop); - else if (className == "TriggerProperty") - _triggerProperties.erase(prop); - else if (className == "SelectionProperty") - _selectionProperties.erase(prop); - } - it->second.clear(); - _propertiesByOwner.erase(it); - } -} - -void GuiPropertyComponent::handleProperty(const ghoul::Dictionary& dictionary) { - //static const std::string TypeKey = "Type"; - //static const std::string IdentifierKey = "Identifier"; - //static const std::string NameKey = "Name"; - //static const std::string GroupKey = "MetaData.Group"; - - //ghoul_assert( - // dictionary.hasKeyAndValue(TypeKey), "Missing Type key" - //); - //ghoul_assert( - // dictionary.hasKeyAndValue(IdentifierKey), "Missing Identifier key" - //); - //ghoul_assert( - // dictionary.hasKeyAndValue(NameKey), "Missing Name key" - //); - //ghoul_assert( - // dictionary.hasKeyAndValue(GroupKey), "Missing Group key" - //); - - //std::string typeString = dictionary.value(TypeKey); - //std::string identifier = dictionary.value(IdentifierKey); - //std::string name = dictionary.value(NameKey); - //std::string group = dictionary.value(GroupKey); - - //PropertyType type = toPropertyType(typeString); - // - //size_t pos = identifier.find('.'); - //std::string owner = identifier.substr(0, pos); - - //PropertyInfo info = { type, identifier, name, group }; - - //auto it = std::find_if(_properties.begin(), _properties.end(), - // [owner](const Property& prop) { - // return prop.owner == owner; - //}); - //if (it == _properties.end()) { - // Property p; - // p.owner = owner; - // p.properties = {info}; - // _properties.push_back(p); - //} - //else - // it->properties.push_back(std::move(info)); -} - -void GuiPropertyComponent::render() { - ImGui::Begin("Properties", &_isEnabled, size, 0.5f); - - // if (ImGui::CollapsingHeader("OnScreen GUI")) { - // glm::vec2& pos = OsEng.renderEngine()._onScreenInformation._position; - // Vec2Property::ValueType value = pos; - // ImGui::SliderFloat2("Position", &value.x, -1.f, 1.f); - // pos = value; - - // unsigned int& size = OsEng.renderEngine()._onScreenInformation._size; - // int sizeValue = static_cast(size); - // ImGui::SliderInt("Size", &sizeValue, 0, 36); - // size = static_cast(sizeValue); - - // int& node = OsEng.renderEngine()._onScreenInformation._node; - // int iValue = node; - // ImGui::SliderInt("Node#", &iValue, 0, 30); - // node = iValue; - // } - - ImGui::Spacing(); - - for (const auto& p : _propertiesByOwner) { - if (ImGui::CollapsingHeader(p.first.c_str())) { - for (properties::Property* prop : p.second) { - if (_boolProperties.find(prop) != _boolProperties.end()) { - renderBoolProperty(prop, p.first); - continue; - } - - if (_intProperties.find(prop) != _intProperties.end()) { - renderIntProperty(prop, p.first); - continue; - } - - if (_floatProperties.find(prop) != _floatProperties.end()) { - renderFloatProperty(prop, p.first); - continue; - } - - if (_vec2Properties.find(prop) != _vec2Properties.end()) { - renderVec2Property(prop, p.first); - continue; - } - - if (_vec3Properties.find(prop) != _vec3Properties.end()) { - renderVec3Property(prop, p.first); - continue; - } - - if (_vec4Properties.find(prop) != _vec4Properties.end()) { - renderVec4Property(prop, p.first); - continue; - } - - if (_optionProperties.find(prop) != _optionProperties.end()) { - renderOptionProperty(prop, p.first); - continue; - } - - if (_triggerProperties.find(prop) != _triggerProperties.end()) { - renderTriggerProperty(prop, p.first); - continue; - } - - if (_selectionProperties.find(prop) != _selectionProperties.end()) { - renderSelectionProperty(prop, p.first); - continue; - } - - if (_stringProperties.find(prop) != _stringProperties.end()) { - renderStringProperty(prop, p.first); - continue; - } + else { + if (ImGui::TreeNode(subOwner->name().c_str())) { + renderPropertyOwner(subOwner); + ImGui::TreePop(); } } } - //for (const Property& prop : _properties) { - // if (ImGui::CollapsingHeader(prop.owner.c_str())) { - // for (const PropertyInfo& info : prop.properties) { - // renderProperty(info); - // } - // } - // } + ImGui::Spacing(); + using Properties = std::vector; + std::map propertiesByGroup; + Properties remainingProperies; + for (properties::Property* p : owner->properties()) { + std::string group = p->groupIdentifier(); + if (group.empty()) { + remainingProperies.push_back(p); + } + else { + propertiesByGroup[group].push_back(p); + } + } - //for (const auto& p : _propertiesByOwner) { - // if (ImGui::CollapsingHeader(p.first.c_str())) { - // for (properties::Property* prop : p.second) { - // if (_boolProperties.find(prop) != _boolProperties.end()) { - // renderBoolProperty(prop, p.first); - // continue; - // } + for (const std::pair& p : propertiesByGroup) { + if (ImGui::TreeNode(p.first.c_str())) { + for (properties::Property* prop : p.second) { + renderProperty(prop, owner); + } + ImGui::TreePop(); + } + } - // if (_intProperties.find(prop) != _intProperties.end()) { - // renderIntProperty(prop, p.first); - // continue; - // } + ImGui::Spacing(); - // if (_floatProperties.find(prop) != _floatProperties.end()) { - // renderFloatProperty(prop, p.first); - // continue; - // } + for (properties::Property* prop : remainingProperies) { + if (prop->isVisible()) { + renderProperty(prop, owner); + } + } + ImGui::PopID(); +} - // if (_vec2Properties.find(prop) != _vec2Properties.end()) { - // renderVec2Property(prop, p.first); - // continue; - // } +void GuiPropertyComponent::render() { + ImGui::Begin(_name.c_str(), &_isEnabled, size, 0.5f); - // if (_vec3Properties.find(prop) != _vec3Properties.end()) { - // renderVec3Property(prop, p.first); - // continue; - // } + ImGui::Spacing(); - // if (_optionProperty.find(prop) != _optionProperty.end()) { - // renderOptionProperty(prop, p.first); - // continue; - // } + if (_function) { + const std::vector& owners = _function(); - // if (_triggerProperty.find(prop) != _triggerProperty.end()) { - // renderTriggerProperty(prop, p.first); - // continue; - // } + for (properties::PropertyOwner* pOwner : owners) { + if (pOwner->propertiesRecursive().empty()) + continue; - // if (_selectionProperty.find(prop) != _selectionProperty.end()) { - // renderSelectionProperty(prop, p.first); - // continue; - // } - // } - // } - //} + auto header = [&]() -> bool { + if (owners.size() > 1) { + // Create a header in case we have multiple owners + return ImGui::CollapsingHeader(pOwner->name().c_str()); + } + else { + // Otherwise, do nothing + ImGui::Text(pOwner->name().c_str()); + ImGui::Spacing(); + return true; + } + }; + + if (header()) { + renderPropertyOwner(pOwner); + } + } + } ImGui::End(); } -GuiPropertyComponent::PropertyType GuiPropertyComponent::toPropertyType( - const std::string& name) const -{ - if (name == "BoolProperty") - return PropertyType::BoolProperty; - if (name == "IntProperty") - return PropertyType::IntProperty; - if (name == "FloatProperty") - return PropertyType::FloatProperty; - if (name == "Vec2Property") - return PropertyType::Vec2Property; - if (name == "Vec3Property") - return PropertyType::Vec3Property; - if (name == "StringProperty") - return PropertyType::StringProperty; - if (name == "OptionProperty") - return PropertyType::OptionProperty; - if (name == "SelectionProperty") - return PropertyType::SelectionProperty; - if (name == "TriggerProperty") - return PropertyType::TriggerProperty; - - LWARNING("Unsupported property type '" << name << "'"); - return PropertyType::InvalidPropertyType; -} - -void GuiPropertyComponent::renderProperty(const PropertyInfo& info) const { - switch (info.type) { - case PropertyType::BoolProperty: - { - // BoolProperty* p = static_cast(prop); - // std::string name = p->guiName(); - - // BoolProperty::ValueType value = *p; - // ImGui::Checkbox((ownerName + "." + name).c_str(), &value); - // p->set(value); - - - - - break; - } - default: - LERROR("Missing case statement: {" << int(info.type) << "," << info.identifier << "}"); - //ghoul_assert(false, "Missing case statement"); - } +void GuiPropertyComponent::renderProperty(properties::Property* prop, properties::PropertyOwner* owner) { + using Func = std::function; + static std::map FunctionMapping = { + { "BoolProperty", &renderBoolProperty }, + { "IntProperty", &renderIntProperty }, + { "FloatProperty", &renderFloatProperty }, + { "Vec2Property", &renderVec2Property }, + { "Vec3Property", &renderVec3Property }, + { "Vec4Property", &renderVec4Property }, + { "StringProperty", &renderStringProperty }, + { "OptionProperty", &renderOptionProperty }, + { "TriggerProperty", &renderTriggerProperty }, + { "SelectionProperty", &renderSelectionProperty } + }; + auto it = FunctionMapping.find(prop->className()); + if (it != FunctionMapping.end()) { + it->second(prop, owner->name()); + } } } // gui diff --git a/modules/onscreengui/src/guitimecomponent.cpp b/modules/onscreengui/src/guitimecomponent.cpp index 3222665d23..6c71d1c6d3 100644 --- a/modules/onscreengui/src/guitimecomponent.cpp +++ b/modules/onscreengui/src/guitimecomponent.cpp @@ -27,13 +27,8 @@ #include #include -#include #include "imgui.h" -namespace { - const std::string _loggerCat = "GuiTimeComponent"; -} - namespace openspace { namespace gui { @@ -41,37 +36,11 @@ void GuiTimeComponent::render() { float deltaTime = static_cast(Time::ref().deltaTime()); bool changed = ImGui::SliderFloat("Delta Time", &deltaTime, -500000.f, 500000.f); - if (changed) - OsEng.scriptEngine().queueScript("openspace.time.setDeltaTime(" + std::to_string(deltaTime) + ")"); - - - //char dateBuffer[512] = {}; - //ImGui::InputText("Date", dateBuffer, 512); - //bool pressed = ImGui::Button("Set Date"); - //if (pressed) - // OsEng.scriptEngine()->queueScript("openspace.time.setTime('" + std::string(dateBuffer) + "')"); - - //const SceneGraphNode* currentFocus = OsEng.interactionHandler()->focusNode(); - - //std::vector nodes = OsEng.renderEngine()->sceneGraph()->allSceneGraphNodes(); - //std::sort(nodes.begin(), nodes.end(), [](SceneGraphNode* lhs, SceneGraphNode* rhs) { return lhs->name() < rhs->name(); }); - //auto it = std::find(nodes.begin(), nodes.end(), currentFocus); - //ghoul_assert(it != nodes.end(), "Focus node not found"); - - //std::string nodeNames = ""; - //for (SceneGraphNode* n : nodes) - // nodeNames += n->name() + '\0'; - - - //int position = it - nodes.begin(); - - //bool result = ImGui::Combo("Origin", &position, nodeNames.c_str()); - - //if (result) { - // LINFO("openspace.setOrigin('" + nodes[position]->name() + "');"); - // OsEng.scriptEngine()->queueScript("openspace.setOrigin('" + nodes[position]->name() + "');"); - //} - + if (changed) { + OsEng.scriptEngine().queueScript( + "openspace.time.setDeltaTime(" + std::to_string(deltaTime) + ")" + ); + } } } // gui diff --git a/modules/onscreengui/src/renderproperties.cpp b/modules/onscreengui/src/renderproperties.cpp index 0f8f0b9901..7ae57786cf 100644 --- a/modules/onscreengui/src/renderproperties.cpp +++ b/modules/onscreengui/src/renderproperties.cpp @@ -21,293 +21,253 @@ * 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 "imgui.h" +namespace openspace { -using namespace openspace::properties; +using namespace properties; - void executeScript(const std::string& id, const std::string& value) { - std::string script = - "openspace.setPropertyValue('" + id + "', " + value + ");"; - OsEng.scriptEngine().queueScript(script); +void renderTooltip(Property* prop) { + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip(prop->fullyQualifiedIdentifier().c_str()); } +} - void renderBoolProperty(Property* prop, const std::string& ownerName) { - BoolProperty* p = static_cast(prop); - std::string name = p->guiName(); - ImGui::PushID((ownerName + "." + name).c_str()); +void executeScript(const std::string& id, const std::string& value) { + std::string script = + "openspace.setPropertyValue('" + id + "', " + value + ");"; + OsEng.scriptEngine().queueScript(script); +} - BoolProperty::ValueType value = *p; - ImGui::Checkbox(name.c_str(), &value); +void renderBoolProperty(Property* prop, const std::string& ownerName) { + BoolProperty* p = static_cast(prop); + std::string name = p->guiName(); + ImGui::PushID((ownerName + "." + name).c_str()); + + BoolProperty::ValueType value = *p; + ImGui::Checkbox(name.c_str(), &value); + renderTooltip(prop); + + if (value != p->value()) + executeScript(p->fullyQualifiedIdentifier(), value ? "true" : "false"); + ImGui::PopID(); +} + +void renderOptionProperty(Property* prop, const std::string& ownerName) { + OptionProperty* p = static_cast(prop); + std::string name = p->guiName(); + ImGui::PushID((ownerName + "." + name).c_str()); + + int value = *p; + std::vector options = p->options(); + for (const OptionProperty::Option& o : options) { + ImGui::RadioButton(name.c_str(), &value, o.value); + + ImGui::SameLine(); + ImGui::Text(o.description.c_str()); + renderTooltip(prop); - if (value != p->value()) - executeScript(p->fullyQualifiedIdentifier(), value ? "true": "false"); - ImGui::PopID(); } + if (value != p->value()) + executeScript(p->fullyQualifiedIdentifier(), std::to_string(value)); + ImGui::PopID(); +} - void renderOptionProperty(Property* prop, const std::string& ownerName) { - OptionProperty* p = static_cast(prop); - std::string name = p->guiName(); - ImGui::PushID((ownerName + "." + name).c_str()); +void renderSelectionProperty(Property* prop, const std::string& ownerName) { + SelectionProperty* p = static_cast(prop); + std::string name = p->guiName(); + ImGui::PushID((ownerName + "." + name).c_str()); - int value = *p; - std::vector options = p->options(); - for (const OptionProperty::Option& o : options) { - ImGui::RadioButton(name.c_str(), &value, o.value); - ImGui::SameLine(); - ImGui::Text(o.description.c_str()); + if (ImGui::TreeNode(name.c_str())) { + const std::vector& options = p->options(); + std::vector newSelectedIndices; + + std::vector selectedIndices = p->value(); + + for (int i = 0; i < options.size(); ++i) { + std::string description = options[i].description; + bool selected = std::find( + selectedIndices.begin(), selectedIndices.end(), i + ) != selectedIndices.end(); + + ImGui::Checkbox(description.c_str(), &selected); + renderTooltip(prop); + + if (selected) + newSelectedIndices.push_back(i); } - if (value != p->value()) - executeScript(p->fullyQualifiedIdentifier(), std::to_string(value)); - ImGui::PopID(); - } - void renderSelectionProperty(Property* prop, const std::string& ownerName) { - SelectionProperty* p = static_cast(prop); - std::string name = p->guiName(); - ImGui::PushID((ownerName + "." + name).c_str()); - - if (ImGui::CollapsingHeader(name.c_str())) { - const std::vector& options = p->options(); - std::vector newSelectedIndices; - - std::vector selectedIndices = p->value(); - - for (int i = 0; i < options.size(); ++i) { - std::string description = options[i].description; - bool selected = std::find(selectedIndices.begin(), selectedIndices.end(), i) != selectedIndices.end(); - ImGui::Checkbox(description.c_str(), &selected); - - if (selected) - newSelectedIndices.push_back(i); - } - - if (newSelectedIndices != p->value()) { - std::string parameters = "{"; - for (int i : newSelectedIndices) - parameters += std::to_string(i) + ","; - parameters += "}"; - executeScript(p->fullyQualifiedIdentifier(), parameters); - } + if (newSelectedIndices != p->value()) { + std::string parameters = "{"; + for (int i : newSelectedIndices) + parameters += std::to_string(i) + ","; + parameters += "}"; + executeScript(p->fullyQualifiedIdentifier(), parameters); } - ImGui::PopID(); + ImGui::TreePop(); } + ImGui::PopID(); +} - void renderStringProperty(Property* prop, const std::string& ownerName) { - StringProperty* p = static_cast(prop); - std::string name = p->guiName(); - ImGui::PushID((ownerName + "." + name).c_str()); +void renderStringProperty(Property* prop, const std::string& ownerName) { + StringProperty* p = static_cast(prop); + std::string name = p->guiName(); + ImGui::PushID((ownerName + "." + name).c_str()); - static const int bufferSize = 256; - static char buffer[bufferSize]; + 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, p->value().length() + 1, p->value().c_str()); #else - strcpy(buffer, p->value().c_str()); + strcpy(buffer, p->value().c_str()); #endif - ImGui::InputText(name.c_str(), buffer, bufferSize); - std::string newValue(buffer); + ImGui::InputText(name.c_str(), buffer, bufferSize); + renderTooltip(prop); - if (newValue != p->value() && FileSys.fileExists(newValue)) - executeScript(p->fullyQualifiedIdentifier(), "'" + newValue + "'"); + std::string newValue(buffer); - ImGui::PopID(); + if (newValue != p->value()) + executeScript(p->fullyQualifiedIdentifier(), "'" + newValue + "'"); + + ImGui::PopID(); +} + +void renderIntProperty(Property* prop, const std::string& ownerName) { + IntProperty* p = static_cast(prop); + std::string name = p->guiName(); + ImGui::PushID((ownerName + "." + name).c_str()); + + IntProperty::ValueType value = *p; + int min = p->minValue(); + int max = p->maxValue(); + + ImGui::SliderInt(name.c_str(), &value, min, max); + renderTooltip(prop); + + if (value != p->value()) + executeScript(p->fullyQualifiedIdentifier(), std::to_string(value)); + + ImGui::PopID(); +} + +void renderFloatProperty(Property* prop, const std::string& ownerName) { + FloatProperty* p = static_cast(prop); + std::string name = p->guiName(); + ImGui::PushID((ownerName + "." + name).c_str()); + + FloatProperty::ValueType value = *p; + float min = p->minValue(); + float max = p->maxValue(); + ImGui::SliderFloat(name.c_str(), &value, min, max); + renderTooltip(prop); + + if (value != p->value()) + executeScript(p->fullyQualifiedIdentifier(), std::to_string(value)); + + ImGui::PopID(); +} + +void renderVec2Property(Property* prop, const std::string& ownerName) { + Vec2Property* p = static_cast(prop); + std::string name = p->guiName(); + ImGui::PushID((ownerName + "." + name).c_str()); + + Vec2Property::ValueType value = *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 (value != p->value()) { + executeScript(p->fullyQualifiedIdentifier(), + "{" + std::to_string(value.x) + "," + std::to_string(value.y) + "}" + ); } - void renderIntProperty(Property* prop, const std::string& ownerName) { - IntProperty* p = static_cast(prop); - std::string name = p->guiName(); - ImGui::PushID((ownerName + "." + name).c_str()); + ImGui::PopID(); +} - IntProperty::ValueType value = *p; - ImGui::SliderInt(name.c_str(), &value, p->minValue(), p->maxValue()); +void renderVec3Property(Property* prop, const std::string& ownerName) { + Vec3Property* p = static_cast(prop); + std::string name = p->guiName(); + ImGui::PushID((ownerName + "." + name).c_str()); - if (value != p->value()) - executeScript(p->fullyQualifiedIdentifier(), std::to_string(value)); - - ImGui::PopID(); - } + Vec3Property::ValueType value = *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); - void renderFloatProperty(Property* prop, const std::string& ownerName) { - FloatProperty* p = static_cast(prop); - std::string name = p->guiName(); - ImGui::PushID((ownerName + "." + name).c_str()); + ImGui::SliderFloat3( + name.c_str(), + &value.x, + min, + max + ); + renderTooltip(prop); - FloatProperty::ValueType value = *p; - ImGui::SliderFloat(name.c_str(), &value, p->minValue(), p->maxValue()); + 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)); - - ImGui::PopID(); - } + ImGui::PopID(); +} - void renderVec2Property(Property* prop, const std::string& ownerName) { - Vec2Property* p = static_cast(prop); - std::string name = p->guiName(); - ImGui::PushID((ownerName + "." + name).c_str()); +void renderVec4Property(Property* prop, const std::string& ownerName) { + Vec4Property* p = static_cast(prop); + std::string name = p->guiName(); + ImGui::PushID((ownerName + "." + name).c_str()); - Vec2Property::ValueType value = *p; + Vec4Property::ValueType value = *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::SliderFloat2(name.c_str(), &value.x, std::min(p->minValue().x, p->minValue().y), std::max(p->maxValue().x, p->maxValue().y)); + ImGui::SliderFloat4( + 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) + "}"); - - ImGui::PopID(); - } + 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) + "}"); - void renderVec3Property(Property* prop, const std::string& ownerName) { - Vec3Property* p = static_cast(prop); - std::string name = p->guiName(); - ImGui::PushID((ownerName + "." + name).c_str()); + ImGui::PopID(); +} - Vec3Property::ValueType value = *p; +void renderTriggerProperty(Property* prop, const std::string& ownerName) { + std::string name = prop->guiName(); + ImGui::PushID((ownerName + "." + name).c_str()); - ImGui::SliderFloat3(name.c_str(), &value.x, p->minValue().x, p->maxValue().x); + bool pressed = ImGui::Button(name.c_str()); + if (pressed) + executeScript(prop->fullyQualifiedIdentifier(), "nil"); + renderTooltip(prop); - if (value != p->value()) - executeScript(p->fullyQualifiedIdentifier(), - "{" + std::to_string(value.x) + "," + - std::to_string(value.y) + "," + - std::to_string(value.z) + "}"); - - ImGui::PopID(); - } + ImGui::PopID(); +} - void renderVec4Property(Property* prop, const std::string& ownerName) { - Vec4Property* p = static_cast(prop); - std::string name = p->guiName(); - ImGui::PushID((ownerName + "." + name).c_str()); - - Vec4Property::ValueType value = *p; - - ImGui::SliderFloat4(name.c_str(), &value.x, p->minValue().x, p->maxValue().x); - - 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 renderTriggerProperty(Property* prop, const std::string& ownerName) { - std::string name = prop->guiName(); - ImGui::PushID((ownerName + "." + name).c_str()); - - bool pressed = ImGui::Button(name.c_str()); - if (pressed) - executeScript(prop->fullyQualifiedIdentifier(), "nil"); - - ImGui::PopID(); - } - -//void renderBoolProperty(Property* prop, const std::string& ownerName) { -// BoolProperty* p = static_cast(prop); -// std::string name = p->guiName(); - -// BoolProperty::ValueType value = *p; -// ImGui::Checkbox(name.c_str(), &value); -// p->set(value); -//} - -//void renderOptionProperty(Property* prop, const std::string& ownerName) { -// OptionProperty* p = static_cast(prop); -// std::string name = p->guiName(); - -// int value = *p; -// std::vector options = p->options(); -// for (const OptionProperty::Option& o : options) { -// ImGui::RadioButton(name.c_str(), &value, o.value); -// ImGui::SameLine(); -// ImGui::Text(o.description.c_str()); -// } -// p->set(value); -//} - -//void renderSelectionProperty(Property* prop, const std::string& ownerName) { -// SelectionProperty* p = static_cast(prop); -// std::string name = p->guiName(); - -// if (ImGui::CollapsingHeader(name.c_str())) { -// const std::vector& options = p->options(); -// std::vector newSelectedIndices; - -// std::vector selectedIndices = p->value(); - -// for (int i = 0; i < options.size(); ++i) { -// std::string description = options[i].description; -// bool selected = std::find(selectedIndices.begin(), selectedIndices.end(), i) != selectedIndices.end(); -// ImGui::Checkbox(description.c_str(), &selected); - -// if (selected) -// newSelectedIndices.push_back(i); -// } - -// p->setValue(std::move(newSelectedIndices)); -// } -//} - -//void renderIntProperty(Property* prop, const std::string& ownerName) { -// IntProperty* p = static_cast(prop); -// std::string name = p->guiName(); - -// IntProperty::ValueType value = *p; -// ImGui::SliderInt(name.c_str(), &value, p->minValue(), p->maxValue()); -// p->set(value); -//} - -//void renderFloatProperty(Property* prop, const std::string& ownerName) { -// FloatProperty* p = static_cast(prop); -// std::string name = p->guiName(); - -// FloatProperty::ValueType value = *p; -// ImGui::SliderFloat(name.c_str(), &value, p->minValue(), p->maxValue()); -// p->set(value); -//} - -//void renderVec2Property(Property* prop, const std::string& ownerName) { -// Vec2Property* p = static_cast(prop); -// std::string name = p->guiName(); - -// Vec2Property::ValueType value = *p; - -// ImGui::SliderFloat2(name.c_str(), &value.x, p->minValue().x, p->maxValue().x); -// p->set(value); -//} - - -//void renderVec3Property(Property* prop, const std::string& ownerName) { -// Vec3Property* p = static_cast(prop); -// std::string name = p->guiName(); - -// Vec3Property::ValueType value = *p; - -// ImGui::SliderFloat3(name.c_str(), &value.x, p->minValue().x, p->maxValue().x); -// p->set(value); -//} - -//void renderTriggerProperty(Property* prop, const std::string& ownerName) { -// std::string name = prop->guiName(); -// bool pressed = ImGui::Button(name.c_str()); -// if (pressed) -// prop->set(0); -//} \ No newline at end of file +} // namespace openspace diff --git a/openspace.cfg b/openspace.cfg index 87cb583903..5f0ac5e37d 100644 --- a/openspace.cfg +++ b/openspace.cfg @@ -8,10 +8,8 @@ return { -- Sets the scene that is to be loaded by OpenSpace. A scene file is a description -- of all entities that will be visible during an instance of OpenSpace -- Scene = "${SCENE}/default-moon.scene", - -- Scene = "${SCENE}/default_nh.scene", - -- Scene = "${SCENE}/default.scene", - Scene = "${SCENE}/globebrowsing.scene", - -- Scene = "${SCENE}/default-modified.scene", + Scene = "${SCENE}/default.scene", + -- Scene = "${SCENE}/globebrowsing.scene", -- Scene = "${SCENE}/rosetta.scene", -- Scene = "${SCENE}/dawn.scene", -- Scene = "${SCENE}/newhorizons.scene", @@ -53,6 +51,10 @@ return { Type = "text", File = "${BASE_PATH}/Properties.txt" }, + ScriptLogFile = { + Type = "text", + File = "${BASE_PATH}/ScriptLog.txt" + }, DownloadRequestURL = "http://openspace.itn.liu.se/request.cgi", RenderingMethod = "Framebuffer" --RenderingMethod = "ABuffer" -- alternative: "Framebuffer" diff --git a/scripts/bind_keys.lua b/scripts/bind_keys.lua index be68aeff20..3dba610ecf 100644 --- a/scripts/bind_keys.lua +++ b/scripts/bind_keys.lua @@ -16,3 +16,9 @@ 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/common.lua b/scripts/common.lua index cef02c1794..7861bbf263 100644 --- a/scripts/common.lua +++ b/scripts/common.lua @@ -16,6 +16,9 @@ helper.setCommonKeys = function() openspace.bindKey("COMMA", "openspace.setRenderer('Framebuffer');") openspace.bindKey("PERIOD", "openspace.setRenderer('ABuffer');") + + openspace.bindKey("f", helper.property.invert('Interaction.rotationalFriction')) + openspace.bindKey("Shift+f", helper.property.invert('Interaction.zoomFriction')) end helper.setDeltaTimeKeys = function(t) diff --git a/shaders/PowerScaling/powerScaling_fs.hglsl b/shaders/PowerScaling/powerScaling_fs.hglsl index ba2442ebcf..855c98707a 100644 --- a/shaders/PowerScaling/powerScaling_fs.hglsl +++ b/shaders/PowerScaling/powerScaling_fs.hglsl @@ -53,11 +53,7 @@ float pscDepth(vec4 position) { // For now: simply convert power scaled coordinates to a linear scale. // TODO: get rid of power scaled coordinates and use scale graph instead. // return (position.w + log(abs(position.z) + 1/pow(k, position.w))/log(k)) / 27.0; - if (position.z < 0) { - return safeLength(pscToLinear(position)); - } else { - return -safeLength(pscToLinear(position)); - } + return safeLength(pscToLinear(position)); } diff --git a/shaders/framebuffer/resolveframebuffer.vert b/shaders/framebuffer/resolveframebuffer.vert index d069c8affe..91fd0e9223 100644 --- a/shaders/framebuffer/resolveframebuffer.vert +++ b/shaders/framebuffer/resolveframebuffer.vert @@ -25,9 +25,15 @@ #version __CONTEXT__ in vec4 position; + out vec2 texCoord; +out vec3 vPosition; +out vec4 worldPosition; void main() { gl_Position = position; texCoord = 0.5 + position.xy / 2.0; + + vPosition = position.xyz; + worldPosition = position; } diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index f580bcd61d..f65d6e4b36 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -30,6 +30,7 @@ set(OPENSPACE_SOURCE ${OPENSPACE_BASE_DIR}/src/engine/moduleengine.cpp ${OPENSPACE_BASE_DIR}/src/engine/moduleengine_lua.inl ${OPENSPACE_BASE_DIR}/src/engine/openspaceengine.cpp + ${OPENSPACE_BASE_DIR}/src/engine/settingsengine.cpp ${OPENSPACE_BASE_DIR}/src/engine/wrapper/sgctwindowwrapper.cpp ${OPENSPACE_BASE_DIR}/src/engine/wrapper/windowwrapper.cpp ${OPENSPACE_BASE_DIR}/src/interaction/controller.cpp @@ -105,6 +106,7 @@ set(OPENSPACE_HEADER ${OPENSPACE_BASE_DIR}/include/openspace/engine/logfactory.h ${OPENSPACE_BASE_DIR}/include/openspace/engine/moduleengine.h ${OPENSPACE_BASE_DIR}/include/openspace/engine/openspaceengine.h + ${OPENSPACE_BASE_DIR}/include/openspace/engine/settingsengine.h ${OPENSPACE_BASE_DIR}/include/openspace/engine/wrapper/sgctwindowwrapper.h ${OPENSPACE_BASE_DIR}/include/openspace/engine/wrapper/windowwrapper.h ${OPENSPACE_BASE_DIR}/include/openspace/interaction/controller.h diff --git a/src/engine/configurationmanager.cpp b/src/engine/configurationmanager.cpp index f868aa5316..55211d1074 100644 --- a/src/engine/configurationmanager.cpp +++ b/src/engine/configurationmanager.cpp @@ -45,6 +45,8 @@ const string ConfigurationManager::KeyFonts = "Fonts"; const string ConfigurationManager::KeyConfigSgct = "SGCTConfig"; const string ConfigurationManager::KeyLuaDocumentationType = "LuaDocumentationFile.Type"; const string ConfigurationManager::KeyLuaDocumentationFile = "LuaDocumentationFile.File"; +const string ConfigurationManager::KeyScriptLogType = "ScriptLogFile.Type"; +const string ConfigurationManager::KeyScriptLogFile = "ScriptLogFile.File"; const string ConfigurationManager::KeyPropertyDocumentationType = "PropertyDocumentationFile.Type"; const string ConfigurationManager::KeyPropertyDocumentationFile = diff --git a/src/engine/downloadmanager.cpp b/src/engine/downloadmanager.cpp index fdd46eaf49..623d0f2089 100644 --- a/src/engine/downloadmanager.cpp +++ b/src/engine/downloadmanager.cpp @@ -160,9 +160,9 @@ std::shared_ptr DownloadManager::downloadFile( return nullptr; std::shared_ptr future = std::make_shared(file.filename()); - errno = 0; + errno = 0; FILE* fp = fopen(file.path().c_str(), "wb"); // write binary - ghoul_assert(fp != nullptr, "Could not open/create file:\n" << file.path().c_str() << " \nerrno: " << errno); + ghoul_assert(fp != nullptr, "Could not open/create file:\n" << file.path().c_str() << " \nerrno: " << errno); //LDEBUG("Start downloading file: '" << url << "' into file '" << file.path() << "'"); @@ -293,7 +293,7 @@ std::vector> DownloadManager::downl LDEBUG("Request File: " << requestFile); bool isFinished = false; - auto callback = [&futures, destination, &progressCallback, &isFinished, requestFile, overrideFiles](const FileFuture& f) { + auto callback = [&](const FileFuture& f) { LDEBUG("Finished: " << requestFile); std::ifstream temporary(requestFile); std::string line; @@ -310,7 +310,7 @@ std::vector> DownloadManager::downl LDEBUG("\tLine: " << line << " ; Dest: " << destination.path() + "/" + file); - std::shared_ptr future = DlManager.downloadFile( + std::shared_ptr future = downloadFile( line, destination.path() + "/" + file, overrideFiles, @@ -350,8 +350,11 @@ void DownloadManager::downloadRequestFilesAsync(const std::string& identifier, }; if (_useMultithreadedDownload) { + using namespace ghoul::thread; std::thread t = std::thread(downloadFunction); - ghoul::thread::setPriority(t, ghoul::thread::ThreadPriority::Lowest); + ghoul::thread::setPriority( + t, ThreadPriorityClass::Idle, ThreadPriorityLevel::Lowest + ); t.detach(); } else @@ -386,16 +389,11 @@ void DownloadManager::getFileExtension(const std::string& url, } }; if (_useMultithreadedDownload) { + using namespace ghoul::thread; std::thread t = std::thread(requestFunction); - -#ifdef WIN32 - std::thread::native_handle_type h = t.native_handle(); - SetPriorityClass(h, IDLE_PRIORITY_CLASS); - SetThreadPriority(h, THREAD_PRIORITY_LOWEST); -#else - // TODO: Implement thread priority ---abock -#endif - + ghoul::thread::setPriority( + t, ThreadPriorityClass::Idle, ThreadPriorityLevel::Lowest + ); t.detach(); } else { diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index 305450fe5e..2cf8464123 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -69,6 +70,7 @@ #endif #ifdef OPENSPACE_MODULE_ISWA_ENABLED +#include #include #endif @@ -109,6 +111,10 @@ namespace { namespace openspace { +namespace properties { + class Property; +} + OpenSpaceEngine* OpenSpaceEngine::_engine = nullptr; OpenSpaceEngine::OpenSpaceEngine(std::string programName, @@ -123,6 +129,8 @@ OpenSpaceEngine::OpenSpaceEngine(std::string programName, )) , _console(new LuaConsole) , _moduleEngine(new ModuleEngine) + , _settingsEngine(new SettingsEngine) + , _downloadManager(nullptr) #ifdef OPENSPACE_MODULE_ONSCREENGUI_ENABLED , _gui(new gui::GUI) #endif @@ -135,6 +143,7 @@ OpenSpaceEngine::OpenSpaceEngine(std::string programName, { _interactionHandler->setPropertyOwner(_globalPropertyNamespace.get()); _globalPropertyNamespace->addPropertySubOwner(_interactionHandler.get()); + _globalPropertyNamespace->addPropertySubOwner(_settingsEngine.get()); FactoryManager::initialize(); FactoryManager::ref().addFactory( std::make_unique>() @@ -165,6 +174,7 @@ OpenSpaceEngine::~OpenSpaceEngine() { _commandlineParser = nullptr; _console = nullptr; _moduleEngine = nullptr; + _settingsEngine = nullptr; #ifdef OPENSPACE_MODULE_ONSCREENGUI_ENABLED _gui = nullptr; #endif @@ -355,8 +365,9 @@ bool OpenSpaceEngine::initialize() { std::string requestURL = ""; bool success = configurationManager().getValue(ConfigurationManager::KeyDownloadRequestURL, requestURL); - if (success) - DownloadManager::initialize(requestURL, DownloadVersion); + if (success) { + _downloadManager = std::make_unique(requestURL, DownloadVersion); + } // Load SPICE time kernel success = loadSpiceKernels(); @@ -429,6 +440,48 @@ bool OpenSpaceEngine::initialize() { #ifdef OPENSPACE_MODULE_ONSCREENGUI_ENABLED LINFO("Initializing GUI"); _gui->initialize(); + _gui->_globalProperty.setSource( + [&]() { + std::vector res = { + _settingsEngine.get(), + _interactionHandler.get() + }; + return res; + } + ); + + OsEng.gui()._screenSpaceProperty.setSource( + [&]() { + const auto& ssr = renderEngine().screenSpaceRenderables(); + return std::vector(ssr.begin(), ssr.end()); + } + ); + + OsEng.gui()._property.setSource( + [&]() { + const auto& nodes = renderEngine().scene()->allSceneGraphNodes(); + return std::vector(nodes.begin(), nodes.end()); + } + ); + +#ifdef OPENSPACE_MODULE_ISWA_ENABLED + OsEng.gui()._iswa.setSource( + [&]() { + const auto& groups = IswaManager::ref().groups(); + std::vector res; + std::transform( + groups.begin(), + groups.end(), + std::back_inserter(res), + [](const auto& val) { + return val.second.get(); + } + ); + return res; + } + ); +#endif + #endif #ifdef OPENSPACE_MODULE_ISWA_ENABLED @@ -761,15 +814,19 @@ void OpenSpaceEngine::postSynchronizationPreDraw() { LogMgr.resetMessageCounters(); } -void OpenSpaceEngine::render(const glm::mat4 &projectionMatrix, const glm::mat4 &viewMatrix) { - _renderEngine->render(projectionMatrix, viewMatrix); +void OpenSpaceEngine::render(const glm::mat4& projectionMatrix, const glm::mat4& viewMatrix) { + bool showGui = _windowWrapper->hasGuiWindow() ? _windowWrapper->isGuiWindow() : true; + + _renderEngine->render(projectionMatrix, viewMatrix, showGui); if (_isMaster && _windowWrapper->isRegularRendering()) { - if (_console->isVisible()) + if (showGui) { + if (_console->isVisible()) _console->render(); #ifdef OPENSPACE_MODULE_ONSCREENGUI_ENABLED - if (_gui->isEnabled()) - _gui->endFrame(); + if (_gui->isEnabled()) + _gui->endFrame(); + } #endif } } @@ -951,4 +1008,10 @@ ghoul::fontrendering::FontManager& OpenSpaceEngine::fontManager() { return *_fontManager; } +DownloadManager& OpenSpaceEngine::downloadManager() { + ghoul_assert(_downloadManager, "Download Manager must not be nullptr"); + return *_downloadManager; +} + + } // namespace openspace diff --git a/src/engine/settingsengine.cpp b/src/engine/settingsengine.cpp new file mode 100644 index 0000000000..0dd553da15 --- /dev/null +++ b/src/engine/settingsengine.cpp @@ -0,0 +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. * + ****************************************************************************************/ + +#include + +#include +#include + +namespace openspace { + +SettingsEngine::SettingsEngine() : + _eyeSeparation("eyeSeparation", "Eye Separation" , 0.f, 0.f, 10.f) +{ + addProperty(_eyeSeparation); + setName("Global"); + _eyeSeparation.onChange( + [this](){ OsEng.windowWrapper().setEyeSeparationDistance(_eyeSeparation); }); +} + +} diff --git a/src/engine/wrapper/sgctwindowwrapper.cpp b/src/engine/wrapper/sgctwindowwrapper.cpp index b3a3134a22..1b0908db63 100644 --- a/src/engine/wrapper/sgctwindowwrapper.cpp +++ b/src/engine/wrapper/sgctwindowwrapper.cpp @@ -30,6 +30,10 @@ #undef near #undef far +namespace { + const std::string GuiWindowName = "GUI"; +} + namespace openspace { void SGCTWindowWrapper::setBarrier(bool enabled) { @@ -111,15 +115,36 @@ bool SGCTWindowWrapper::isRegularRendering() const { return true; } + +bool SGCTWindowWrapper::hasGuiWindow() const { + auto engine = sgct::Engine::instance(); + for (size_t i = 0; i < engine->getNumberOfWindows(); ++i) { + if (engine->getWindowPtr(i)->getName() == GuiWindowName) + return true; + } + return false; +} + +bool SGCTWindowWrapper::isGuiWindow() const { + return sgct::Engine::instance()->getCurrentWindowPtr()->getName() == GuiWindowName; +} glm::mat4 SGCTWindowWrapper::viewProjectionMatrix() const { return sgct::Engine::instance()->getCurrentModelViewProjectionMatrix(); } + +glm::mat4 SGCTWindowWrapper::modelMatrix() const { + return sgct::Engine::instance()->getModelMatrix(); +} void SGCTWindowWrapper::setNearFarClippingPlane(float nearPlane, float farPlane) { sgct::Engine::instance()->setNearAndFarClippingPlanes(nearPlane, farPlane); } - + +void SGCTWindowWrapper::setEyeSeparationDistance(float distance) { + sgct::Engine::instance()->setEyeSeparation(distance); +} + glm::ivec4 SGCTWindowWrapper::viewportPixelCoordinates() const { int x1, xSize, y1, ySize; sgct::Engine::instance()->getCurrentWindowPtr()->getCurrentViewportPixelCoords(x1, diff --git a/src/engine/wrapper/windowwrapper.cpp b/src/engine/wrapper/windowwrapper.cpp index 8283edf577..0e45b73a0e 100644 --- a/src/engine/wrapper/windowwrapper.cpp +++ b/src/engine/wrapper/windowwrapper.cpp @@ -72,11 +72,25 @@ bool WindowWrapper::isRegularRendering() const { return true; } +bool WindowWrapper::hasGuiWindow() const { + return false; +} + +bool WindowWrapper::isGuiWindow() const { + return false; +} + glm::mat4 WindowWrapper::viewProjectionMatrix() const { return glm::mat4(1.f); } + +glm::mat4 WindowWrapper::modelMatrix() const { + return glm::mat4(1.f); +} void WindowWrapper::setNearFarClippingPlane(float near, float far) {} + +void WindowWrapper::setEyeSeparationDistance(float distance) {} glm::ivec4 WindowWrapper::viewportPixelCoordinates() const { return glm::ivec4( diff --git a/src/interaction/interactionhandler.cpp b/src/interaction/interactionhandler.cpp index ef0c2ce3ce..c0f26d9538 100644 --- a/src/interaction/interactionhandler.cpp +++ b/src/interaction/interactionhandler.cpp @@ -617,11 +617,16 @@ void InteractionHandler::clearKeyframes(){ #else // USE_OLD_INTERACTIONHANDLER - // InteractionHandler InteractionHandler::InteractionHandler() : _origin("origin", "Origin", "") - , _coordinateSystem("coordinateSystem", "Coordinate System", "") { + , _coordinateSystem("coordinateSystem", "Coordinate System", "") + , _rotationalFriction("rotationalFriction", "Rotational Friction", 1, 0, 1) + , _horizontalFriction("horizontalFriction", "Horizontal Friction", 1, 0, 1) + , _verticalFriction("verticalFriction", "Vertical Friction", 1, 0, 1) + , _sensitivity("sensitivity", "Sensitivity", 0.002, 0.0001, 0.02) + , _rapidness("rapidness", "Rapidness", 1, 0.1, 60) +{ setName("Interaction"); _origin.onChange([this]() { @@ -639,6 +644,7 @@ InteractionHandler::InteractionHandler() }); addProperty(_coordinateSystem); + // Create the interactionModes _inputState = std::make_unique(); // Inject the same mouse states to both orbital and global interaction mode @@ -648,6 +654,30 @@ InteractionHandler::InteractionHandler() // Set the interactionMode _currentInteractionMode = _orbitalInteractionMode; + + // Define lambda functions for changed properties + _rotationalFriction.onChange([&]() { + _mouseStates->setRotationalFriction(_rotationalFriction); + }); + _horizontalFriction.onChange([&]() { + _mouseStates->setHorizontalFriction(_horizontalFriction); + }); + _verticalFriction.onChange([&]() { + _mouseStates->setVerticalFriction(_verticalFriction); + }); + _sensitivity.onChange([&]() { + _mouseStates->setSensitivity(_sensitivity); + }); + _rapidness.onChange([&]() { + _mouseStates->setVelocityScaleFactor(_rapidness); + }); + + // Add the properties + addProperty(_rotationalFriction); + addProperty(_horizontalFriction); + addProperty(_verticalFriction); + addProperty(_sensitivity); + addProperty(_rapidness); } InteractionHandler::~InteractionHandler() { @@ -662,6 +692,38 @@ void InteractionHandler::setCamera(Camera* camera) { _camera = camera; } +void InteractionHandler::resetCameraDirection() { + LINFO("Setting camera direction to point at focus node."); + + glm::dquat rotation = _camera->rotationQuaternion(); + glm::dvec3 focusPosition = focusNode()->worldPosition().dvec3(); + 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 + dmat4 lookAtMat = lookAt( + dvec3(0, 0, 0), + directionToFocusNode, + lookUpVector); + dquat rotationLookAtFocusNode = normalize(quat_cast(inverse(lookAtMat))); + + // Update camera Rotation + _camera->setRotation(rotationLookAtFocusNode); + + // Explicitly synch + _camera->preSynchronization(); + _camera->postSynchronizationPreDraw(); +} + void InteractionHandler::setInteractionMode(std::shared_ptr interactionMode) { // Focus node is passed over from the previous interaction mode SceneGraphNode* focusNode = _currentInteractionMode->focusNode(); @@ -791,34 +853,6 @@ ghoul::Dictionary InteractionHandler::getCameraStateDictionary() { return cameraDict; } -void InteractionHandler::setInteractionFriction(double friction) { - if (friction < 0) { - LWARNING("Clamping friction factor to a value bigger or equal to 0"); - friction = glm::max(friction, 0.0); - } - _mouseStates->setFriction(friction); - LINFO("Interaction friction set to: " << friction); -} - -void InteractionHandler::setInteractionSensitivity(double sensitivity) { - if (sensitivity < 0) { - LWARNING("Clamping scale sensitivity to a value bigger or equal to 0"); - sensitivity = glm::max(sensitivity, 0.0); - } - _mouseStates->setSensitivity(sensitivity); - LINFO("Interaction sensitivity set to: " << sensitivity); -} - -void InteractionHandler::setInteractionFollowScaleFactor(double scaleFactor) { - const double minFollowScaleFactor = 0.01; - if (scaleFactor < minFollowScaleFactor) { - LWARNING("Clamping scale factor to a value bigger or equal to " << minFollowScaleFactor); - scaleFactor = glm::max(scaleFactor, minFollowScaleFactor); - } - _mouseStates->setVelocityScaleFactor(scaleFactor); - LINFO("Interaction velocity scale factor set to: " << scaleFactor); -} - void InteractionHandler::saveCameraStateToFile(const std::string& filepath) { if (!filepath.empty()) { auto fullpath = absPath(filepath); @@ -914,22 +948,10 @@ scripting::ScriptEngine::LuaLibrary InteractionHandler::luaLibrary() { "Restore the camera state from file" }, { - "setInteractionFriction", - &luascriptfunctions::setInteractionFriction, - "number", - "Set the interaction friction" - }, - { - "setInteractionSensitivity", - &luascriptfunctions::setInteractionSensitivity, - "number", - "Set the interaction sensitivity" - }, - { - "setInteractionFollowScaleFactor", - &luascriptfunctions::setInteractionFollowScaleFactor, - "number", - "Set the interaction follow scale factor" + "resetCameraDirection", + &luascriptfunctions::resetCameraDirection, + "void", + "Reset the camera direction to point at the focus node" }, } }; diff --git a/src/interaction/interactionhandler_lua.inl b/src/interaction/interactionhandler_lua.inl index 154dc599a1..fda12f78c7 100644 --- a/src/interaction/interactionhandler_lua.inl +++ b/src/interaction/interactionhandler_lua.inl @@ -133,7 +133,11 @@ int setInteractionMode(lua_State* L) { OsEng.interactionHandler().setInteractionModeToOrbital(); } else if (interactionModeName == "GlobeBrowsingInteractionMode") { +#ifdef OPENSPACE_MODULE_GLOBEBROWSING_ENABLED OsEng.interactionHandler().setInteractionModeToGlobeBrowsing(); +#else + return luaL_error(L, "OpenSpace compiled without support for GlobeBrowsing"); +#endif } else { // Default return luaL_error(L, "Unknown interaction mode. default is 'OrbitalInteractionMode'"); @@ -174,43 +178,17 @@ int saveCameraStateToFile(lua_State* L) { OsEng.interactionHandler().saveCameraStateToFile(cameraStateFilePath); } -int setInteractionFriction(lua_State* L) { - const std::string _loggerCat = "lua.setInteractionFriction"; +int resetCameraDirection(lua_State* L) { + using ghoul::lua::luaTypeToString; + const std::string _loggerCat = "lua.resetCameraDirection"; int nArguments = lua_gettop(L); - if (nArguments != 1) - return luaL_error(L, "Expected %i arguments, got %i", 1, nArguments); + if (nArguments != 0) + return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments); - double friction = luaL_checknumber(L, -1); - - OsEng.interactionHandler().setInteractionFriction(friction); + OsEng.interactionHandler().resetCameraDirection(); } -int setInteractionSensitivity(lua_State* L) { - const std::string _loggerCat = "lua.setInteractionFriction"; - - int nArguments = lua_gettop(L); - if (nArguments != 1) - return luaL_error(L, "Expected %i arguments, got %i", 1, nArguments); - - double sensitivity = luaL_checknumber(L, -1); - - OsEng.interactionHandler().setInteractionSensitivity(sensitivity); -} - -int setInteractionFollowScaleFactor(lua_State* L) { - const std::string _loggerCat = "lua.setInteractionFriction"; - - int nArguments = lua_gettop(L); - if (nArguments != 1) - return luaL_error(L, "Expected %i arguments, got %i", 1, nArguments); - - double scaleFactor = luaL_checknumber(L, -1); - - OsEng.interactionHandler().setInteractionFollowScaleFactor(scaleFactor); -} - - #ifdef USE_OLD_INTERACTIONHANDLER /** diff --git a/src/interaction/interactionmode.cpp b/src/interaction/interactionmode.cpp index 85b16c9769..07be735a9f 100644 --- a/src/interaction/interactionmode.cpp +++ b/src/interaction/interactionmode.cpp @@ -252,14 +252,20 @@ void OrbitalInteractionMode::MouseStates::updateMouseStatesFromInput(const Input } } -void OrbitalInteractionMode::MouseStates::setFriction(double friction) { - _globalRotationMouseState.setFriction(friction); +void OrbitalInteractionMode::MouseStates::setRotationalFriction(double friction) { _localRotationMouseState.setFriction(friction); - _truckMovementMouseState.setFriction(friction); _localRollMouseState.setFriction(friction); _globalRollMouseState.setFriction(friction); } +void OrbitalInteractionMode::MouseStates::setHorizontalFriction(double friction) { + _globalRotationMouseState.setFriction(friction); +} + +void OrbitalInteractionMode::MouseStates::setVerticalFriction(double friction) { + _truckMovementMouseState.setFriction(friction); +} + void OrbitalInteractionMode::MouseStates::setSensitivity(double sensitivity) { _sensitivity = sensitivity; } diff --git a/src/performance/performancemanager.cpp b/src/performance/performancemanager.cpp index 91731768a0..4b07613823 100644 --- a/src/performance/performancemanager.cpp +++ b/src/performance/performancemanager.cpp @@ -46,16 +46,14 @@ PerformanceManager::PerformanceManager() // Compute the total size const int totalSize = sizeof(PerformanceLayout); LINFO("Create shared memory of " << totalSize << " bytes"); - - try { - ghoul::SharedMemory::remove(PerformanceMeasurementSharedData); - } - catch (const ghoul::SharedMemory::SharedMemoryError& e) { - LINFOC(e.component, e.what()); - } - + + if (ghoul::SharedMemory::exists(PerformanceMeasurementSharedData)) + LWARNING("Shared memory for Performance measurements already existed."); + ghoul::SharedMemory::create(PerformanceMeasurementSharedData, totalSize); - _performanceMemory = new ghoul::SharedMemory(PerformanceMeasurementSharedData); + + _performanceMemory = std::make_unique(PerformanceMeasurementSharedData); + void* ptr = _performanceMemory->memory(); // Using the placement-new to create a PerformanceLayout in the shared memory @@ -63,8 +61,7 @@ PerformanceManager::PerformanceManager() } PerformanceManager::~PerformanceManager() { - if (ghoul::SharedMemory::exists(PerformanceMeasurementSharedData)) - ghoul::SharedMemory::remove(PerformanceMeasurementSharedData); + ghoul::SharedMemory::remove(PerformanceMeasurementSharedData); } void PerformanceManager::resetPerformanceMeasurements() { diff --git a/src/performance/performancemeasurement.cpp b/src/performance/performancemeasurement.cpp index a62a6d5d4e..722d7b965d 100644 --- a/src/performance/performancemeasurement.cpp +++ b/src/performance/performancemeasurement.cpp @@ -46,6 +46,7 @@ PerformanceMeasurement::PerformanceMeasurement(std::string identifier, } PerformanceMeasurement::~PerformanceMeasurement() { + glFinish(); auto endTime = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast( endTime - _startTime).count(); diff --git a/src/properties/property.cpp b/src/properties/property.cpp index 4bf82fd209..305624c7bd 100644 --- a/src/properties/property.cpp +++ b/src/properties/property.cpp @@ -136,6 +136,12 @@ void Property::setVisible(bool state) { _metaData.setValue(_metaDataKeyVisible, state); } +bool Property::isVisible() const { + bool visible = true; + _metaData.getValue(_metaDataKeyVisible, visible); + return visible; +} + void Property::setReadOnly(bool state) { _metaData.setValue(_metaDataKeyReadOnly, state); } diff --git a/src/properties/propertyowner.cpp b/src/properties/propertyowner.cpp index eea4579470..5f54329aae 100644 --- a/src/properties/propertyowner.cpp +++ b/src/properties/propertyowner.cpp @@ -57,7 +57,7 @@ PropertyOwner::~PropertyOwner() { _subOwners.clear(); } -const std::vector& PropertyOwner::properties() const { +std::vector PropertyOwner::properties() const { return _properties; } @@ -112,7 +112,7 @@ bool PropertyOwner::hasProperty(const std::string& id) const { return property(id) != nullptr; } -const std::vector& PropertyOwner::propertySubOwners() const { +std::vector PropertyOwner::propertySubOwners() const { return _subOwners; } @@ -140,7 +140,7 @@ void PropertyOwner::setPropertyGroupName(std::string groupID, std::string name) _groupNames[std::move(groupID)] = std::move(name); } -const std::string& PropertyOwner::propertyGroupName(const std::string& groupID) const { +std::string PropertyOwner::propertyGroupName(const std::string& groupID) const { auto it = _groupNames.find(groupID); if (it == _groupNames.end()) return groupID; diff --git a/src/rendering/abufferrenderer.cpp b/src/rendering/abufferrenderer.cpp index 2620cb2a86..234c2b205c 100644 --- a/src/rendering/abufferrenderer.cpp +++ b/src/rendering/abufferrenderer.cpp @@ -32,6 +32,7 @@ #include #include #include +#include #include @@ -166,6 +167,8 @@ void ABufferRenderer::raycastersChanged(VolumeRaycaster& raycaster, bool attache } void ABufferRenderer::update() { + PerfMeasure("ABufferRenderer::update"); + // Make sure that the fragment buffer has the correct resoliution // according to the output render buffer size if (_dirtyResolution) { @@ -221,10 +224,13 @@ void ABufferRenderer::update() { void ABufferRenderer::render(float blackoutFactor, bool doPerformanceMeasurements) { - if (_scene == nullptr) return; - if (_camera == nullptr) return; + PerfMeasure("ABufferRenderer::render"); + if (_scene == nullptr) + return; + if (_camera == nullptr) + return; _mainColorTextureUnit = std::make_unique(); _mainColorTextureUnit->activate(); @@ -387,6 +393,8 @@ void ABufferRenderer::clear() { } void ABufferRenderer::updateResolution() { + PerfMeasure("ABufferRenderer::updateResolution"); + int totalPixels = _resolution.x * _resolution.y; glBindTexture(GL_TEXTURE_2D, _anchorPointerTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_R32UI, _resolution.x, _resolution.y, 0, GL_RED_INTEGER, GL_UNSIGNED_INT, NULL); @@ -475,6 +483,7 @@ void ABufferRenderer::updateResolveDictionary() { } void ABufferRenderer::updateRaycastData() { + PerfMeasure("ABufferRenderer::updateRaycastData"); _raycastData.clear(); _boundsPrograms.clear(); @@ -543,6 +552,8 @@ void ABufferRenderer::updateRaycastData() { void ABufferRenderer::updateRendererData() { + PerfMeasure("ABufferRenderer::updateRendererData"); + ghoul::Dictionary dict; dict.setValue("windowWidth", _resolution.x); dict.setValue("windowHeight", _resolution.y); diff --git a/src/rendering/renderengine.cpp b/src/rendering/renderengine.cpp index b2574b01f9..5ca6d5e33f 100644 --- a/src/rendering/renderengine.cpp +++ b/src/rendering/renderengine.cpp @@ -35,6 +35,7 @@ #include #include +#include #include @@ -382,11 +383,13 @@ void RenderEngine::postSynchronizationPreDraw() { } -void RenderEngine::render(const glm::mat4 &projectionMatrix, const glm::mat4 &viewMatrix) { +void RenderEngine::render(const glm::mat4& projectionMatrix, const glm::mat4& viewMatrix, bool showGui) { _mainCamera->sgctInternal.setViewMatrix(viewMatrix); _mainCamera->sgctInternal.setProjectionMatrix(projectionMatrix); - if (!(OsEng.isMaster() && _disableMasterRendering)) { + + + if (!(OsEng.isMaster() && _disableMasterRendering) && !OsEng.windowWrapper().isGuiWindow()) { _renderer->render(_globalBlackOutFactor, _performanceManager != nullptr); } @@ -395,13 +398,13 @@ void RenderEngine::render(const glm::mat4 &projectionMatrix, const glm::mat4 &vi if (_showInfo) { renderInformation(); } - if (_showLog) { + if (_showLog && showGui) { renderScreenLog(); } } for (auto screenSpaceRenderable : _screenSpaceRenderables) { - if(screenSpaceRenderable->isEnabled()) + if (screenSpaceRenderable->isEnabled() && screenSpaceRenderable->isReady()) screenSpaceRenderable->render(); } } @@ -1152,6 +1155,17 @@ std::shared_ptr RenderEngine::screenSpaceRenderable(std:: return nullptr; } +std::vector RenderEngine::screenSpaceRenderables() const { + std::vector res(_screenSpaceRenderables.size()); + std::transform( + _screenSpaceRenderables.begin(), + _screenSpaceRenderables.end(), + res.begin(), + [](std::shared_ptr p) { return p.get(); } + ); + return res; +} + RenderEngine::RendererImplementation RenderEngine::rendererFromString(const std::string& impl) { const std::map RenderingMethods = { { "ABuffer", RendererImplementation::ABuffer }, @@ -1476,11 +1490,14 @@ void RenderEngine::renderScreenLog() { } } -void RenderEngine::sortScreenspaceRenderables(){ - std::sort(_screenSpaceRenderables.begin(), _screenSpaceRenderables.end(), - [](std::shared_ptr j, std::shared_ptr i){ - return i->depth() > j->depth(); - }); +void RenderEngine::sortScreenspaceRenderables() { + std::sort( + _screenSpaceRenderables.begin(), + _screenSpaceRenderables.end(), + [](auto j, auto i) { + return i->depth() > j->depth(); + } + ); } }// namespace openspace diff --git a/src/rendering/screenspacerenderable.cpp b/src/rendering/screenspacerenderable.cpp index f6970d31d3..57187b38b8 100644 --- a/src/rendering/screenspacerenderable.cpp +++ b/src/rendering/screenspacerenderable.cpp @@ -21,19 +21,38 @@ * 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 + #ifdef WIN32 + #define _USE_MATH_DEFINES + #include + #endif + namespace { const std::string _loggerCat = "ScreenSpaceRenderable"; + const std::string KeyType = "Type"; + const std::string KeyFlatScreen = "FlatScreen"; + const std::string KeyPosition = "Position"; + const std::string KeyScale = "Scale"; + const std::string KeyDepth = "Depth"; + const std::string KeyAlpha = "Alpha"; + + const float PlaneDepth = -2.f; } namespace openspace { -ScreenSpaceRenderable* ScreenSpaceRenderable::createFromDictionary(const ghoul::Dictionary& dictionary) { - +ScreenSpaceRenderable* ScreenSpaceRenderable::createFromDictionary( + const ghoul::Dictionary& dictionary) +{ std::string renderableType; bool success = dictionary.getValue(KeyType, renderableType); @@ -42,11 +61,12 @@ ScreenSpaceRenderable* ScreenSpaceRenderable::createFromDictionary(const ghoul:: return nullptr; } - ghoul::TemplateFactory* factory - = FactoryManager::ref().factory(); + auto factory = FactoryManager::ref().factory(); ScreenSpaceRenderable* result = factory->create(renderableType, dictionary); if (result == nullptr) { - LERROR("Failed to create a ScreenSpaceRenderable object of type '" << renderableType << "'"); + LERROR("Failed to create a ScreenSpaceRenderable object of type '" << + renderableType << "'" + ); return nullptr; } @@ -55,232 +75,242 @@ ScreenSpaceRenderable* ScreenSpaceRenderable::createFromDictionary(const ghoul:: ScreenSpaceRenderable::ScreenSpaceRenderable(const ghoul::Dictionary& dictionary) - :_enabled("enabled", "Is Enabled", true) - ,_useFlatScreen("flatScreen", "Flat Screen", true) - ,_euclideanPosition("euclideanPosition", "Euclidean coordinates", glm::vec2(0),glm::vec2(-4),glm::vec2(4)) - ,_sphericalPosition("sphericalPosition", "Spherical coordinates", glm::vec2(0, M_PI_2),glm::vec2(-M_PI),glm::vec2(M_PI)) - ,_depth("depth", "Depth", 0, 0, 1) - ,_scale("scale", "Scale" , 0.25, 0, 2) - ,_alpha("alpha", "Alpha" , 1, 0, 1) - ,_delete("delete", "Delete") - ,_quad(0) - ,_vertexPositionBuffer(0) - ,_rendererPath("${SHADERS}/framebuffer/renderframebuffer.frag") - ,_vertexPath("${MODULE_BASE}/shaders/screnspace_vs.glsl") - ,_fragmentPath("${MODULE_BASE}/shaders/screnspace_fs.glsl") - ,_texture(nullptr) - ,_shader(nullptr) + : _enabled("enabled", "Is Enabled", true) + , _useFlatScreen("flatScreen", "Flat Screen", true) + , _euclideanPosition( + "euclideanPosition", + "Euclidean coordinates", + glm::vec2(0.f), + glm::vec2(-4.f), + glm::vec2(4.f) + ) + , _sphericalPosition( + "sphericalPosition", + "Spherical coordinates", + glm::vec2(0.f, M_PI_2), + glm::vec2(-M_PI), + glm::vec2(M_PI) + ) + , _depth("depth", "Depth", 0.f, 0.f, 1.f) + , _scale("scale", "Scale", 0.25f, 0.f, 2.f) + , _alpha("alpha", "Alpha", 1.f, 0.f, 1.f) + , _delete("delete", "Delete") + , _quad(0) + , _vertexPositionBuffer(0) + , _texture(nullptr) + , _shader(nullptr) + , _radius(PlaneDepth) { addProperty(_enabled); addProperty(_useFlatScreen); - addProperty(_euclideanPosition); - addProperty(_sphericalPosition); addProperty(_depth); addProperty(_scale); addProperty(_alpha); addProperty(_delete); - _rendererData = ghoul::Dictionary(); - _rendererData.setValue("fragmentRendererPath", _rendererPath); - _rendererData.setValue("windowWidth", OsEng.windowWrapper().currentWindowResolution().x); - _rendererData.setValue("windowHeight", OsEng.windowWrapper().currentWindowResolution().y); - _radius = _planeDepth; - - - if(dictionary.hasValue("FlatScreen")){ - bool useFlatScreen; - dictionary.getValue("FlatScreen", useFlatScreen); - - _useFlatScreen.setValue(useFlatScreen); - } - - useEuclideanCoordinates(_useFlatScreen.value()); + dictionary.getValue(KeyFlatScreen, _useFlatScreen); + useEuclideanCoordinates(_useFlatScreen); - if(dictionary.hasValue("Position")){ - glm::vec2 pos; - dictionary.getValue("Position", pos); - if(_useFlatScreen) - _euclideanPosition.setValue(pos); - else - _sphericalPosition.setValue(pos); - } + if (_useFlatScreen) + dictionary.getValue(KeyPosition, _euclideanPosition); + else + dictionary.getValue(KeyPosition, _sphericalPosition); - if(dictionary.hasValue("Scale")){ - float scale; - dictionary.getValue("Scale", scale); - _scale.setValue(scale); - } - - if(dictionary.hasValue("Depth")){ - float depth; - dictionary.getValue("Depth", depth); - _depth.setValue(depth); - } - - if(dictionary.hasValue("Alpha")){ - float alpha; - dictionary.getValue("Scale", alpha); - _alpha.setValue(alpha); - } + dictionary.getValue(KeyScale, _scale); + dictionary.getValue(KeyDepth, _depth); + dictionary.getValue(KeyAlpha, _alpha); // Setting spherical/euclidean onchange handler _useFlatScreen.onChange([this](){ - if(_useFlatScreen.value()){ - OsEng.gui()._screenSpaceProperty.registerProperty(&_euclideanPosition, &_useFlatScreen); - OsEng.gui()._screenSpaceProperty.unregisterProperty(&_sphericalPosition); + if (_useFlatScreen) { + addProperty(_euclideanPosition); + removeProperty(_sphericalPosition); } else { - OsEng.gui()._screenSpaceProperty.unregisterProperty(&_euclideanPosition); - OsEng.gui()._screenSpaceProperty.registerProperty(&_sphericalPosition, &_useFlatScreen); + removeProperty(_euclideanPosition); + addProperty(_sphericalPosition); } - useEuclideanCoordinates(_useFlatScreen.value()); + useEuclideanCoordinates(_useFlatScreen); }); _delete.onChange([this](){ - std::string script = "openspace.unregisterScreenSpaceRenderable('" + name() + "');"; + std::string script = + "openspace.unregisterScreenSpaceRenderable('" + name() + "');"; OsEng.scriptEngine().queueScript(script); }); } -ScreenSpaceRenderable::~ScreenSpaceRenderable(){} +ScreenSpaceRenderable::~ScreenSpaceRenderable() {} bool ScreenSpaceRenderable::isEnabled() const { return _enabled; } +glm::vec3 ScreenSpaceRenderable::euclideanPosition() const { + return glm::vec3(_euclideanPosition.value(), _depth.value()); +} + +glm::vec3 ScreenSpaceRenderable::sphericalPosition() const { + return glm::vec3(_sphericalPosition.value(), _depth.value()); +} + +float ScreenSpaceRenderable::depth() const { + return _depth; +} + void ScreenSpaceRenderable::createPlane() { - glGenVertexArrays(1, &_quad); // generate array - glGenBuffers(1, &_vertexPositionBuffer); // generate buffer + glGenVertexArrays(1, &_quad); + glGenBuffers(1, &_vertexPositionBuffer); // ============================ // GEOMETRY (quad) // ============================ - const GLfloat vertex_data[] = { // square of two triangles (sigh) + const GLfloat vertex_data[] = { // x y z w s t - -1, -1, 0.0f, 1, 0, 1, - 1, 1, 0.0f, 1, 1, 0, - -1, 1, 0.0f, 1, 0, 0, - -1, -1, 0.0f, 1, 0, 1, - 1, -1, 0.0f, 1, 1, 1, - 1, 1, 0.0f, 1, 1, 0, + -1, -1, 0.0f, 1, 0, 0, + 1, 1, 0.0f, 1, 1, 1, + -1, 1, 0.0f, 1, 0, 1, + -1, -1, 0.0f, 1, 0, 0, + 1, -1, 0.0f, 1, 1, 0, + 1, 1, 0.0f, 1, 1, 1, }; - glBindVertexArray(_quad); // bind array - glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); // bind buffer + glBindVertexArray(_quad); + glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW); glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, reinterpret_cast(0)); + glVertexAttribPointer( + 0, + 4, + GL_FLOAT, + GL_FALSE, + sizeof(GLfloat) * 6, + 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(GLfloat) * 6, + reinterpret_cast(sizeof(GLfloat) * 4) + ); } -void ScreenSpaceRenderable::useEuclideanCoordinates(bool b){ +void ScreenSpaceRenderable::useEuclideanCoordinates(bool b) { _useEuclideanCoordinates = b; - if(_useEuclideanCoordinates){ - _euclideanPosition.set(toEuclidean(_sphericalPosition.value(), _radius)); + if (_useEuclideanCoordinates) { + _euclideanPosition = toEuclidean(_sphericalPosition.value(), _radius); } else { - _sphericalPosition.set(toSpherical(_euclideanPosition.value())); + _sphericalPosition = toSpherical(_euclideanPosition.value()); } } -glm::vec2 ScreenSpaceRenderable::toEuclidean(glm::vec2 polar, float r){ - float x = r*sin(polar[0])*sin(polar[1]); - float y = r*cos(polar[1]); +glm::vec2 ScreenSpaceRenderable::toEuclidean(const glm::vec2& spherical, float r) { + float x = r * sin(spherical[0]) * sin(spherical[1]); + float y = r * cos(spherical[1]); return glm::vec2(x, y); } -glm::vec2 ScreenSpaceRenderable::toSpherical(glm::vec2 euclidean){ - _radius = -sqrt(pow(euclidean[0],2)+pow(euclidean[1],2)+pow(_planeDepth,2)); - float theta = atan2(-_planeDepth,euclidean[0])-M_PI/2.0; +glm::vec2 ScreenSpaceRenderable::toSpherical(const glm::vec2& euclidean) { + _radius = -sqrt(pow(euclidean[0],2)+pow(euclidean[1],2)+pow(PlaneDepth,2)); + float theta = atan2(-PlaneDepth,euclidean[0])-M_PI/2.0; float phi = acos(euclidean[1]/_radius); return glm::vec2(theta, phi); } -void ScreenSpaceRenderable::registerProperties(){ - OsEng.gui()._screenSpaceProperty.registerProperty(&_enabled); - OsEng.gui()._screenSpaceProperty.registerProperty(&_useFlatScreen); - OsEng.gui()._screenSpaceProperty.registerProperty(&_euclideanPosition); - OsEng.gui()._screenSpaceProperty.registerProperty(&_depth); - OsEng.gui()._screenSpaceProperty.registerProperty(&_scale); - OsEng.gui()._screenSpaceProperty.registerProperty(&_alpha); - OsEng.gui()._screenSpaceProperty.registerProperty(&_delete); -} - -void ScreenSpaceRenderable::unregisterProperties(){ - OsEng.gui()._screenSpaceProperty.unregisterProperties(name()); -} - -void ScreenSpaceRenderable::createShaders(){ - if(!_shader) { - +void ScreenSpaceRenderable::createShaders() { + if (!_shader) { ghoul::Dictionary dict = ghoul::Dictionary(); - dict.setValue("rendererData", _rendererData); - dict.setValue("fragmentPath", _fragmentPath); - _shader = ghoul::opengl::ProgramObject::Build("ScreenSpaceProgram", - _vertexPath, + auto res = OsEng.windowWrapper().currentWindowResolution(); + ghoul::Dictionary rendererData = { + { "fragmentRendererPath", "${SHADERS}/framebuffer/renderframebuffer.frag" }, + { "windowWidth" , res.x }, + { "windowHeight" , res.y } + }; + + dict.setValue("rendererData", rendererData); + dict.setValue("fragmentPath", "${MODULE_BASE}/shaders/screenspace_fs.glsl"); + _shader = ghoul::opengl::ProgramObject::Build( + "ScreenSpaceProgram", + "${MODULE_BASE}/shaders/screenspace_vs.glsl", "${SHADERS}/render.frag", dict - ); + ); } } -glm::mat4 ScreenSpaceRenderable::scaleMatrix(){ - glm::mat4 scale(1.0); - +glm::mat4 ScreenSpaceRenderable::scaleMatrix() { glm::vec2 resolution = OsEng.windowWrapper().currentWindowResolution(); //to scale the plane - float textureRatio = (float(_texture->height())/float(_texture->width())); - float scalingRatioX = _originalViewportSize[0]/ resolution[0]; - float scalingRatioY = _originalViewportSize[1]/ resolution[1]; - scale = glm::scale(scale, glm::vec3(_scale.value() * scalingRatioX, - _scale.value() * scalingRatioY * textureRatio, - 1)); - return scale; + float textureRatio = + static_cast(_texture->height()) / static_cast(_texture->width()); + + float scalingRatioX = _originalViewportSize.x / resolution.x; + float scalingRatioY = _originalViewportSize.y / resolution.y; + return glm::scale( + glm::mat4(1.f), + glm::vec3( + _scale * scalingRatioX, + _scale * scalingRatioY * textureRatio, + 1.f + ) + ); } -glm::mat4 ScreenSpaceRenderable::rotationMatrix(){ - glm::mat4 rotation(1.0); - if(!_useEuclideanCoordinates){ +glm::mat4 ScreenSpaceRenderable::rotationMatrix() { + // Get the scene transform + glm::mat4 rotation = OsEng.windowWrapper().modelMatrix(); + if (!_useEuclideanCoordinates) { glm::vec2 position = _sphericalPosition.value(); float theta = position.x; - float phi = position.y - M_PI/2.0; + float phi = position.y - M_PI_2; - rotation = glm::rotate(rotation, position.x, glm::vec3(0.0f, 1.0f, 0.0f)); - rotation = glm::rotate(rotation, (float) (position.y - M_PI/2.0) , glm::vec3(1.0f, 0.0f, 0.0f)); + rotation = glm::rotate(rotation, position.x, glm::vec3(0.f, 1.f, 0.f)); + rotation = glm::rotate( + rotation, + static_cast(position.y - M_PI_2), + glm::vec3(1.f, 0.f, 0.f) + ); } return rotation; } - -glm::mat4 ScreenSpaceRenderable::translationMatrix(){ +glm::mat4 ScreenSpaceRenderable::translationMatrix() { glm::mat4 translation(1.0); - if(!_useEuclideanCoordinates){ - translation = glm::translate(translation, glm::vec3(0.0f, 0.0f, _planeDepth)); - }else{ - translation = glm::translate(glm::mat4(1.f), glm::vec3(_euclideanPosition.value(), _planeDepth)); + if (!_useEuclideanCoordinates) { + translation = glm::translate(translation, glm::vec3(0.0f, 0.0f, PlaneDepth)); + } else { + translation = glm::translate( + glm::mat4(1.f), + glm::vec3(_euclideanPosition.value(), PlaneDepth) + ); } return translation; } - -void ScreenSpaceRenderable::draw(glm::mat4 modelTransform){ - float occlusionDepth = 1-_depth.value(); - +void ScreenSpaceRenderable::draw(glm::mat4 modelTransform) { glEnable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); _shader->activate(); - _shader->setUniform("OcclusionDepth", occlusionDepth); + _shader->setUniform("OcclusionDepth", 1.f - _depth); _shader->setUniform("Alpha", _alpha); - _shader->setUniform("ModelTransform",modelTransform); - _shader->setUniform("ViewProjectionMatrix", OsEng.renderEngine().camera()->viewProjectionMatrix()); + _shader->setUniform("ModelTransform", modelTransform); + _shader->setUniform( + "ViewProjectionMatrix", + OsEng.renderEngine().camera()->viewProjectionMatrix() + ); + ghoul::opengl::TextureUnit unit; unit.activate(); _texture->bind(); @@ -288,8 +318,10 @@ void ScreenSpaceRenderable::draw(glm::mat4 modelTransform){ glBindVertexArray(_quad); glDrawArrays(GL_TRIANGLES, 0, 6); + glEnable(GL_CULL_FACE); _shader->deactivate(); } -}// namespace openspace \ No newline at end of file + +} // namespace openspace diff --git a/src/scene/scene.cpp b/src/scene/scene.cpp index 19be7dbed9..475f50ab65 100644 --- a/src/scene/scene.cpp +++ b/src/scene/scene.cpp @@ -103,34 +103,6 @@ void Scene::update(const UpdateData& data) { } } - //if (!ONCE) { - // ghoul::Dictionary d = { - // {"Name", std::string("Earth_Pluto")}, - // {"Parent", std::string("PlutoBarycenter")}, - // {"Renderable", ghoul::Dictionary{ - // {"Type", std::string("RenderablePlanet")}, - // {"Frame", std::string("IAU_EARTH")}, - // {"Body", std::string("EARTH")}, - // {"Geometry", ghoul::Dictionary{ - // {"Type", std::string("SimpleSphere")}, - // {"Radius", glm::vec2(6.3f, 6.0f)}, - // {"Segments", 100.0} - // }}, - // {"Textures", ghoul::Dictionary{ - // {"Type", std::string("simple")}, - // { "Color", std::string("C:/alebo68/OpenSpace/data/scene/earth/textures/earth_bluemarble.jpg") }, - // { "Night", std::string("C:/alebo68/OpenSpace/data/scene/earth/textures/earth_night.jpg")} - // }} - // }} - // }; - - // SceneGraphNode* node = SceneGraphNode::createFromDictionary(d); - // node->setParent(sceneGraphNode(d.value("Parent"))); - // node->initialize(); - // _graph.addSceneGraphNode(node); - // ONCE = true; - //} - for (SceneGraphNode* node : _graph.nodes()) { try { node->update(data); @@ -226,187 +198,13 @@ bool Scene::loadSceneInternal(const std::string& sceneDescriptionFilePath) { for (auto it = _graph.nodes().rbegin(); it != _graph.nodes().rend(); ++it) (*it)->calculateBoundingSphere(); - // Read the camera dictionary + // Read the camera dictionary and set the camera state ghoul::Dictionary cameraDictionary; if (dictionary.getValue(KeyCamera, cameraDictionary)) { OsEng.interactionHandler().setCameraStateFromDictionary(cameraDictionary); } - // HOLY MOLY! This much code to read a camera state? Added the above code with - // functions to set camera state from a dictionary in interactio handler and commented - // away the below code. - // Also, the camera is now defined with a slightly different dictionary (no psc!) //KB - - /* - // TODO: Make it less hard-coded and more flexible when nodes are not found - ghoul::Dictionary cameraDictionary; - if (dictionary.getValue(KeyCamera, cameraDictionary)) { - LDEBUG("Camera dictionary found"); - std::string focus; - - if (cameraDictionary.hasKey(KeyFocusObject) - && cameraDictionary.getValue(KeyFocusObject, focus)) - { - auto focusIterator = std::find_if( - _graph.nodes().begin(), - _graph.nodes().end(), - [focus](SceneGraphNode* node) { - return node->name() == focus; - } - ); - - if (focusIterator != _graph.nodes().end()) { - _focus = focus; - LDEBUG("Setting camera focus to '" << _focus << "'"); - } - else { - LERROR("Could not find focus object '" << focus << "'"); - _focus = "Root"; - } - } - } - - // Initialize all nodes - for (SceneGraphNode* node : _graph.nodes()) { - try { - bool success = node->initialize(); - if (success) - LDEBUG(node->name() << " initialized successfully!"); - else - LWARNING(node->name() << " not initialized."); - } - catch (const ghoul::RuntimeError& e) { - LERRORC(_loggerCat + "(" + e.component + ")", e.what()); - } - } - - - // update the position of all nodes - // TODO need to check this; unnecessary? (ab) - for (SceneGraphNode* node : _graph.nodes()) { - try { - node->update({ Time::ref().currentTime() }); - } - catch (const ghoul::RuntimeError& e) { - LERRORC(e.component, e.message); - } - } - - for (auto it = _graph.nodes().rbegin(); it != _graph.nodes().rend(); ++it) - (*it)->calculateBoundingSphere(); - - - // Calculate the bounding sphere for the scenegraph - //_root->calculateBoundingSphere(); - - // set the camera position - Camera* c = OsEng.ref().renderEngine().camera(); - //auto focusIterator = _allNodes.find(_focus); - auto focusIterator = std::find_if( - _graph.nodes().begin(), - _graph.nodes().end(), - [&](SceneGraphNode* node) { - return node->name() == _focus; - } - ); - - glm::vec2 cameraScaling(1); - psc cameraPosition(0,0,1,0); - - //if (_focus->) - if (focusIterator != _graph.nodes().end()) { - LDEBUG("Camera focus is '" << _focus << "'"); - SceneGraphNode* focusNode = *focusIterator; - //Camera* c = OsEng.interactionHandler().getCamera(); - - // TODO: Make distance depend on radius - // TODO: Set distance and camera direction in some more smart way - // TODO: Set scaling dependent on the position and distance - // set position for camera - const PowerScaledScalar bound = focusNode->calculateBoundingSphere(); - - // this part is full of magic! - glm::vec2 boundf = bound.vec2(); - //glm::vec2 scaling{1.0f, -boundf[1]}; - - cameraScaling = glm::vec2(1.f, -boundf[1]); - //boundf[0] *= 5.0f; - - - //psc cameraPosition = focusNode->position(); - //cameraPosition += psc(glm::vec4(0.f, 0.f, boundf)); - - //cameraPosition = psc(glm::vec4(0.f, 0.f, 1.f,0.f)); - - cameraPosition = focusNode->position(); - cameraPosition += psc(glm::vec4(boundf[0], 0.f, 0.f, boundf[1])); - - //why this line? (JK) - //cameraPosition = psc(glm::vec4(0.f, 0.f, 1.f, 0.f)); - - - //c->setPosition(cameraPosition); - // c->setCameraDirection(glm::vec3(0, 0, -1)); - // c->setScaling(scaling); - - // Set the focus node for the interactionhandler - OsEng.interactionHandler().setFocusNode(focusNode); - } - else - OsEng.interactionHandler().setFocusNode(_graph.rootNode()); - - glm::vec4 position; - if (cameraDictionary.hasKeyAndValue(KeyPositionObject)) { - try { - position = cameraDictionary.value(KeyPositionObject); - - LDEBUG("Camera position is (" - << position[0] << ", " - << position[1] << ", " - << position[2] << ", " - << position[3] << ")"); - - cameraPosition = psc(position); - } - catch (const ghoul::Dictionary::DictionaryError& e) { - LERROR("Error loading Camera location: " << e.what()); - } - } - - // the camera position - const SceneGraphNode* fn = OsEng.interactionHandler().focusNode(); - if (!fn) { - throw ghoul::RuntimeError("Could not find focus node"); - } - - // Check crash for when fn == nullptr - glm::vec3 target = glm::normalize(fn->worldPosition().vec3() - cameraPosition.vec3()); - glm::mat4 la = glm::lookAt(glm::vec3(0, 0, 0), target, glm::vec3(c->lookUpVectorCameraSpace())); - - c->setRotation(glm::quat_cast(la)); - c->setPosition(cameraPosition); - c->setScaling(cameraScaling); - - glm::vec3 viewOffset; - if (cameraDictionary.hasKey(KeyViewOffset) - && cameraDictionary.getValue(KeyViewOffset, viewOffset)) { - glm::quat rot = glm::quat(viewOffset); - c->rotate(rot); - } - - // explicitly update and sync the camera - c->preSynchronization(); - c->postSynchronizationPreDraw(); - */ - - for (SceneGraphNode* node : _graph.nodes()) { - std::vector properties = node->propertiesRecursive(); - for (properties::Property* p : properties) { - OsEng.gui()._property.registerProperty(p); - } - } - - // If a LuaDocumentationFile was specified, generate it now + // If a PropertyDocumentationFile was specified, generate it now const bool hasType = OsEng.configurationManager().hasKey(ConfigurationManager::KeyPropertyDocumentationType); const bool hasFile = OsEng.configurationManager().hasKey(ConfigurationManager::KeyPropertyDocumentationFile); if (hasType && hasFile) { diff --git a/src/scripting/scriptengine.cpp b/src/scripting/scriptengine.cpp index ae6760e394..32156b5262 100644 --- a/src/scripting/scriptengine.cpp +++ b/src/scripting/scriptengine.cpp @@ -24,12 +24,15 @@ #include -#include #include -#include +#include +#include + +#include #include #include -#include +#include + #include #include @@ -140,7 +143,12 @@ bool ScriptEngine::runScript(const std::string& script) { LWARNING("Script was empty"); return false; } - + + if (_logScripts) { + // Write command to log before it's executed + writeLog(script); + } + try { ghoul::lua::runScript(_state, script); } @@ -561,6 +569,66 @@ bool ScriptEngine::writeDocumentation(const std::string& filename, const std::st } } +bool ScriptEngine::writeLog(const std::string& script) { + // Check that logging is enabled and initialize if necessary + if (!_logFileExists) { + // If a ScriptLogFile was specified, generate it now + const bool hasType = OsEng.configurationManager() + .hasKey(ConfigurationManager::KeyScriptLogType); + const bool hasFile = OsEng.configurationManager() + .hasKey(ConfigurationManager::KeyScriptLogFile); + if (hasType && hasFile) { + OsEng.configurationManager() + .getValue(ConfigurationManager::KeyScriptLogType, _logType); + OsEng.configurationManager() + .getValue(ConfigurationManager::KeyScriptLogFile, _logFilename); + + _logFilename = absPath(_logFilename); + _logFileExists = true; + + LDEBUG("Using script log of type '" << _logType << + "' to file '" << _logFilename << "'"); + + // Test file and clear previous input + std::ofstream file(_logFilename, std::ofstream::out | std::ofstream::trunc); + + if (!file.good()) { + LERROR("Could not open file '" << _logFilename + << "' for logging scripts"); + + return false; + } + } else { + LDEBUG("No script log specified in 'openspace.cfg.' To log, set '" + << ConfigurationManager::KeyScriptLogType << " and " + << ConfigurationManager::KeyScriptLogFile + << " in configuration table."); + _logScripts = false; + return false; + } + } + + if (_logType == "text") { + // Simple text output to logfile + std::ofstream file(_logFilename, std::ofstream::app); + if (!file.good()) { + LERROR("Could not open file '" << _logFilename << "' for logging scripts"); + return false; + } + + file << script << std::endl; + file.close(); + } + else { + LERROR("Undefined type '" << _logType << "' for script documentation"); + _logScripts = false; + return false; + } + + return true; +} + + void ScriptEngine::serialize(SyncBuffer* syncBuffer){ syncBuffer->encode(_currentSyncedScript); _currentSyncedScript.clear(); diff --git a/src/util/histogram.cpp b/src/util/histogram.cpp index 45224535d9..31600c1b0b 100644 --- a/src/util/histogram.cpp +++ b/src/util/histogram.cpp @@ -296,31 +296,54 @@ float Histogram::entropy(){ } void Histogram::print() const { - std::cout << "number of bins: " << _numBins << std::endl - << "range: " << _minValue << " - " << _maxValue << std::endl << std::endl; + // std::cout << "number of bins: " << _numBins << std::endl + // << "range: " << _minValue << " - " << _maxValue << std::endl << std::endl; for (int i = 0; i < _numBins; i++) { float low = _minValue + float(i) / _numBins * (_maxValue - _minValue); float high = low + (_maxValue - _minValue) / float(_numBins); - std::cout << i << " [" << low << ", " << high << "]" - << " " << _data[i] << std::endl; + // std::cout << i << " [" << low << ", " << high << "]" + // << " " << _data[i] << std::endl; + std::cout << _data[i]/(float)_numValues << ", "; } - std::cout << std::endl << std::endl << std::endl<< "==============" << std::endl; + std::cout << std::endl; + // std::cout << std::endl << std::endl << std::endl<< "==============" << std::endl; } -float Histogram::highestBinValue(bool equalized){ +float Histogram::highestBinValue(bool equalized, int overBins){ int highestBin = 0; + float highestValue = 0; + for(int i=0; i<_numBins; i++){ - if(_data[i] > _data[highestBin]) + float value = 0; + int num = 0; + for(int j=0; j0){ + value += _data[i-j]; + num++; + } + if(i+j<_numBins){ + value += _data[i+j]; + num++; + } + } + + value += _data[i]; + value /= (float)++num; + + if(value > highestValue){ highestBin = i; + highestValue = value; + } } - float low = _minValue + float(highestBin) / _numBins * (_maxValue - _minValue); - float high = low + (_maxValue - _minValue) / float(_numBins); if(!equalized){ + float low = _minValue + float(highestBin) / _numBins * (_maxValue - _minValue); + float high = low + (_maxValue - _minValue) / float(_numBins); return (high+low)/2.0; }else{ - return equalize((high+low)/2.0); + return highestBin/(float)_numBins; + // return equalize((high+low)/2.0); } } diff --git a/src/util/keys.cpp b/src/util/keys.cpp index 2384f503cb..71637f0a10 100644 --- a/src/util/keys.cpp +++ b/src/util/keys.cpp @@ -36,6 +36,12 @@ namespace { namespace openspace { +bool hasKeyModifier(KeyAction lhs, KeyAction rhs) { + return + static_cast>(lhs) & + static_cast>(rhs); +} + KeyAction operator|(KeyAction lhs, KeyAction rhs) { return static_cast( static_cast>(lhs) | @@ -48,6 +54,13 @@ KeyAction operator|=(KeyAction& lhs, KeyAction rhs) { return lhs; } +bool hasKeyModifier(KeyModifier lhs, KeyModifier rhs) { + return + static_cast>(lhs) & + static_cast>(rhs); +} + + KeyModifier operator|(KeyModifier lhs, KeyModifier rhs) { return static_cast( static_cast>(lhs) | diff --git a/src/util/spicemanager.cpp b/src/util/spicemanager.cpp index 7c6ecb08d6..b76b21bf55 100644 --- a/src/util/spicemanager.cpp +++ b/src/util/spicemanager.cpp @@ -32,7 +32,7 @@ #include #include -#include +#include namespace { const std::string _loggerCat = "SpiceManager"; @@ -952,7 +952,7 @@ glm::dvec3 SpiceManager::getEstimatedPosition(const std::string& target, int observerId = naifId(observer); - std::set coveredTimes = _spkCoverageTimes.find(targetId)->second; + const std::set& coveredTimes = _spkCoverageTimes.find(targetId)->second; glm::dvec3 pos; if (coveredTimes.lower_bound(ephemerisTime) == coveredTimes.begin()) { diff --git a/src/util/time_lua.inl b/src/util/time_lua.inl index 687780c459..89681cf9fc 100644 --- a/src/util/time_lua.inl +++ b/src/util/time_lua.inl @@ -24,7 +24,7 @@ #include -#include +#include #include namespace openspace { diff --git a/src/util/transformationmanager.cpp b/src/util/transformationmanager.cpp index 3da4d3fe06..0838c1318c 100644 --- a/src/util/transformationmanager.cpp +++ b/src/util/transformationmanager.cpp @@ -25,6 +25,8 @@ #include #include +#define _USE_MATH_DEFINES +#include namespace { const std::string _loggerCat = "TransformationManager"; @@ -37,11 +39,9 @@ #else LWARNING("Kameleon module needed for transformations with dynamic frames"); #endif - _kameleonFrames = { "J2000", "GEI", "GEO", "MAG", "GSE", "GSM", "SM", "RTN", "GSEQ", //geocentric "HEE", "HAE", "HEEQ" //heliocentric }; - // _dipoleFrames = {"GSM", "MAG"}; } TransformationManager::~TransformationManager(){ @@ -50,74 +50,60 @@ #endif } + glm::dmat3 TransformationManager::kameleonTransformationMatrix( std::string from, + std::string to, + double ephemerisTime) const + { +#ifdef OPENSPACE_MODULE_KAMELEON_ENABLED + ccmc::Position in0 = {1.f, 0.f, 0.f}; + ccmc::Position in1 = {0.f, 1.f, 0.f}; + ccmc::Position in2 = {0.f, 0.f, 1.f}; + + ccmc::Position out0; + ccmc::Position out1; + ccmc::Position out2; + + _kameleon->_cxform(from.c_str(), to.c_str(), ephemerisTime, &in0, &out0); + _kameleon->_cxform(from.c_str(), to.c_str(), ephemerisTime, &in1, &out1); + _kameleon->_cxform(from.c_str(), to.c_str(), ephemerisTime, &in2, &out2); + + return glm::dmat3( + out0.c0 , out0.c1 , out0.c2, + out1.c0 , out1.c1 , out1.c2, + out2.c0 , out2.c1 , out2.c2 + ); +#else + return glm::dmat3(0.0); +#endif + } + glm::dmat3 TransformationManager::frameTransformationMatrix(std::string from, std::string to, double ephemerisTime) const { #ifdef OPENSPACE_MODULE_KAMELEON_ENABLED - auto fromit = _dipoleFrames.find(from); - auto toit = _dipoleFrames.find(to); - - // //diopole frame to J200 makes the frame rotate. - // if(fromit != _dipoleFrames.end()) from = "GSE"; - // if(toit != _dipoleFrames.end()) to = "GSE"; - - fromit = _kameleonFrames.find(from); - toit = _kameleonFrames.find(to); + auto fromit = _kameleonFrames.find(from); + auto toit = _kameleonFrames.find(to); bool fromKameleon = (fromit != _kameleonFrames.end()); bool toKameleon = (toit != _kameleonFrames.end()); - - ccmc::Position in0 = {1.f, 0.f, 0.f}; - ccmc::Position in1 = {0.f, 1.f, 0.f}; - ccmc::Position in2 = {0.f, 0.f , 1.f}; - - ccmc::Position out0; - ccmc::Position out1; - ccmc::Position out2; if(!fromKameleon && !toKameleon){ return SpiceManager::ref().frameTransformationMatrix(from, to, ephemerisTime); } if(fromKameleon && toKameleon){ - _kameleon->_cxform(from.c_str(), to.c_str(), ephemerisTime, &in0, &out0); - _kameleon->_cxform(from.c_str(), to.c_str(), ephemerisTime, &in1, &out1); - _kameleon->_cxform(from.c_str(), to.c_str(), ephemerisTime, &in2, &out2); - - return glm::dmat3( - out0.c0 , out0.c1 , out0.c2, - out1.c0 , out1.c1 , out1.c2, - out2.c0 , out2.c1 , out2.c2 - ); + return kameleonTransformationMatrix(from, to, ephemerisTime); }else if(fromKameleon && !toKameleon){ - _kameleon->_cxform(from.c_str(), "J2000", ephemerisTime, &in0, &out0); - _kameleon->_cxform(from.c_str(), "J2000", ephemerisTime, &in1, &out1); - _kameleon->_cxform(from.c_str(), "J2000", ephemerisTime, &in2, &out2); - - glm::dmat3 kameleonTransformation( - out0.c0 , out0.c1 , out0.c2, - out1.c0 , out1.c1 , out1.c2, - out2.c0 , out2.c1 , out2.c2 - ); - + glm::dmat3 kameleonTransformation = kameleonTransformationMatrix(from, "J2000", ephemerisTime); glm::dmat3 spiceTransformation = SpiceManager::ref().frameTransformationMatrix("J2000", to, ephemerisTime); return spiceTransformation*kameleonTransformation; }else if(!fromKameleon && toKameleon){ glm::dmat3 spiceTransformation = SpiceManager::ref().frameTransformationMatrix(from, "J2000", ephemerisTime); - - _kameleon->_cxform("J2000", to.c_str(), ephemerisTime, &in0, &out0); - _kameleon->_cxform("J2000", to.c_str(), ephemerisTime, &in1, &out1); - _kameleon->_cxform("J2000", to.c_str(), ephemerisTime, &in2, &out2); - - glm::dmat3 kameleonTransformation( - out0.c0 , out0.c1 , out0.c2, - out1.c0 , out1.c1 , out1.c2, - out2.c0 , out2.c1 , out2.c2 - ); + glm::dmat3 kameleonTransformation = kameleonTransformationMatrix("J2000", to, ephemerisTime); return kameleonTransformation*spiceTransformation; } diff --git a/tests/main.cpp b/tests/main.cpp index c6dc8c16db..5f978b987d 100644 --- a/tests/main.cpp +++ b/tests/main.cpp @@ -38,7 +38,7 @@ //#include //#include //#include -#include +//#include //#include //#include @@ -66,19 +66,26 @@ using namespace ghoul::filesystem; using namespace ghoul::logging; namespace { - std::string _loggerCat = "OpenSpaceTest"; + std::string _loggerCat = "OpenSpaceTest"; } int main(int argc, char** argv) { - std::vector args; - openspace::OpenSpaceEngine::create(argc, argv, std::make_unique(), args); + std::vector args; + openspace::OpenSpaceEngine::create(argc, argv, std::make_unique(), args); - testing::InitGoogleTest(&argc, argv); + testing::InitGoogleTest(&argc, argv); - int returnVal = RUN_ALL_TESTS(); + //testing::internal::CaptureStdout(); + //testing::internal::CaptureStderr(); + bool b = RUN_ALL_TESTS(); + //std::string output = testing::internal::GetCapturedStdout(); + //std::string error = testing::internal::GetCapturedStderr(); - // keep console from closing down - int dummy; std::cin >> dummy; + //std::ofstream o("output.txt"); + //o << output; - return returnVal; + //std::ofstream e("error.txt"); + //e << error; + + return b; } diff --git a/tests/test_iswamanager.inl b/tests/test_iswamanager.inl index e8c8ec5d70..2e704c69f0 100644 --- a/tests/test_iswamanager.inl +++ b/tests/test_iswamanager.inl @@ -21,13 +21,17 @@ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ + #ifdef OPENSPACE_MODULE_ISWA_ENABLED -#include "gtest/gtest.h" + #define private public #include #define private private + +#include #include + /* * For each test the following is run: * Constructor() -> setUp() -> test -> tearDown() -> Deconstructor() @@ -35,49 +39,46 @@ namespace openspace { -class IswaManagerTest : public testing::Test{ +class IswaManagerTest : public testing::Test { protected: - IswaManagerTest() - { - IswaManager::initialize(); - } + IswaManagerTest() { + DownloadManager::initialize("", 0); + IswaManager::initialize(); + } - ~IswaManagerTest(){ - IswaManager::deinitialize(); - } + ~IswaManagerTest() { + IswaManager::deinitialize(); + DownloadManager::deinitialize(); + } - - void reset() {} - - //std::shared_ptr iSWAManager; + void reset() {} }; TEST_F(IswaManagerTest, initialize){ + IswaManager::deinitialize(); - IswaManager::deinitialize(); + ASSERT_FALSE(IswaManager::isInitialized()) << "IswaManager is initialized before initialize call"; - ASSERT_TRUE(!IswaManager::isInitialized()) << "IswaManager is initialized before initialize call"; + IswaManager::initialize(); - IswaManager::initialize(); + ASSERT_TRUE(IswaManager::isInitialized()) << "IswaManager is not initialized after initialize call"; - ASSERT_TRUE(IswaManager::isInitialized()) << "IswaManager is not initialized after initialize call"; + ASSERT_NE(&IswaManager::ref(), nullptr) << "IswaManager ref() is not a nullptr"; - ASSERT_NE(&IswaManager::ref(), nullptr) << "IswaManager ref() is not a nullptr"; - - EXPECT_EQ(&IswaManager::ref(), &IswaManager::ref()) << "IswaManager ref() returns the same object twice"; + EXPECT_EQ(&IswaManager::ref(), &IswaManager::ref()) << "IswaManager ref() returns the same object twice"; } TEST_F(IswaManagerTest, iswaUrl){ - //OsEng.loadSpiceKernels(); - //Time::ref().setTime(double(100000.0)); - //Time::ref().preSynchronization(); - //Time::ref().postSynchronizationPreDraw(); - //std::string url = ISWAManager::ref().iSWAurl(7); - //std::string expectedUrl = "http://iswa2.ccmc.gsfc.nasa.gov/IswaSystemWebApp/iSWACygnetStreamer?timestamp=2000-01-02%2015:45:35&window=-1&cygnetId=7"; + //OsEng.loadSpiceKernels(); + //Time::ref().setTime(double(100000.0)); + //Time::ref().preSynchronization(); + //Time::ref().postSynchronizationPreDraw(); + //std::string url = ISWAManager::ref().iSWAurl(7); + //std::string expectedUrl = "http://iswa2.ccmc.gsfc.nasa.gov/IswaSystemWebApp/iSWACygnetStreamer?timestamp=2000-01-02%2015:45:35&window=-1&cygnetId=7"; - //EXPECT_EQ(expectedUrl, url); + //EXPECT_EQ(expectedUrl, url); } }//namespace openspace diff --git a/tests/test_luaconversions.inl b/tests/test_luaconversions.inl index 771c5e6c43..0b907d00ad 100644 --- a/tests/test_luaconversions.inl +++ b/tests/test_luaconversions.inl @@ -33,27 +33,27 @@ class LuaConversionTest : public testing::Test { protected: - lua_State* state; + lua_State* state; - LuaConversionTest() { - state = luaL_newstate(); - luaL_openlibs(state); + LuaConversionTest() { + state = luaL_newstate(); + luaL_openlibs(state); } - ~LuaConversionTest() { - lua_close(state); + ~LuaConversionTest() { + lua_close(state); } - void reset() { - lua_close(state); - state = luaL_newstate(); - luaL_openlibs(state); - } + void reset() { + lua_close(state); + state = luaL_newstate(); + luaL_openlibs(state); + } }; TEST_F(LuaConversionTest, LuaExecution) { - int status = luaL_loadstring(state, ""); - EXPECT_EQ(status, LUA_OK); + int status = luaL_loadstring(state, ""); + EXPECT_EQ(status, LUA_OK); } #define CONVERSION_TEST_TEMPLATE(__NAME__, __TYPE__, __VALUE__) \ @@ -89,7 +89,7 @@ TEST_F(LuaConversionTest, LuaExecution) { CONVERSION_TEST_TEMPLATE(Bool, bool, true); CONVERSION_TEST_NUMERICAL(Char, char, 1); -CONVERSION_TEST_NUMERICAL(WChar, wchar_t, 1); +//CONVERSION_TEST_NUMERICAL(WChar, wchar_t, 1); CONVERSION_TEST_NUMERICAL(SignedChar, signed char, 1); CONVERSION_TEST_NUMERICAL(UnsignedChar, unsigned char, 1); CONVERSION_TEST_NUMERICAL(Short, short, 1); @@ -138,14 +138,14 @@ CONVERSION_TEST_NUMERICAL(DMat4x4, glm::dmat4x4, glm::dmat4x4(1.f)); TEST_F(LuaConversionTest, String) { - using namespace openspace::properties; - bool success - = PropertyDelegate>::toLuaValue( - state, "value"); - EXPECT_TRUE(success) << "toLuaValue"; - std::string value = ""; - value = PropertyDelegate>::fromLuaValue( - state, success); - EXPECT_TRUE(success) << "fromLuaValue"; - EXPECT_EQ(value, "value") << "fromLuaValue"; + using namespace openspace::properties; + bool success + = PropertyDelegate>::toLuaValue( + state, "value"); + EXPECT_TRUE(success) << "toLuaValue"; + std::string value = ""; + value = PropertyDelegate>::fromLuaValue( + state, success); + EXPECT_TRUE(success) << "fromLuaValue"; + EXPECT_EQ(value, "value") << "fromLuaValue"; } \ No newline at end of file diff --git a/tests/test_spicemanager.inl b/tests/test_spicemanager.inl index 35d21636de..ccf081a0fc 100644 --- a/tests/test_spicemanager.inl +++ b/tests/test_spicemanager.inl @@ -28,17 +28,17 @@ class SpiceManagerTest : public testing::Test{ protected: - SpiceManagerTest(){ - openspace::SpiceManager::initialize(); - } - ~SpiceManagerTest(){ - openspace::SpiceManager::deinitialize(); - } + SpiceManagerTest() { + //openspace::SpiceManager::initialize(); + } + ~SpiceManagerTest() { + //openspace::SpiceManager::deinitialize(); + } - void reset() { - openspace::SpiceManager::deinitialize(); - openspace::SpiceManager::initialize(); - } + void reset() { + openspace::SpiceManager::deinitialize(); + openspace::SpiceManager::initialize(); + } }; //global constants @@ -60,330 +60,344 @@ double abs_error = 0.00001; // In this testclass only a handset of the testfunctions require a single kernel. // The remaining methods rely on multiple kernels, loaded as a SPICE 'meta-kernel'. #define KERNEL(param) int kernelID = -1; \ - kernelID = openspace::SpiceManager::ref().loadKernel(param); \ - EXPECT_TRUE(kernelID != -1) << "loadKernel did not return proper id"; \ - return kernelID; \ + kernelID = openspace::SpiceManager::ref().loadKernel(param); \ + EXPECT_TRUE(kernelID != -1) << "loadKernel did not return proper id"; \ + return kernelID; \ int loadMetaKernel() { KERNEL(META); } int loadLSKKernel() { KERNEL(LSK); } int loadPCKKernel() { KERNEL(PCK); } std::string fileType(char type[]){ - std::string str(type); - return str; + std::string str(type); + return str; } + // Try loading single kernel -TEST_F(SpiceManagerTest, loadSingleKernel){ - loadLSKKernel(); - //naif0008.tls is a text file, check if loaded. - SpiceBoolean found; - kdata_c(0, "text", FILLEN, TYPLEN, SRCLEN, file, filtyp, source, &handle, &found); - - ASSERT_TRUE(found == SPICETRUE) << "Kernel not loaded"; - unload_c(LSK.c_str()); +TEST_F(SpiceManagerTest, loadSingleKernel) { + loadLSKKernel(); + // naif0008.tls is a text file, check if loaded. + SpiceBoolean found; + kdata_c(0, "text", FILLEN, TYPLEN, SRCLEN, file, filtyp, source, &handle, &found); + + ASSERT_TRUE(found == SPICETRUE) << "Kernel not loaded"; + unload_c(LSK.c_str()); } // Try loading multiple kernels via META file -TEST_F(SpiceManagerTest, loadMetaKernel){ - loadMetaKernel(); - // typeArr[] has values ordered to match each type of kernel - // as specified in the 'metaKernel.tm' file - std::string typeArr[nrMetaKernels] = { "META", "TEXT", "TEXT", - "SPK", "SPK", "SPK", - "TEXT", "CK", "TEXT" }; - // If one of the kernels does not load we expect a mismatch - for (int i = 0; i < nrMetaKernels; i++){ - SpiceBoolean found; - kdata_c(i, "all", FILLEN, TYPLEN, SRCLEN, file, filtyp, source, &handle, &found); - EXPECT_EQ(fileType(filtyp), typeArr[i]) << "One or more kernels did not load properly"; - } - unload_c(META.c_str()); +TEST_F(SpiceManagerTest, loadMetaKernel) { + loadMetaKernel(); + // typeArr[] has values ordered to match each type of kernel + // as specified in the 'metaKernel.tm' file + std::string typeArr[nrMetaKernels] = { "META", "TEXT", "TEXT", + "SPK", "SPK", "SPK", + "TEXT", "CK", "TEXT" }; + // If one of the kernels does not load we expect a mismatch + for (int i = 0; i < nrMetaKernels; i++){ + SpiceBoolean found; + kdata_c(i, "all", FILLEN, TYPLEN, SRCLEN, file, filtyp, source, &handle, &found); + EXPECT_EQ(fileType(filtyp), typeArr[i]) << "One or more kernels did not load properly"; + } + unload_c(META.c_str()); } + // Try unloading kernel using user assigned keyword -TEST_F(SpiceManagerTest, unloadKernelString){ - loadLSKKernel(); - //naif0008.tls is a text file, check if loaded. - SpiceBoolean found; - kdata_c(0, "text", FILLEN, TYPLEN, SRCLEN, file, filtyp, source, &handle, &found); - ASSERT_TRUE(found == SPICETRUE); +TEST_F(SpiceManagerTest, unloadKernelString) { + loadLSKKernel(); + // naif0008.tls is a text file, check if loaded. + SpiceBoolean found; + kdata_c(0, "text", FILLEN, TYPLEN, SRCLEN, file, filtyp, source, &handle, &found); + ASSERT_TRUE(found == SPICETRUE); - //unload using string keyword - openspace::SpiceManager::ref().unloadKernel(LSK); + // unload using string keyword + openspace::SpiceManager::ref().unloadKernel(LSK); - found = SPICEFALSE; - kdata_c(0, "text", FILLEN, TYPLEN, SRCLEN, file, filtyp, source, &handle, &found); - EXPECT_FALSE(found == SPICETRUE); + found = SPICEFALSE; + kdata_c(0, "text", FILLEN, TYPLEN, SRCLEN, file, filtyp, source, &handle, &found); + EXPECT_FALSE(found == SPICETRUE); } + // Try unloading kernel using integer as ID -TEST_F(SpiceManagerTest, unloadKernelInteger){ - int kernelID = loadLSKKernel(); - //naif0008.tls is a text file, check if loaded. - SpiceBoolean found; - kdata_c(0, "text", FILLEN, TYPLEN, SRCLEN, file, filtyp, source, &handle, &found); - ASSERT_TRUE(found == SPICETRUE); +TEST_F(SpiceManagerTest, unloadKernelInteger) { + int kernelID = loadLSKKernel(); + // naif0008.tls is a text file, check if loaded. + SpiceBoolean found; + kdata_c(0, "text", FILLEN, TYPLEN, SRCLEN, file, filtyp, source, &handle, &found); + ASSERT_TRUE(found == SPICETRUE); - //unload using unique int ID - openspace::SpiceManager::ref().unloadKernel(kernelID); + // unload using unique int ID + openspace::SpiceManager::ref().unloadKernel(kernelID); - found = SPICEFALSE; - kdata_c(0, "text", FILLEN, TYPLEN, SRCLEN, file, filtyp, source, &handle, &found); - EXPECT_FALSE(found == SPICETRUE) << "One or more kernels still present in kernel-pool"; + found = SPICEFALSE; + kdata_c(0, "text", FILLEN, TYPLEN, SRCLEN, file, filtyp, source, &handle, &found); + EXPECT_FALSE(found == SPICETRUE) << "One or more kernels still present in kernel-pool"; } + // Try unloading multiple kernels -TEST_F(SpiceManagerTest, unloadMetaKernel){ - loadMetaKernel(); - // The metakernel loads these kerneltypes in the exact order as in typeArr - std::string typeArr[nrMetaKernels] = { "META", "TEXT", "TEXT", - "SPK", "SPK", "SPK", - "TEXT", "CK", "TEXT" }; +TEST_F(SpiceManagerTest, unloadMetaKernel) { + loadMetaKernel(); + // The metakernel loads these kerneltypes in the exact order as in typeArr + std::string typeArr[nrMetaKernels] = { "META", "TEXT", "TEXT", + "SPK", "SPK", "SPK", + "TEXT", "CK", "TEXT" }; - for (int i = 0; i < nrMetaKernels; i++){ - // check kernelpool against typeArr - SpiceBoolean found; - kdata_c(i, "all", FILLEN, TYPLEN, SRCLEN, file, filtyp, source, &handle, &found); - EXPECT_EQ(fileType(filtyp), typeArr[i]) << "One or more kernels did not load properly"; - } - openspace::SpiceManager::ref().unloadKernel(META); + for (int i = 0; i < nrMetaKernels; i++) { + // check kernelpool against typeArr + SpiceBoolean found; + kdata_c(i, "all", FILLEN, TYPLEN, SRCLEN, file, filtyp, source, &handle, &found); + EXPECT_EQ(fileType(filtyp), typeArr[i]) << "One or more kernels did not load properly"; + } + openspace::SpiceManager::ref().unloadKernel(META); - for (int i = 0; i < nrMetaKernels; i++){ - // the values should by now be unloaded - SpiceBoolean found; - kdata_c(i, "all", FILLEN, TYPLEN, SRCLEN, file, filtyp, source, &handle, &found); - EXPECT_FALSE(found == SPICETRUE) << "Failed unloading kernel"; - } - unload_c(META.c_str()); + for (int i = 0; i < nrMetaKernels; i++) { + // the values should by now be unloaded + SpiceBoolean found; + kdata_c(i, "all", FILLEN, TYPLEN, SRCLEN, file, filtyp, source, &handle, &found); + EXPECT_FALSE(found == SPICETRUE) << "Failed unloading kernel"; + } + unload_c(META.c_str()); } + // Attempt finding a value in kernelpool -TEST_F(SpiceManagerTest, hasValue){ - loadPCKKernel(); +TEST_F(SpiceManagerTest, hasValue) { + loadPCKKernel(); - int naifId = 399; //Earth + int naifId = 399; // Earth - std::string kernelPoolValue = "RADII"; + std::string kernelPoolValue = "RADII"; - bool found = openspace::SpiceManager::ref().hasValue(naifId, kernelPoolValue); - ASSERT_TRUE(found) << "Could not find value for specified kernel"; - unload_c(PCK.c_str()); + bool found = openspace::SpiceManager::ref().hasValue(naifId, kernelPoolValue); + ASSERT_TRUE(found) << "Could not find value for specified kernel"; + unload_c(PCK.c_str()); } + // Get 1dim value from kernelpool -TEST_F(SpiceManagerTest, getValueFromID_1D){ - loadPCKKernel(); +TEST_F(SpiceManagerTest, getValueFromID_1D) { + loadPCKKernel(); - std::string target = "EARTH"; - std::string value1D = "MAG_NORTH_POLE_LAT"; + std::string target = "EARTH"; + std::string value1D = "MAG_NORTH_POLE_LAT"; - double return1D; - bool found = openspace::SpiceManager::ref().getValue(target, value1D, return1D); - ASSERT_TRUE(found) << "Could not retrieve value"; - EXPECT_EQ(return1D, 78.565) << "Value not found / differs from expected return"; - unload_c(PCK.c_str()); + double return1D; + ASSERT_NO_THROW(openspace::SpiceManager::ref().getValue(target, value1D, return1D)); + EXPECT_EQ(return1D, 78.565) << "Value not found / differs from expected return"; + unload_c(PCK.c_str()); } + // Get 2dim value from kernelpool -TEST_F(SpiceManagerTest, getValueFromID_3D){ - loadPCKKernel(); +TEST_F(SpiceManagerTest, getValueFromID_3D) { + loadPCKKernel(); - std::string target = "EARTH"; - std::string value3D = "RADII"; + std::string target = "EARTH"; + std::string value3D = "RADII"; - glm::dvec3 return3D; - openspace::SpiceManager::ref().getValue(target, value3D, return3D); + glm::dvec3 return3D; + ASSERT_NO_THROW(openspace::SpiceManager::ref().getValue(target, value3D, return3D)); - EXPECT_EQ(return3D.x, 6378.14) << "Value not found / differs from expected return"; - EXPECT_EQ(return3D.y, 6378.14) << "Value not found / differs from expected return"; - EXPECT_EQ(return3D.z, 6356.75) << "Value not found / differs from expected return"; - unload_c(PCK.c_str()); + EXPECT_EQ(return3D.x, 6378.14) << "Value not found / differs from expected return"; + EXPECT_EQ(return3D.y, 6378.14) << "Value not found / differs from expected return"; + EXPECT_EQ(return3D.z, 6356.75) << "Value not found / differs from expected return"; + unload_c(PCK.c_str()); } + // Get Ndim value from kernelpool -TEST_F(SpiceManagerTest, getValueFromID_ND){ - loadPCKKernel(); +TEST_F(SpiceManagerTest, getValueFromID_ND) { + loadPCKKernel(); - std::string target = "SATURN"; - std::string valueND = "RING6_A"; + std::string target = "SATURN"; + std::string valueND = "RING6_A"; - std::vector returnND(5); - bool found = openspace::SpiceManager::ref().getValue(target, valueND, returnND); - ASSERT_TRUE(found) << "Could not retrieve value for specified kernel"; + std::vector returnND(5); + ASSERT_NO_THROW(openspace::SpiceManager::ref().getValue(target, valueND, returnND)); - std::vector controlVec{ 189870.0, 256900.0, 9000.0, 9000.0, 0.000003 }; - - ASSERT_EQ(controlVec.size(), returnND.size()) << "Vectors differ in size"; + std::vector controlVec{ 189870.0, 256900.0, 9000.0, 9000.0, 0.000003 }; + + ASSERT_EQ(controlVec.size(), returnND.size()) << "Vectors differ in size"; - for (unsigned int i = 0; i < returnND.size(); ++i){ - EXPECT_EQ(controlVec[i], returnND[i]) << "Vector value not equal"; - } - unload_c(PCK.c_str()); + for (unsigned int i = 0; i < returnND.size(); ++i){ + EXPECT_EQ(controlVec[i], returnND[i]) << "Vector value not equal"; + } + unload_c(PCK.c_str()); } + // Try converting string to Ephemeris time -TEST_F(SpiceManagerTest, stringToEphemerisTime){ - loadLSKKernel(); +TEST_F(SpiceManagerTest, stringToEphemerisTime) { + loadLSKKernel(); - double ephemerisTime; - double control_ephemerisTime; - char date[SRCLEN] = "Thu Mar 20 12:53:29 PST 1997"; - str2et_c(date, &control_ephemerisTime); + double ephemerisTime; + double control_ephemerisTime; + char date[SRCLEN] = "Thu Mar 20 12:53:29 PST 1997"; + str2et_c(date, &control_ephemerisTime); - bool success = openspace::SpiceManager::ref().getETfromDate(date, ephemerisTime); - EXPECT_EQ(success, true); - - EXPECT_EQ(ephemerisTime, control_ephemerisTime) << "Ephemeries times differ / not found"; - unload_c(LSK.c_str()); + ASSERT_NO_THROW(ephemerisTime = openspace::SpiceManager::ref().ephemerisTimeFromDate(date)); + + EXPECT_EQ(ephemerisTime, control_ephemerisTime) << "Ephemeries times differ / not found"; + unload_c(LSK.c_str()); } + // Try getting positional vector of target -TEST_F(SpiceManagerTest, getTargetPosition){ - loadMetaKernel(); +TEST_F(SpiceManagerTest, getTargetPosition) { + using openspace::SpiceManager; + loadMetaKernel(); - double et; - double pos[3]; - double lt; - char utctime[SRCLEN] = "2004 jun 11 19:32:00"; + double et; + double pos[3]; + double lt; + char utctime[SRCLEN] = "2004 jun 11 19:32:00"; - str2et_c(utctime, &et); - spkpos_c("EARTH", et, "J2000", "LT+S", "CASSINI", pos, <); + str2et_c(utctime, &et); + spkpos_c("EARTH", et, "J2000", "LT+S", "CASSINI", pos, <); - glm::dvec3 targetPosition; - double lightTime = 0.0; - bool found = openspace::SpiceManager::ref().getTargetPosition("EARTH", "CASSINI", "J2000", "LT+S", et, - targetPosition, lightTime); - ASSERT_TRUE(found); - EXPECT_DOUBLE_EQ(pos[0], targetPosition[0]) << "Position not found or differs from expected return"; - EXPECT_DOUBLE_EQ(pos[1], targetPosition[1]) << "Position not found or differs from expected return"; - EXPECT_DOUBLE_EQ(pos[2], targetPosition[2]) << "Position not found or differs from expected return"; - unload_c(META.c_str()); + glm::dvec3 targetPosition; + double lightTime = 0.0; + SpiceManager::AberrationCorrection corr = { + SpiceManager::AberrationCorrection::Type::LightTimeStellar, + SpiceManager::AberrationCorrection::Direction::Reception + }; + + ASSERT_NO_THROW(targetPosition = SpiceManager::ref().targetPosition( + "EARTH", "CASSINI", "J2000", corr, et, lightTime) + ); + EXPECT_DOUBLE_EQ(pos[0], targetPosition[0]) << "Position not found or differs from expected return"; + EXPECT_DOUBLE_EQ(pos[1], targetPosition[1]) << "Position not found or differs from expected return"; + EXPECT_DOUBLE_EQ(pos[2], targetPosition[2]) << "Position not found or differs from expected return"; + unload_c(META.c_str()); } + // Try getting position & velocity vectors of target -TEST_F(SpiceManagerTest, getTargetState){ - loadMetaKernel(); +TEST_F(SpiceManagerTest, getTargetState) { + using openspace::SpiceManager; + loadMetaKernel(); - double et; - double state[6]; - double lt; - char utctime[SRCLEN] = "2004 jun 11 19:32:00"; + double et; + double state[6]; + double lt; + char utctime[SRCLEN] = "2004 jun 11 19:32:00"; - str2et_c(utctime, &et); - spkezr_c("EARTH", et, "J2000", "LT+S", "CASSINI", state, <); + str2et_c(utctime, &et); + spkezr_c("EARTH", et, "J2000", "LT+S", "CASSINI", state, <); - glm::dvec3 targetPosition; - glm::dvec3 targetVelocity; - double lightTime = 0.0; - bool found = openspace::SpiceManager::ref().getTargetState("EARTH", "CASSINI", "J2000", "LT+S", et, - targetPosition, targetVelocity, lightTime); - ASSERT_TRUE(found); - //x,y,z - for (int i = 0; i < 3; i++){ - EXPECT_DOUBLE_EQ(state[i], targetPosition[i]) << "Position not found or differs from expected return"; - EXPECT_DOUBLE_EQ(state[i+3], targetVelocity[i]) << "Velocity not found or differs from expected return"; - } - unload_c(META.c_str()); + SpiceManager::AberrationCorrection corr = { + SpiceManager::AberrationCorrection::Type::LightTimeStellar, + SpiceManager::AberrationCorrection::Direction::Reception + }; + + SpiceManager::TargetStateResult res; + ASSERT_NO_THROW(res = SpiceManager::ref().targetState("EARTH", "CASSINI", "J2000", corr, et)); + + // x,y,z + for (int i = 0; i < 3; i++){ + EXPECT_DOUBLE_EQ(state[i], res.position[i]) << "Position not found or differs from expected return"; + EXPECT_DOUBLE_EQ(state[i+3], res.velocity[i]) << "Velocity not found or differs from expected return"; + } + unload_c(META.c_str()); } + // Try getting transformation matrix and transform position and velocity into new reference frame -TEST_F(SpiceManagerTest, getStateTransformMatrix){ - loadMetaKernel(); +TEST_F(SpiceManagerTest, getStateTransformMatrix) { + loadMetaKernel(); - double et; - double state[6]; - double state_t[6]; - double lt; - double referenceMatrix[6][6]; + double et; + double state[6]; + double state_t[6]; + double lt; + double referenceMatrix[6][6]; - str2et_c("2004 jun 11 19:32:00", &et); - spkezr_c("PHOEBE", et, "J2000", "LT+S", "CASSINI", state, <); - sxform_c("J2000", "IAU_PHOEBE", et, referenceMatrix); + str2et_c("2004 jun 11 19:32:00", &et); + spkezr_c("PHOEBE", et, "J2000", "LT+S", "CASSINI", state, <); + sxform_c("J2000", "IAU_PHOEBE", et, referenceMatrix); - glm::dvec3 position(state[0], state[1], state[2]); - glm::dvec3 velocity(state[3], state[4], state[5]); + glm::dvec3 position(state[0], state[1], state[2]); + glm::dvec3 velocity(state[3], state[4], state[5]); - openspace::SpiceManager::TransformMatrix stateMatrix; - bool found = openspace::SpiceManager::ref().getStateTransformMatrix("J2000", - "IAU_PHOEBE", - et, - stateMatrix); - ASSERT_TRUE(found); - //check for matrix consistency - for (int i = 0; i < 6; i++){ - for (int j = 0; j < 6; j++){ - EXPECT_DOUBLE_EQ(referenceMatrix[i][j], stateMatrix[i * 6 + j]) << "State-matrix not set or has wrong values"; - } - } - mxvg_c(referenceMatrix, state, 6, 6, state_t); + openspace::SpiceManager::TransformMatrix stateMatrix; + ASSERT_NO_THROW(stateMatrix = openspace::SpiceManager::ref().stateTransformMatrix( + "J2000", "IAU_PHOEBE", et)); + + // check for matrix consistency + for (int i = 0; i < 6; i++) { + for (int j = 0; j < 6; j++) { + EXPECT_DOUBLE_EQ(referenceMatrix[i][j], stateMatrix[i * 6 + j]) << "State-matrix not set or has wrong values"; + } + } + mxvg_c(referenceMatrix, state, 6, 6, state_t); - for (int i = 0; i < 3; i++){ - EXPECT_DOUBLE_EQ(position[i], state_t[i]) << "Position vector differs from its reference"; - EXPECT_DOUBLE_EQ(velocity[i], state_t[i + 3]) << "Velocity vector differs from its reference"; - } - unload_c(META.c_str()); + for (int i = 0; i < 3; i++) { + EXPECT_DOUBLE_EQ(position[i], state_t[i]) << "Position vector differs from its reference"; + EXPECT_DOUBLE_EQ(velocity[i], state_t[i + 3]) << "Velocity vector differs from its reference"; + } + unload_c(META.c_str()); } + // Try getting transformation matrix and transform the position only into new reference frame -TEST_F(SpiceManagerTest, getPositionTransformMatrix){ - loadMetaKernel(); +TEST_F(SpiceManagerTest, getPositionTransformMatrix) { + using openspace::SpiceManager; + loadMetaKernel(); - double et; - double state[3] = { 1.0, 1.0, 1.0 }; - double state_t[3]; - double referenceMatrix[3][3]; + double et; + double state[3] = { 1.0, 1.0, 1.0 }; + double state_t[3]; + double referenceMatrix[3][3]; - str2et_c("2004 jun 11 19:32:00", &et); - pxform_c("CASSINI_HGA", "J2000", et, referenceMatrix); + str2et_c("2004 jun 11 19:32:00", &et); + pxform_c("CASSINI_HGA", "J2000", et, referenceMatrix); - glm::dmat3 positionMatrix; - glm::dvec3 position(state[0], state[1], state[2]); - bool found = openspace::SpiceManager::ref().getPositionTransformMatrix("CASSINI_HGA", - "J2000", - et, - positionMatrix); - ASSERT_TRUE(found); - //check for matrix consistency - for (int i = 0; i < 3; i++){ - for (int j = 0; j < 3; j++){ - EXPECT_DOUBLE_EQ(referenceMatrix[i][j], positionMatrix[j][i]) << "Position-matrix not set or has wrong values"; - } - } - //transform reference position into new frame - mxvg_c(referenceMatrix, state, 3, 3, state_t); + glm::dmat3 positionMatrix; + glm::dvec3 position(state[0], state[1], state[2]); + ASSERT_NO_THROW(positionMatrix = SpiceManager::ref().positionTransformMatrix( + "CASSINI_HGA", "J2000", et) + ); - position = positionMatrix * position; - //check transformed values match - for (int i = 0; i < 3; i++){ - EXPECT_DOUBLE_EQ(position[i], state_t[i]) << "Position vector differs from its reference"; - } - unload_c(META.c_str()); + // check for matrix consistency + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + EXPECT_DOUBLE_EQ(referenceMatrix[i][j], positionMatrix[j][i]) << "Position-matrix not set or has wrong values"; + } + } + // transform reference position into new frame + mxvg_c(referenceMatrix, state, 3, 3, state_t); + + position = positionMatrix * position; + // check transformed values match + for (int i = 0; i < 3; i++) { + EXPECT_DOUBLE_EQ(position[i], state_t[i]) << "Position vector differs from its reference"; + } + unload_c(META.c_str()); } + // Try to get boresight vector and instrument field of view boundary vectors -TEST_F(SpiceManagerTest, getFieldOfView){ - loadMetaKernel(); - - SpiceInt n; - SpiceInt cassini_ID; - double et; - glm::dvec3 boresight; - double bounds_ref[5][3]; - char shape_ref[TYPLEN]; - char name_ref[FILLEN]; - double boresightVec[3]; +TEST_F(SpiceManagerTest, getFieldOfView) { + using openspace::SpiceManager; + loadMetaKernel(); + + SpiceInt n; + SpiceInt cassini_ID; + double et; + glm::dvec3 boresight; + double bounds_ref[5][3]; + char shape_ref[TYPLEN]; + char name_ref[FILLEN]; + double boresightVec[3]; - str2et_c("2004 jun 11 19:32:00", &et); - SpiceBoolean found; - bodn2c_c("CASSINI_ISS_NAC", &cassini_ID, &found); - ASSERT_TRUE(found == SPICETRUE) << "Cannot locate ID for Cassini"; + str2et_c("2004 jun 11 19:32:00", &et); + SpiceBoolean found; + bodn2c_c("CASSINI_ISS_NAC", &cassini_ID, &found); + ASSERT_TRUE(found == SPICETRUE) << "Cannot locate ID for Cassini"; - getfov_c(cassini_ID, 5, TYPLEN, TYPLEN, shape_ref, name_ref, boresightVec, &n, bounds_ref); + getfov_c(cassini_ID, 5, TYPLEN, TYPLEN, shape_ref, name_ref, boresightVec, &n, bounds_ref); - std::string shape, name; - shape.resize(32); - name.resize(32); - std::vector bounds; - found = openspace::SpiceManager::ref().getFieldOfView("CASSINI_ISS_NAC", - shape, - name, - boresight, - bounds); - ASSERT_TRUE(found == SPICETRUE); - //check vectors have correct values - for (int i = 0; i < bounds.size(); i++){ - for (int j = 0; j < 3; j++){ - EXPECT_DOUBLE_EQ(bounds_ref[i][j], bounds[i][j]) << "One or more Field of View Boundary vectors \ - differ from expected output"; - } - } - unload_c(META.c_str()); + SpiceManager::FieldOfViewResult res; + + ASSERT_NO_THROW(res = SpiceManager::ref().fieldOfView("CASSINI_ISS_NAC")); + + ASSERT_TRUE(found == SPICETRUE); + //check vectors have correct values + for (int i = 0; i < res.bounds.size(); i++){ + for (int j = 0; j < 3; j++){ + EXPECT_DOUBLE_EQ(bounds_ref[i][j], res.bounds[i][j]) << "One or more Field of View Boundary vectors \ + differ from expected output"; + } + } + unload_c(META.c_str()); }