diff --git a/config/flareConfig.txt b/config/flareConfig.txt index c58f00c202..4a78ba7d30 100644 --- a/config/flareConfig.txt +++ b/config/flareConfig.txt @@ -1,8 +1,8 @@ # Filenames # Don't change during runtime # (Transfer function values can be changed during runtime though) -tsp_filename /home/hhellteg/data/enlil_128_256_32.tsp -transferfunction_filename ../config/transferfunctions/fire.txt +tsp_filename ${OPENSPACE_DATA}/enlil_64_32_8.tsp +transferfunction_filename ${CONFIG}/transferfunctions/fire.txt # Window dimensions # Don't change during runtime @@ -26,7 +26,7 @@ local_worksize_y 16 # Scaling division to make textures smaller # Saves OpenCL threads # (A factor of 2 results in half the number of threads per dimension etc) -texture_division_factor 1 +texture_division_factor 1 # Error tolerances # Use -1 for no tolerance @@ -48,12 +48,12 @@ raycaster_intensity 1.0 animator_refresh_interval 0.05 # Various paths -raycaster_kernel_filename ../kernels/RaycasterTSP.cl -tsp_traversal_kernel_filename ../kernels/TSPTraversal.cl -cube_shader_vert_filename ../shaders/cubeVert.glsl -cube_shader_frag_filename ../shaders/cubeFrag.glsl -quad_shader_vert_filename ../shaders/quadVert.glsl -quad_shader_frag_filename ../shaders/quadFrag.glsl +raycaster_kernel_filename ${KERNELS}/RaycasterTSP.cl +tsp_traversal_kernel_filename ${KERNELS}/TSPTraversal.cl +cube_shader_vert_filename ${SHADERS}/cubeVert.glsl +cube_shader_frag_filename ${SHADERS}/cubeFrag.glsl +quad_shader_vert_filename ${SHADERS}/quadVert.glsl +quad_shader_frag_filename ${SHADERS}/quadFrag.glsl # Model start_pitch -20.0 diff --git a/config/single.xml b/config/sgct/single.xml similarity index 94% rename from config/single.xml rename to config/sgct/single.xml index 6e7cd6db55..bb27080161 100644 --- a/config/single.xml +++ b/config/sgct/single.xml @@ -4,7 +4,7 @@ - + diff --git a/config/single_fisheye.xml b/config/sgct/single_fisheye.xml similarity index 100% rename from config/single_fisheye.xml rename to config/sgct/single_fisheye.xml diff --git a/config/single_sbs_stereo.xml b/config/sgct/single_sbs_stereo.xml similarity index 100% rename from config/single_sbs_stereo.xml rename to config/sgct/single_sbs_stereo.xml diff --git a/config/single_two_win.xml b/config/sgct/single_two_win.xml similarity index 100% rename from config/single_two_win.xml rename to config/sgct/single_two_win.xml diff --git a/ext/ghoul b/ext/ghoul index 92fd3508c1..0d1857cb2b 160000 --- a/ext/ghoul +++ b/ext/ghoul @@ -1 +1 @@ -Subproject commit 92fd3508c138111f3367973686480e1f232104fc +Subproject commit 0d1857cb2b43054ba0c98191614532cfab9be34c diff --git a/src/openspaceengine.h b/include/openspace/engine/openspaceengine.h similarity index 78% rename from src/openspaceengine.h rename to include/openspace/engine/openspaceengine.h index 659515dfc9..35af715048 100644 --- a/src/openspaceengine.h +++ b/include/openspace/engine/openspaceengine.h @@ -25,13 +25,13 @@ #ifndef __OPENSPACEENGINE_H__ #define __OPENSPACEENGINE_H__ -#include "interaction/interactionhandler.h" -#include "rendering/renderengine.h" +#include +#include #include +#include -#include -#include -//#include +#include +#include namespace openspace { @@ -44,13 +44,19 @@ public: Flare }; - static void create(int argc, char** argv, int& newArgc, char**& newArgv); + static void create(int argc, char** argv, std::vector& sgctArguments); static void destroy(); static OpenSpaceEngine& ref(); + static bool isInitialized(); bool initialize(); void setRenderer(OpenSpaceEngine::Renderers renderer); + + static bool registerPathsFromDictionary(const ghoul::Dictionary& dictionary); + static bool registerBasePathFromConfigurationFile(const std::string& filename); + static bool findConfiguration(std::string& filename) ; + ghoul::ConfigurationManager& configurationManager(); InteractionHandler& interactionHandler(); RenderEngine& renderEngine(); @@ -65,6 +71,7 @@ public: void mouseButtonCallback(int key, int action); void mousePositionCallback(int x, int y); void mouseScrollWheelCallback(int pos); + void encode(); void decode(); @@ -80,46 +87,11 @@ private: InteractionHandler* _interactionHandler; RenderEngine* _renderEngine; ScriptEngine* _scriptEngine; -// Interface* _interface; bool _useVolumeRaycaster, _useFlare; }; #define OsEng (openspace::OpenSpaceEngine::ref()) - /* -class RenderEngine: public Object { -public: - - // constructors & destructor - RenderEngine(int argc, char **argv); - ~RenderEngine(); - - // sgct wrapped functions - bool init(); - void preSync(); - void postSyncPreDraw(); - void render(); - void postDraw(); - void keyboardCallback(int key, int action); - void mouseButtonCallback(int key, int action); - void mousePosCallback(int x, int y); - void mouseScrollCallback(int pos); - - // object extensions - virtual void encode(); - virtual void decode(); - -private: - double masterTime_; - Camera *mainCamera_; - //MouseExternalControl *mouseControl_; - //KeyboardExternalControl *keyboardControl_; - - SceneGraph *sceneGraph_; - glm::vec3 eyePosition_; -}; -*/ - } // namespace openspace #endif // __OPENSPACEENGINE_H__ diff --git a/src/flare/Animator.h b/include/openspace/flare/Animator.h similarity index 100% rename from src/flare/Animator.h rename to include/openspace/flare/Animator.h diff --git a/src/flare/BrickManager.h b/include/openspace/flare/BrickManager.h similarity index 95% rename from src/flare/BrickManager.h rename to include/openspace/flare/BrickManager.h index 6f05f59c44..f4d077227f 100644 --- a/src/flare/BrickManager.h +++ b/include/openspace/flare/BrickManager.h @@ -13,6 +13,7 @@ #include #include #include +#include // Make sure we get 64 bits for offset #define _FILE_OFFSET_BITS 64 @@ -21,7 +22,6 @@ namespace osp { -class Texture3D; class Config; class BrickManager { @@ -53,7 +53,7 @@ public: return brickLists_[_bufIdx]; } - Texture3D * TextureAtlas() { return textureAtlas_; } + ghoul::opengl::Texture * TextureAtlas() { return textureAtlas_; } // Header accessors unsigned int GridType() const { return gridType_; } @@ -106,13 +106,13 @@ private: int zCoord_; // Texture where the actual atlas is kept - Texture3D *textureAtlas_; + ghoul::opengl::Texture *textureAtlas_; std::vector > brickLists_; // C-style I/O std::FILE *file_; - off dataPos_; + off_t dataPos_; bool hasReadHeader_; bool atlasInitialized_; diff --git a/src/flare/CLManager.h b/include/openspace/flare/CLManager.h similarity index 87% rename from src/flare/CLManager.h rename to include/openspace/flare/CLManager.h index ac3741c318..614f93aed4 100644 --- a/src/flare/CLManager.h +++ b/include/openspace/flare/CLManager.h @@ -6,18 +6,19 @@ #ifndef CL_MANAGER_H_ #define CL_MANAGER_H_ -#ifndef _WIN32 -#include -#else -#include -#endif +#include +#include +#include +#include +#include +#include +#include #include #include -#include +#include namespace osp { -class Texture; class TransferFunction; class CLProgram; class TSP; @@ -48,11 +49,11 @@ public: // Add an OpenGL texture to a program bool AddTexture(std::string _programName, unsigned int _argNr, - Texture *_texture, TextureType _textureType, + ghoul::opengl::Texture *_texture, TextureType _textureType, Permissions _permissions); bool AddTexture(std::string _programName, unsigned int _argNr, - Texture *_texture, TextureType _textureType, + ghoul::opengl::Texture *_texture, TextureType _textureType, Permissions _permissions, cl_mem& _clTextureMem); bool AddTexture(std::string _programName, unsigned int _argNr, @@ -120,11 +121,13 @@ private: char deviceName_[MAX_NAME_LENGTH]; char driverVersion_[MAX_NAME_LENGTH]; char platformVersion_[MAX_NAME_LENGTH]; - cl_context context_; - cl_command_queue commandQueues_[NUM_QUEUE_INDICES]; + //cl_context context_; + ghoul::opencl::CLCommandQueue commandQueues_[NUM_QUEUE_INDICES]; // Programs are mapped using strings std::map clPrograms_; + + ghoul::opencl::CLContext _context; }; diff --git a/src/flare/CLProgram.h b/include/openspace/flare/CLProgram.h similarity index 88% rename from src/flare/CLProgram.h rename to include/openspace/flare/CLProgram.h index bc80eede1e..0eadab5b60 100644 --- a/src/flare/CLProgram.h +++ b/include/openspace/flare/CLProgram.h @@ -6,14 +6,11 @@ #ifndef CL_PROGRAM_H_ #define CL_PROGRAM_H_ -#ifndef _WIN32 -#include -#else -#include -#endif +#include #include #include -#include +#include +#include namespace osp { @@ -40,11 +37,11 @@ public: bool BuildProgram(); bool CreateKernel(); - bool AddTexture(unsigned int _argNr, Texture *_texture, + bool AddTexture(unsigned int _argNr, ghoul::opengl::Texture *_texture, GLuint _textureType, cl_mem_flags _permissions); - bool AddTexture(unsigned int _argNr, Texture *_texture, + bool AddTexture(unsigned int _argNr, ghoul::opengl::Texture *_texture, GLuint _textureType, cl_mem_flags _permissions, cl_mem& _clTextureMem); diff --git a/src/flare/Config.h b/include/openspace/flare/Config.h similarity index 100% rename from src/flare/Config.h rename to include/openspace/flare/Config.h diff --git a/src/flare/KernelConstants.h b/include/openspace/flare/KernelConstants.h similarity index 100% rename from src/flare/KernelConstants.h rename to include/openspace/flare/KernelConstants.h diff --git a/src/flare/MappingKey.h b/include/openspace/flare/MappingKey.h similarity index 97% rename from src/flare/MappingKey.h rename to include/openspace/flare/MappingKey.h index 28d4cbd2c2..462a723135 100644 --- a/src/flare/MappingKey.h +++ b/include/openspace/flare/MappingKey.h @@ -9,7 +9,7 @@ for which the key is active, and RGBA values for that specific intensity. */ #include -#include +#include namespace osp { diff --git a/src/flare/Raycaster.h b/include/openspace/flare/Raycaster.h similarity index 79% rename from src/flare/Raycaster.h rename to include/openspace/flare/Raycaster.h index ef86c18857..833877a55f 100644 --- a/src/flare/Raycaster.h +++ b/include/openspace/flare/Raycaster.h @@ -8,25 +8,21 @@ together. Manages state, render calls and a lot of initializations. TODO: Iteratively break away parts from it into other classes. */ -#include +#include #include #include #include #include -#ifndef _WIN32 -#include -#else -#include -#endif -#include +#include +#include #include -#include +#include + +#include +#include namespace osp { -class ShaderProgram; -class Texture2D; -class Texture3D; class TransferFunction; class Animator; class BrickManager; @@ -64,7 +60,7 @@ public: // Update matrices with current view parameters bool UpdateMatrices(); // Bind transformation matrices to a ShaderProgram - bool BindTransformationMatrices(ShaderProgram *_program); + bool BindTransformationMatrices(ghoul::opengl::ProgramObject *_program); // Read kernel config from file and voxel data, // update the constants that get sent to the kernel every frame bool UpdateKernelConfig(); @@ -74,16 +70,16 @@ public: // TODO Actually support and make use of multiple TFs void AddTransferFunction(TransferFunction *_transferFunction); - Texture2D * CubeFrontTexture() const { return cubeFrontTex_; } - Texture2D * CubeBackTexture() const { return cubeBackTex_; } - Texture2D * QuadTexture() const { return quadTex_; } + ghoul::opengl::Texture * CubeFrontTexture() const { return cubeFrontTex_; } + ghoul::opengl::Texture * CubeBackTexture() const { return cubeBackTex_; } + ghoul::opengl::Texture * QuadTexture() const { return quadTex_; } void SetKernelConfigFilename(const std::string &_filename); - void SetCubeFrontTexture(Texture2D *_cubeFrontTexture); - void SetCubeBackTexture(Texture2D *_cubeBackTexture); - void SetQuadTexture(Texture2D *_quadTexture); - void SetCubeShaderProgram(ShaderProgram *_cubeShaderProgram); - void SetQuadShaderProgram(ShaderProgram *_quadShaderProgram); + void SetCubeFrontTexture(ghoul::opengl::Texture *_cubeFrontTexture); + void SetCubeBackTexture(ghoul::opengl::Texture *_cubeBackTexture); + void SetQuadTexture(ghoul::opengl::Texture *_quadTexture); + void SetCubeShaderProgram(ghoul::opengl::ProgramObject *_cubeShaderProgram); + void SetQuadShaderProgram(ghoul::opengl::ProgramObject *_quadShaderProgram); void SetAnimator(Animator *_animator); void SetCLManager(CLManager *_clManager); void SetBrickManager(BrickManager *_brickManager); @@ -112,13 +108,13 @@ private: unsigned int cubePositionAttrib_; unsigned int quadPositionAttrib_; // Shaders - ShaderProgram *cubeShaderProgram_; - ShaderProgram *quadShaderProgram_; + ghoul::opengl::ProgramObject *cubeShaderProgram_; + ghoul::opengl::ProgramObject *quadShaderProgram_; // Textures - Texture2D *cubeFrontTex_; - Texture2D *cubeBackTex_; - Texture2D *quadTex_; - Texture3D *volumeTex_; + ghoul::opengl::Texture *cubeFrontTex_; + ghoul::opengl::Texture *cubeBackTex_; + ghoul::opengl::Texture *quadTex_; + ghoul::opengl::Texture *volumeTex_; // Model params float pitch_; float yaw_; @@ -189,6 +185,10 @@ private: // Timer and timer constants boost::timer::cpu_timer timer_; + + + cl_mem cubeFrontCLmem; + cl_mem cubeBackCLmem; }; } diff --git a/src/flare/Renderer.h b/include/openspace/flare/Renderer.h similarity index 100% rename from src/flare/Renderer.h rename to include/openspace/flare/Renderer.h diff --git a/src/flare/TSP.h b/include/openspace/flare/TSP.h similarity index 99% rename from src/flare/TSP.h rename to include/openspace/flare/TSP.h index fbaced99fb..0e55448860 100644 --- a/src/flare/TSP.h +++ b/include/openspace/flare/TSP.h @@ -139,7 +139,7 @@ private: //std::ios::pos_type dataPos_; // Position of first data entry (after header) - off dataPos_; + off_t dataPos_; // Calculate weighted square distance between two RGBA colors // c2 should be an averaged or zero color diff --git a/src/flare/Timer.h b/include/openspace/flare/Timer.h similarity index 100% rename from src/flare/Timer.h rename to include/openspace/flare/Timer.h diff --git a/src/flare/TransferFunction.h b/include/openspace/flare/TransferFunction.h similarity index 91% rename from src/flare/TransferFunction.h rename to include/openspace/flare/TransferFunction.h index 452d0f2f5c..6ad4110ffc 100644 --- a/src/flare/TransferFunction.h +++ b/include/openspace/flare/TransferFunction.h @@ -9,14 +9,14 @@ interpolating between the MappingKey values. TODO Use Texture1D for implementation when OpenCL 1.2 is supported */ -#include +#include #include #include #include +#include namespace osp { -class Texture2D; class TransferFunction { public: @@ -48,7 +48,7 @@ public: // Accessors unsigned int Width() const { return width_; } - Texture2D * Texture() { return texture_; } + ghoul::opengl::Texture * Texture() { return texture_; } // TODO temp float * FloatData() { return floatData_; } @@ -61,7 +61,7 @@ private: TransferFunction(const TransferFunction &_tf); float *floatData_; - Texture2D *texture_; + ghoul::opengl::Texture *texture_; unsigned int width_; float lower_; float upper_; diff --git a/src/flare/Utils.h b/include/openspace/flare/Utils.h similarity index 100% rename from src/flare/Utils.h rename to include/openspace/flare/Utils.h diff --git a/src/flare/flare.h b/include/openspace/flare/flare.h similarity index 93% rename from src/flare/flare.h rename to include/openspace/flare/flare.h index a3910033ce..30bab287e3 100644 --- a/src/flare/flare.h +++ b/include/openspace/flare/flare.h @@ -26,17 +26,16 @@ #define __FLARE_H__ #include +#include #include - #include - -#include -#include -#include +#include +#include +#include namespace openspace { -class Flare : public Renderable { +class Flare { public: Flare(); ~Flare(); @@ -44,8 +43,6 @@ public: // This is where the magic happens void render(const Camera *camera = nullptr, const psc &thisPosition = psc(glm::vec3(0))); - // SGCT functions for cluster rendering and interaction. - // Called from OpenspaceEngine. void keyboard(int key, int action); void mouse(int button, int action); void preSync(); diff --git a/src/interaction/deviceidentifier.h b/include/openspace/interaction/deviceidentifier.h similarity index 100% rename from src/interaction/deviceidentifier.h rename to include/openspace/interaction/deviceidentifier.h diff --git a/src/interaction/externalcontrol/externalconnectioncontroller.h b/include/openspace/interaction/externalcontrol/externalconnectioncontroller.h similarity index 85% rename from src/interaction/externalcontrol/externalconnectioncontroller.h rename to include/openspace/interaction/externalcontrol/externalconnectioncontroller.h index 8eecd53f90..4d45937c59 100644 --- a/src/interaction/externalcontrol/externalconnectioncontroller.h +++ b/include/openspace/interaction/externalcontrol/externalconnectioncontroller.h @@ -1,7 +1,7 @@ #ifndef EXTERNALCONNECTIONCONTROLLER_H #define EXTERNALCONNECTIONCONTROLLER_H -#include "interaction/externalcontrol/externalcontrol.h" +#include #include namespace openspace { diff --git a/src/interaction/externalcontrol/externalcontrol.h b/include/openspace/interaction/externalcontrol/externalcontrol.h similarity index 93% rename from src/interaction/externalcontrol/externalcontrol.h rename to include/openspace/interaction/externalcontrol/externalcontrol.h index 6b12c3c75c..6a38aa0a29 100644 --- a/src/interaction/externalcontrol/externalcontrol.h +++ b/include/openspace/interaction/externalcontrol/externalcontrol.h @@ -1,7 +1,7 @@ #ifndef EXTERNALCONTROL_H #define EXTERNALCONTROL_H -#include "util/pss.h" +#include #include #include diff --git a/src/interaction/externalcontrol/joystickexternalcontrol.h b/include/openspace/interaction/externalcontrol/joystickexternalcontrol.h similarity index 100% rename from src/interaction/externalcontrol/joystickexternalcontrol.h rename to include/openspace/interaction/externalcontrol/joystickexternalcontrol.h diff --git a/src/interaction/externalcontrol/keyboardexternalcontrol.h b/include/openspace/interaction/externalcontrol/keyboardexternalcontrol.h similarity index 100% rename from src/interaction/externalcontrol/keyboardexternalcontrol.h rename to include/openspace/interaction/externalcontrol/keyboardexternalcontrol.h diff --git a/src/interaction/externalcontrol/mouseexternalcontrol.h b/include/openspace/interaction/externalcontrol/mouseexternalcontrol.h similarity index 100% rename from src/interaction/externalcontrol/mouseexternalcontrol.h rename to include/openspace/interaction/externalcontrol/mouseexternalcontrol.h diff --git a/src/interaction/externalcontrol/pythonexternalcontrol.h b/include/openspace/interaction/externalcontrol/pythonexternalcontrol.h similarity index 100% rename from src/interaction/externalcontrol/pythonexternalcontrol.h rename to include/openspace/interaction/externalcontrol/pythonexternalcontrol.h diff --git a/src/interaction/externalcontrol/randomexternalcontrol.h b/include/openspace/interaction/externalcontrol/randomexternalcontrol.h similarity index 85% rename from src/interaction/externalcontrol/randomexternalcontrol.h rename to include/openspace/interaction/externalcontrol/randomexternalcontrol.h index a552ff54ba..2cc189f4c5 100644 --- a/src/interaction/externalcontrol/randomexternalcontrol.h +++ b/include/openspace/interaction/externalcontrol/randomexternalcontrol.h @@ -4,7 +4,7 @@ #include #include -#include "interaction/externalcontrol/externalcontrol.h" +#include namespace openspace { diff --git a/src/interaction/interactionhandler.h b/include/openspace/interaction/interactionhandler.h similarity index 83% rename from src/interaction/interactionhandler.h rename to include/openspace/interaction/interactionhandler.h index 393fdea4a5..a27b27986d 100644 --- a/src/interaction/interactionhandler.h +++ b/include/openspace/interaction/interactionhandler.h @@ -2,9 +2,9 @@ #define INTERACTIONHANDLER_H // open space includes -#include "util/camera.h" -#include "externalcontrol/externalcontrol.h" -#include "scenegraph/scenegraphnode.h" +#include +#include +#include // std includes #include @@ -12,17 +12,6 @@ #include #include -// hack until we have a file/path manager -//#ifdef __WIN32__ -//#ifdef NDEBUG -//#define RELATIVE_PATH "" -//#else -//#define RELATIVE_PATH "../../../" -//#endif -//#else -//#define RELATIVE_PATH "../" -//#endif - namespace openspace { class InteractionHandler { diff --git a/src/query/query.h b/include/openspace/query/query.h similarity index 100% rename from src/query/query.h rename to include/openspace/query/query.h diff --git a/src/rendering/renderable.h b/include/openspace/rendering/renderable.h similarity index 57% rename from src/rendering/renderable.h rename to include/openspace/rendering/renderable.h index 389437c4e7..7bdf38c926 100644 --- a/src/rendering/renderable.h +++ b/include/openspace/rendering/renderable.h @@ -2,26 +2,30 @@ #define RENDERABLE_H // open space includes -#include "util/psc.h" -#include "util/pss.h" -#include "util/camera.h" +#include +#include +#include +#include namespace openspace { class Renderable { public: - + // constructors & destructor - Renderable(); - Renderable(const pss &boundingSphere); - virtual ~Renderable(); + Renderable(const ghoul::Dictionary& dictionary); + virtual ~Renderable(); + virtual bool initialize() = 0; + virtual bool deinitialize() = 0; + void setBoundingSphere(const pss &boundingSphere); const pss &getBoundingSphere(); virtual void render(const Camera *camera, const psc &thisPosition) = 0; virtual void update(); - +protected: + Renderable(); private: pss boundingSphere_; diff --git a/src/rendering/renderablebody.h b/include/openspace/rendering/renderablebody.h similarity index 89% rename from src/rendering/renderablebody.h rename to include/openspace/rendering/renderablebody.h index 110663de16..86562c9a2b 100644 --- a/src/rendering/renderablebody.h +++ b/include/openspace/rendering/renderablebody.h @@ -2,15 +2,15 @@ #define RENDERABLEBODY_H // open space includes -#include "renderable.h" -#include "util/sphere.h" +#include +#include // ghoul includes #include "ghoul/opengl/programobject.h" #include "ghoul/opengl/texture.h" namespace openspace { - +/* class RenderableBody: public Renderable { public: @@ -31,7 +31,7 @@ private: gl4::Sphere *planet_; }; - +*/ } // namespace openspace #endif \ No newline at end of file diff --git a/src/rendering/renderableplanet.h b/include/openspace/rendering/renderableplanet.h similarity index 53% rename from src/rendering/renderableplanet.h rename to include/openspace/rendering/renderableplanet.h index 5bf689788d..e99aa4156d 100644 --- a/src/rendering/renderableplanet.h +++ b/include/openspace/rendering/renderableplanet.h @@ -2,12 +2,12 @@ #define RENDERABLEPLANET_H // open space includes -#include "renderable.h" -#include "util/planet.h" +#include +#include // ghoul includes -#include "ghoul/opengl/programobject.h" -#include "ghoul/opengl/texture.h" +#include +#include namespace openspace { @@ -15,21 +15,29 @@ class RenderablePlanet: public Renderable { public: // constructors & destructor - RenderablePlanet(const pss &radius); + RenderablePlanet(const ghoul::Dictionary& dictionary); ~RenderablePlanet(); + + bool initialize(); + bool deinitialize(); - void setProgramObject(ghoul::opengl::ProgramObject *programObject); + void setProgramObject(ghoul::opengl::ProgramObject *programObject = nullptr); void setTexture(ghoul::opengl::Texture *texture); virtual void render(const Camera *camera, const psc &thisPosition); virtual void update(); private: - ghoul::opengl::ProgramObject *programObject_; + + // shader + ghoul::opengl::ProgramObject *programObject_; + + // texture + std::string _texturePath; ghoul::opengl::Texture *texture_; - // double rad_; - - Planet *planet_; + + // Object + PowerScaledSphere *planet_; }; } // namespace openspace diff --git a/src/rendering/renderengine.h b/include/openspace/rendering/renderengine.h similarity index 96% rename from src/rendering/renderengine.h rename to include/openspace/rendering/renderengine.h index c9e16e5648..285282ce31 100644 --- a/src/rendering/renderengine.h +++ b/include/openspace/rendering/renderengine.h @@ -25,7 +25,7 @@ #ifndef __RENDERENGINE_H__ #define __RENDERENGINE_H__ -#include "scenegraph/scenegraph.h" +#include #include @@ -38,7 +38,7 @@ public: RenderEngine(); ~RenderEngine(); - bool initialize(const std::string& sceneGraph); + bool initialize(); SceneGraph* sceneGraph(); diff --git a/src/rendering/volumeraycaster.h b/include/openspace/rendering/volumeraycaster.h similarity index 100% rename from src/rendering/volumeraycaster.h rename to include/openspace/rendering/volumeraycaster.h diff --git a/include/openspace/scenegraph/constantpositioninformation.h b/include/openspace/scenegraph/constantpositioninformation.h new file mode 100644 index 0000000000..6fbc86ca70 --- /dev/null +++ b/include/openspace/scenegraph/constantpositioninformation.h @@ -0,0 +1,46 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __CONSTANTPOSITIONINFORMATION_H__ +#define __CONSTANTPOSITIONINFORMATION_H__ + +#include "positioninformation.h" + +namespace openspace { + +class ConstantPositionInformation: public PositionInformation { +public: + ConstantPositionInformation(const ghoul::Dictionary& dictionary); + virtual ~ConstantPositionInformation(); + virtual bool initialize(); + virtual const psc& position() const; + virtual void update(); +protected: +private: + psc _position; + +}; + +} // namespace openspace +#endif \ No newline at end of file diff --git a/include/openspace/scenegraph/positioninformation.h b/include/openspace/scenegraph/positioninformation.h new file mode 100644 index 0000000000..dc6ce11ff6 --- /dev/null +++ b/include/openspace/scenegraph/positioninformation.h @@ -0,0 +1,47 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __POSITIONINFORMATION_H__ +#define __POSITIONINFORMATION_H__ + +#include +#include + +namespace openspace { + +class PositionInformation { +public: + PositionInformation(const ghoul::Dictionary& dictionary); + virtual ~PositionInformation(); + virtual bool initialize() = 0; + virtual const psc& position() const = 0; + virtual void update() = 0; +protected: + PositionInformation(); +private: + +}; + +} // namespace openspace +#endif \ No newline at end of file diff --git a/include/openspace/scenegraph/scenegraph.h b/include/openspace/scenegraph/scenegraph.h new file mode 100644 index 0000000000..999372d888 --- /dev/null +++ b/include/openspace/scenegraph/scenegraph.h @@ -0,0 +1,103 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef SCENEGRAPH_H +#define SCENEGRAPH_H + +// open space includes +#include + +// std includes +#include +#include + +// ghoul includes +#include +#include + +namespace openspace { + +class SceneGraph { +public: + + // constructors & destructor + SceneGraph(); + ~SceneGraph(); + + /** + * Initalizes the SceneGraph by loading modules from the ${SCENEPATH} directory + */ + bool initialize(); + + /* + * Clean up everything + */ + bool deinitialize(); + + /* + * Load the scenegraph from the provided folder + */ + bool loadFromModulePath(const std::string& path); + + /* + * Updates all SceneGraphNodes relative positions + */ + void update(); + + /* + * Evaluates if the SceneGraphNodes are visible to the provided camera + */ + void evaluate(Camera *camera); + + /* + * Render visible SceneGraphNodes using the provided camera + */ + void render(Camera *camera); + + /* + * Prints the SceneGraph tree. For debugging purposes + */ + void printChildren() const; + + /* + * Returns the root SceneGraphNode + */ + SceneGraphNode* root() const; + +private: + + void loadModulesFromModulePath(const std::string& modulePath); + + std::string _focus, _position; + + // actual scenegraph + SceneGraphNode *_root; + std::vector _nodes; + std::map _allNodes; + +}; + +} // namespace openspace + +#endif \ No newline at end of file diff --git a/include/openspace/scenegraph/scenegraphnode.h b/include/openspace/scenegraph/scenegraphnode.h new file mode 100644 index 0000000000..a7480ec4e0 --- /dev/null +++ b/include/openspace/scenegraph/scenegraphnode.h @@ -0,0 +1,103 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef SCENEGRAPHNODE_H +#define SCENEGRAPHNODE_H + +// open space includes +#include +#include + +#include + +// std includes +#include +#include +#include + +namespace openspace { + +class SceneGraphNode { +public: + + // constructors & destructor + SceneGraphNode(const ghoul::Dictionary& dictionary); + ~SceneGraphNode(); + + bool initialize(); + bool deinitialize(); + + // essential + void update(); + void evaluate(const Camera *camera, const psc &parentPosition = psc()); + void render(const Camera *camera, const psc &parentPosition = psc()); + + // set & get + void addNode(SceneGraphNode* child); + + void setName(const std::string &name); + void setParent(SceneGraphNode *parent); + const psc& getPosition() const; + psc getWorldPosition() const; + std::string nodeName() const; + + SceneGraphNode* parent() const; + const std::vector& children() const; + + // bounding sphere + pss calculateBoundingSphere(); + + SceneGraphNode* get(const std::string& name); + + void print() const; + + // renderable + void setRenderable(Renderable *renderable); + const Renderable * getRenderable() const; + +private: + + // essential + std::vector _children; + SceneGraphNode* _parent; + std::string _nodeName; + PositionInformation* _position; + + // renderable + Renderable *_renderable; + bool _renderableVisible; + + // bounding sphere + bool _boundingSphereVisible; + pss _boundingSphere; + + // private helper methods + bool sphereInsideFrustum(const psc s_pos, const pss & s_rad, const Camera *camera); +}; + +} // namespace openspace + +#include + +#endif \ No newline at end of file diff --git a/include/openspace/scenegraph/scenegraphnode.inl b/include/openspace/scenegraph/scenegraphnode.inl new file mode 100644 index 0000000000..4708f9fade --- /dev/null +++ b/include/openspace/scenegraph/scenegraphnode.inl @@ -0,0 +1,60 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef SCENEGRAPHNODE_INL +#define SCENEGRAPHNODE_INL + +#include + +namespace openspace { + +template +bool safeCreationWithDictionary( T** object, + const std::string& key, + ghoul::Dictionary* dictionary, + const std::string& path = "") +{ + if(dictionary->hasKey(key)) { + ghoul::Dictionary tmpDictionary; + if(dictionary->getValue(key, tmpDictionary)) { + if ( ! tmpDictionary.hasKey("Path") && path != "") { + tmpDictionary.setValue("Path", path); + } + std::string renderableType; + if(tmpDictionary.getValue("Type", renderableType)) { + ghoul::TemplateFactory* factory = FactoryManager::ref().factoryByType(); + T* tmp = factory->create(renderableType, tmpDictionary); + if(tmp != nullptr) { + *object = tmp; + return true; + } + } + } + } + return false; +} + +} // namespace openspace + +#endif \ No newline at end of file diff --git a/include/openspace/scenegraph/spicepositioninformation.h b/include/openspace/scenegraph/spicepositioninformation.h new file mode 100644 index 0000000000..04108ba2c7 --- /dev/null +++ b/include/openspace/scenegraph/spicepositioninformation.h @@ -0,0 +1,51 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __SPICEPOSITIONINFORMATION_H__ +#define __SPICEPOSITIONINFORMATION_H__ + +#include + +#include + +namespace openspace { + +class SpicePositionInformation: public PositionInformation { +public: + SpicePositionInformation(const ghoul::Dictionary& dictionary); + virtual ~SpicePositionInformation(); + virtual bool initialize(); + virtual const psc& position() const; + virtual void update(); +protected: +private: + + std::string _targetName, _originName; + int _target, _origin; + psc _position; + +}; + +} // namespace openspace +#endif \ No newline at end of file diff --git a/include/openspace/tests/test_common.inl b/include/openspace/tests/test_common.inl new file mode 100644 index 0000000000..1e0abd4b26 --- /dev/null +++ b/include/openspace/tests/test_common.inl @@ -0,0 +1,111 @@ +/***************************************************************************************** + * * + * GHOUL * + * General Helpful Open Utility Library * + * * + * Copyright (c) 2012-2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifdef GHL_TIMING_TESTS + +#ifdef WIN32 +#define START_TIMER(__name__, __stream__, __num__) \ + __stream__ << #__name__; \ + double __name__##Total = 0.0; \ + unsigned int __name__##Num = 0; \ + for (__name__##Num = 0; __name__##Num < __num__; ++__name__##Num) { \ + reset(); \ + LARGE_INTEGER __name__##Start; \ + LARGE_INTEGER __name__##End; \ + QueryPerformanceCounter(&__name__##Start) + +#define START_TIMER_NO_RESET(__name__, __stream__, __num__) \ + __stream__ << #__name__; \ + double __name__##Total = 0.0; \ + unsigned int __name__##Num = 0; \ + for (__name__##Num = 0; __name__##Num < __num__; ++__name__##Num) { \ + LARGE_INTEGER __name__##Start; \ + LARGE_INTEGER __name__##End; \ + QueryPerformanceCounter(&__name__##Start) + +#define START_TIMER_PREPARE(__name__, __stream__, __num__, __prepare__) \ + __stream__ << #__name__; \ + double __name__##Total = 0.0; \ + unsigned int __name__##Num = 0; \ + for (__name__##Num = 0; __name__##Num < __num__; ++__name__##Num) { \ + reset(); \ + __prepare__; \ + LARGE_INTEGER __name__##Start; \ + LARGE_INTEGER __name__##End; \ + QueryPerformanceCounter(&__name__##Start) + +#define FINISH_TIMER(__name__, __stream__) \ + QueryPerformanceCounter(&__name__##End); \ + LARGE_INTEGER freq; \ + QueryPerformanceFrequency(&freq); \ + const double freqD = double(freq.QuadPart) / 1000000.0; \ + const double res = ((__name__##End.QuadPart - __name__##Start.QuadPart) / freqD);\ + __name__##Total += res; \ + } \ + __stream__ << '\t' << __name__##Total / __name__##Num << "us\n"; + +#else + +#include + +#define START_TIMER(__name__, __stream__, __num__) \ + __stream__ << #__name__; \ + std::chrono::nanoseconds __name__##Total = std::chrono::nanoseconds(0); \ + unsigned int __name__##Num = 0; \ + for (__name__##Num = 0; __name__##Num < __num__; ++__name__##Num) { \ + reset(); \ + std::chrono::high_resolution_clock::time_point __name__##End; \ + std::chrono::high_resolution_clock::time_point __name__##Start = \ + std::chrono::high_resolution_clock::now() + +#define START_TIMER_NO_RESET(__name__, __stream__, __num__) \ + __stream__ << #__name__; \ + std::chrono::nanoseconds __name__##Total = std::chrono::nanoseconds(0); \ + unsigned int __name__##Num = 0; \ + for (__name__##Num = 0; __name__##Num < __num__; ++__name__##Num) { \ + std::chrono::high_resolution_clock::time_point __name__##End; \ + std::chrono::high_resolution_clock::time_point __name__##Start = \ + std::chrono::high_resolution_clock::now() + +#define START_TIMER_PREPARE(__name__, __stream__, __num__, __prepare__) \ + __stream__ << #__name__; \ + std::chrono::nanoseconds __name__##Total = std::chrono::nanoseconds(0); \ + unsigned int __name__##Num = 0; \ + for (__name__##Num = 0; __name__##Num < __num__; ++__name__##Num) { \ + reset(); \ + __prepare__; \ + std::chrono::high_resolution_clock::time_point __name__##End; \ + std::chrono::high_resolution_clock::time_point __name__##Start = \ + std::chrono::high_resolution_clock::now() + +#define FINISH_TIMER(__name__, __stream__) \ + __name__##End = std::chrono::high_resolution_clock::now(); \ + const std::chrono::nanoseconds d = __name__##End - __name__##Start; \ + __name__##Total += d; \ + } \ + __stream__ << #__name__ << '\t' << __name__##Total.count() / 1000.0 << "us" << '\n'; +#endif + +#endif // GHL_TIMING_TESTS diff --git a/include/openspace/tests/test_powerscalecoordinates.inl b/include/openspace/tests/test_powerscalecoordinates.inl new file mode 100644 index 0000000000..454e61b7df --- /dev/null +++ b/include/openspace/tests/test_powerscalecoordinates.inl @@ -0,0 +1,83 @@ +/***************************************************************************************** + * * + * GHOUL * + * General Helpful Open Utility Library * + * * + * Copyright (c) 2012-2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include "gtest/gtest.h" + +#include +#include + +class PowerscaleCoordinatesTest : public testing::Test { +protected: + PowerscaleCoordinatesTest() { + } + + ~PowerscaleCoordinatesTest() { + } + + void reset() { + } + + openspace::SceneGraph* scenegraph; +}; + + +TEST_F(PowerscaleCoordinatesTest, psc) { + + openspace::psc reference(2.0, 1.0, 1.1, 1.0); + + openspace::psc first(1.0,0.0,1.0,0.0); + openspace::psc second(1.9,1.0,1.0,1.0); + + EXPECT_EQ(reference, first + second); + EXPECT_TRUE(reference == (first + second)); + + openspace::psc third = first; + first[0] = 0.0; + + EXPECT_TRUE(third != first); + + +} + +TEST_F(PowerscaleCoordinatesTest, pss) { + + openspace::pss first(1.0,1.0); + openspace::pss second(1.0,-1.0); + EXPECT_EQ(openspace::pss(1.01,1.0), first + second); + EXPECT_EQ(openspace::pss(1.01,1.0), second + first); + /* + EXPECT_TRUE(first < (first + second)); + bool retu =(second < (first + second)); + + std::cout << "retu: " << retu << std::endl; + EXPECT_TRUE(retu); + + EXPECT_FALSE(first > (first + second)); + EXPECT_FALSE(second > (first + second)); + + */ +} + + diff --git a/include/openspace/tests/test_scenegraph.inl b/include/openspace/tests/test_scenegraph.inl new file mode 100644 index 0000000000..e08a1de09b --- /dev/null +++ b/include/openspace/tests/test_scenegraph.inl @@ -0,0 +1,119 @@ +/***************************************************************************************** + * * + * GHOUL * + * General Helpful Open Utility Library * + * * + * Copyright (c) 2012-2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include "gtest/gtest.h" + +#include +#include +#include +#include +#include + +class SceneGraphTest : public testing::Test { +protected: + SceneGraphTest() { + _scenegraph = new openspace::SceneGraph; + } + + ~SceneGraphTest() { + _scenegraph = new openspace::SceneGraph; + } + + void reset() { + delete _scenegraph; + _scenegraph = new openspace::SceneGraph; + } + + openspace::SceneGraph* _scenegraph; +}; + +TEST_F(SceneGraphTest, SceneGraphNode) { + + openspace::SceneGraphNode* node = new openspace::SceneGraphNode(ghoul::Dictionary()); + + // Should not have a renderable and position should be 0,0,0,0 (undefined). + EXPECT_EQ(nullptr, node->getRenderable()); + EXPECT_EQ(openspace::psc(), node->getPosition()); + + delete node; + ghoul::Dictionary nodeDictionary; + + ghoul::Dictionary positionDictionary; + ghoul::Dictionary positionPositionArrayDictionary; + + ghoul::Dictionary renderableDictionary; + + renderableDictionary.setValue("Type", std::string("RenderablePlanet")); + + positionPositionArrayDictionary.setValue("1", 1.0); + positionPositionArrayDictionary.setValue("2", 1.0); + positionPositionArrayDictionary.setValue("3", 1.0); + positionPositionArrayDictionary.setValue("4", 1.0); + + positionDictionary.setValue("Type", std::string("Static")); + positionDictionary.setValue("Position", positionPositionArrayDictionary); + + nodeDictionary.setValue("Position", positionDictionary); + nodeDictionary.setValue("Renderable", renderableDictionary); + + node = new openspace::SceneGraphNode(nodeDictionary); + + // This node should have a renderable (probably no good values but an existing one) + EXPECT_TRUE(node->getRenderable()); + + // position should be initialized + EXPECT_EQ(openspace::psc(1.0,1.0,1.0,1.0), node->getPosition()); + + delete node; +} + +TEST_F(SceneGraphTest, Loading) { + + + // Should not successfully load a non existing scenegraph + EXPECT_FALSE(_scenegraph->loadFromModulePath(absPath("${TESTDIR}/ScenegraphTestNonExisting"))); + + // Existing scenegraph should load + EXPECT_TRUE(_scenegraph->loadFromModulePath(absPath("${TESTDIR}/ScenegraphTest"))); + + // This loading should fail regardless of existing or not since the + // scenegraph is already loaded + EXPECT_FALSE(_scenegraph->loadFromModulePath(absPath("${TESTDIR}/ScenegraphTest"))); +} + +TEST_F(SceneGraphTest, Reinitializing) { + + // Existing scenegraph should load + EXPECT_TRUE(_scenegraph->loadFromModulePath(absPath("${TESTDIR}/ScenegraphTest"))); + + _scenegraph->deinitialize(); + + // Existing scenegraph should load + EXPECT_TRUE(_scenegraph->loadFromModulePath(absPath("${TESTDIR}/ScenegraphTest"))); +} + + + + diff --git a/src/util/camera.h b/include/openspace/util/camera.h similarity index 97% rename from src/util/camera.h rename to include/openspace/util/camera.h index 1e94cce422..c9c945d505 100644 --- a/src/util/camera.h +++ b/include/openspace/util/camera.h @@ -2,7 +2,7 @@ #define CAMERA_H // open space includes -#include "util/psc.h" +#include // glm includes #include diff --git a/include/openspace/util/factorymanager.h b/include/openspace/util/factorymanager.h new file mode 100644 index 0000000000..8cbc8dcfc5 --- /dev/null +++ b/include/openspace/util/factorymanager.h @@ -0,0 +1,84 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __FACTORYMANAGER_H__ +#define __FACTORYMANAGER_H__ + +// ghoul includes +#include +#include + +#include +#include + + +namespace openspace { + +class FactoryManager { +public: + + /** + * Static initializer that initializes the static member. This needs to be done before + * the FactoryManager can be used. If the manager has been already initialized, an + * assertion will be triggered. + */ + static void initialize(); + static void deinitialize(); + + /** + * This method returns a reference to the initialized FactoryManager. If the manager + * has not been initialized, an assertion will be triggered. + * \return An initialized reference to the singleton manager + */ + static FactoryManager& ref(); + + template + ghoul::TemplateFactory* factoryByType(); + +private: + FactoryManager(); + + /// Not implemented on purpose, using this should result in an error + FactoryManager(const FactoryManager& c); + + /// Not implemented on purpose, using this should result in an error + ~FactoryManager(); + + static FactoryManager* _manager; /// _renderableFactory; + ghoul::TemplateFactory _positionInformationFactory; + +}; + +// Forward declare template specializations +template<> +ghoul::TemplateFactory* FactoryManager::factoryByType(); +template<> +ghoul::TemplateFactory* FactoryManager::factoryByType(); + + +} // namespace openspace + +#endif \ No newline at end of file diff --git a/src/util/geometry.h b/include/openspace/util/geometry.h similarity index 97% rename from src/util/geometry.h rename to include/openspace/util/geometry.h index c76126cb98..fa29eed4d9 100644 --- a/src/util/geometry.h +++ b/include/openspace/util/geometry.h @@ -11,7 +11,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI #define GEOMETRY_H // open space includes -#include "util/vbo.h" +#include namespace gl4 { diff --git a/src/util/planet.h b/include/openspace/util/planet.h similarity index 95% rename from src/util/planet.h rename to include/openspace/util/planet.h index abcd16a2e1..b59d476419 100644 --- a/src/util/planet.h +++ b/include/openspace/util/planet.h @@ -11,8 +11,8 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI #define PLANET_H // open space includes -#include "util/pss.h" -#include "util/vbo_template.h" +#include +#include // std includes #include diff --git a/include/openspace/util/powerscaledsphere.h b/include/openspace/util/powerscaledsphere.h new file mode 100644 index 0000000000..da4e2246ce --- /dev/null +++ b/include/openspace/util/powerscaledsphere.h @@ -0,0 +1,58 @@ +/** +Copyright (C) 2012-2014 Jonas Strandstedt + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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 __POWERSCALEDSPHERE_H__ +#define __POWERSCALEDSPHERE_H__ + +// open space includes +#include +#include +#include + + +namespace openspace { + + +#define BUFFER_OFFSET(i) ((char *)NULL + (i)) + + typedef struct + { + GLfloat location[4]; + GLfloat tex[2]; + GLfloat normal[3]; + GLubyte padding[28]; // Pads the struct out to 64 bytes for performance increase + } Vertex; + + + class PowerScaledSphere + { + public: + //initializers + PowerScaledSphere(const pss radius, int segments = 8); + ~PowerScaledSphere(); + + bool initialize(); + + void render(); + + private: + GLuint _vaoID; + GLuint _vBufferID; + GLuint _iBufferID; + + GLenum _mode; + unsigned int _isize; + unsigned int _vsize; + Vertex *_varray; + int *_iarray; + + }; +} + +#endif diff --git a/src/util/psc.h b/include/openspace/util/psc.h similarity index 92% rename from src/util/psc.h rename to include/openspace/util/psc.h index 03e05bb64b..37abcf2ba8 100644 --- a/src/util/psc.h +++ b/include/openspace/util/psc.h @@ -6,6 +6,7 @@ #include #include #include +#include namespace openspace { @@ -64,7 +65,8 @@ public: const psc operator*(const pss &rhs) const; // comparasion - bool operator==(const psc &other) const; + bool operator==(const psc &other) const; + bool operator!=(const psc &other) const; bool operator<(const psc &other) const; bool operator>(const psc &other) const; bool operator<=(const psc &other) const; @@ -75,6 +77,8 @@ public: psc & operator=(const glm::vec3 &rhs); psc & operator=(const glm::dvec4 &rhs); psc & operator=(const glm::dvec3 &rhs); + + friend std::ostream& operator<<(::std::ostream& os, const psc& rhs); // allow the power scaled scalars to acces private members friend class pss; diff --git a/src/util/pss.h b/include/openspace/util/pss.h similarity index 95% rename from src/util/pss.h rename to include/openspace/util/pss.h index b47053fd3e..2fd263d7e1 100644 --- a/src/util/pss.h +++ b/include/openspace/util/pss.h @@ -6,6 +6,8 @@ #include #include +#include + namespace openspace { @@ -68,6 +70,8 @@ public: pss & operator=(const float &rhs); pss & operator=(const glm::dvec2 &rhs); pss & operator=(const double &rhs); + + friend std::ostream& operator<<(::std::ostream& os, const pss& rhs); // allow the power scaled coordinates to acces private members friend class psc; diff --git a/src/util/sphere.h b/include/openspace/util/sphere.h similarity index 97% rename from src/util/sphere.h rename to include/openspace/util/sphere.h index 95734e2c73..f231052574 100644 --- a/src/util/sphere.h +++ b/include/openspace/util/sphere.h @@ -11,7 +11,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI #define SPHERE_H // open space includes -#include "util/geometry.h" +#include namespace gl4 { diff --git a/src/util/spice.h b/include/openspace/util/spice.h similarity index 100% rename from src/util/spice.h rename to include/openspace/util/spice.h diff --git a/src/util/time.h b/include/openspace/util/time.h similarity index 100% rename from src/util/time.h rename to include/openspace/util/time.h diff --git a/src/util/vbo.h b/include/openspace/util/vbo.h similarity index 100% rename from src/util/vbo.h rename to include/openspace/util/vbo.h diff --git a/src/util/vbo_template.h b/include/openspace/util/vbo_template.h similarity index 100% rename from src/util/vbo_template.h rename to include/openspace/util/vbo_template.h diff --git a/kernels/RaycasterTSP.cl b/kernels/RaycasterTSP.cl index 1c76f579e6..de239b4c07 100644 --- a/kernels/RaycasterTSP.cl +++ b/kernels/RaycasterTSP.cl @@ -12,12 +12,76 @@ struct KernelConstants { int paddedBrickDim_; }; - +float3 CartesianToSpherical(float3 _cartesian); +float Lerp(float _v0, float _v1, float _d); +int LeftBST(int _bstNodeIndex, int _numValuesPerNode, int _numOTNodes, + bool _bstRoot, __global __read_only int *_tsp); +int RightBST(int _bstNodeIndex, int _numValuesPerNode, int _numOTNodes, + bool _bstRoot, __global __read_only int *_tsp); +int ChildNodeIndex(int _bstNodeIndex, + int *_timespanStart, + int *_timespanEnd, + int _timestep, + int _numValuesPerNode, + int _numOTNodes, + bool _bstRoot, + __global __read_only int *_tsp); +int BrickIndex(int _bstNodeIndex, int _numValuesPerNode, + __global __read_only int *_tsp); +bool IsBSTLeaf(int _bstNodeIndex, int _numValuesPerNode, + bool _bstRoot, __global __read_only int *_tsp); +bool IsOctreeLeaf(int _otNodeIndex, int _numValuesPerNode, + __global __read_only int *_tsp); +int OTChildIndex(int _otNodeIndex, int _numValuesPerNode, + int _child, + __global __read_only int *_tsp) ; +float TemporalError(int _bstNodeIndex, int _numValuesPerNode, + __global __read_only int *_tsp) ; +float SpatialError(int _bstNodeIndex, int _numValuesPerNode, + __global __read_only int *_tsp); +int3 BoxCoords(float3 _globalCoords, int _boxesPerAxis) ; +int3 AtlasBoxCoords(int _brickIndex, + __global __read_only int *_brickList); +float3 AtlasCoords(float3 _globalCoords, int _brickIndex, int _boxesPerAxis, + int _paddedBrickDim, int _level, + __global __read_only int *_brickList) ; +void SampleAtlas(float4 *_color, float3 _coords, int _brickIndex, + int _boxesPerAxis, int _paddedBrickDim, int _level, + const sampler_t _atlasSampler, + __read_only image3d_t _textureAtlas, + __read_only image2d_t _transferFunction, + const sampler_t _tfSampler, + __global __read_only int *_brickList); +bool TraverseBST(int _otNodeIndex, int *_brickIndex, + __constant __read_only struct KernelConstants *_constants, + __global __read_only int *_tsp, const int _timestep); +int EnclosingChild(float3 _P, float _boxMid, float3 _offset) ; +void UpdateOffset(float3 *_offset, float _boxDim, int _child) ; +float4 TraverseOctree(float3 _rayO, float3 _rayD, float _maxDist, + __read_only image3d_t _textureAtlas, + __constant struct KernelConstants *_constants, + __read_only image2d_t _transferFunction, + __global __read_only int *_tsp, + __global __read_only int *_brickList, + const int _timestep); +__kernel void RaycasterTSP(__read_only image2d_t _cubeFront, + __read_only image2d_t _cubeBack, + __write_only image2d_t _output, + __read_only image3d_t _textureAtlas, + __constant struct KernelConstants *_constants, + __read_only image2d_t _transferFunction, + //__global __read_only float *_transferFunction, + __global __read_only int *_tsp, + __global __read_only int *_brickList, + const int _timestep); + + + // Turn normalized [0..1] cartesian coordinates // to normalized spherical [0..1] coordinates float3 CartesianToSpherical(float3 _cartesian) { // Put cartesian in [-1..1] range first - _cartesian = (float3)(-1.0) + 2.0* _cartesian; + _cartesian = (float3)(-1.0) + 2.0f* _cartesian; float r = length(_cartesian); float theta, phi; if (r == 0.0) { @@ -26,7 +90,7 @@ float3 CartesianToSpherical(float3 _cartesian) { theta = acospi(_cartesian.z/r); phi = (M_PI + atan2(_cartesian.y, _cartesian.x)) / (2.0*M_PI); } - r = r / native_sqrt(3.0); + r = r / native_sqrt(3.0f); // Sampler ignores w component return (float3)(r, theta, phi); } @@ -218,8 +282,8 @@ float3 AtlasCoords(float3 _globalCoords, int _brickIndex, int _boxesPerAxis, void SampleAtlas(float4 *_color, float3 _coords, int _brickIndex, int _boxesPerAxis, int _paddedBrickDim, int _level, const sampler_t _atlasSampler, - __global __read_only image3d_t _textureAtlas, - __global __read_only image2d_t _transferFunction, + __read_only image3d_t _textureAtlas, + __read_only image2d_t _transferFunction, const sampler_t _tfSampler, __global __read_only int *_brickList) { @@ -235,7 +299,7 @@ void SampleAtlas(float4 *_color, float3 _coords, int _brickIndex, float sample = read_imagef(_textureAtlas, _atlasSampler, a4).x; // Composition float4 tf = read_imagef(_transferFunction, _tfSampler, (float2)(sample, 0.0)); - *_color += (1.0 - _color->w)*tf; + *_color += (1.0f - _color->w)*tf; } @@ -358,9 +422,9 @@ void UpdateOffset(float3 *_offset, float _boxDim, int _child) { } float4 TraverseOctree(float3 _rayO, float3 _rayD, float _maxDist, - __global __read_only image3d_t _textureAtlas, + __read_only image3d_t _textureAtlas, __constant struct KernelConstants *_constants, - __global __read_only image2d_t _transferFunction, + __read_only image2d_t _transferFunction, __global __read_only int *_tsp, __global __read_only int *_brickList, const int _timestep) { @@ -438,7 +502,7 @@ float4 TraverseOctree(float3 _rayO, float3 _rayD, float _maxDist, // Keep traversing the octree // Next box dimension - boxDim /= 2.0; + boxDim /= 2.0f; // Current mid point float boxMid = boxDim; @@ -469,12 +533,12 @@ float4 TraverseOctree(float3 _rayO, float3 _rayD, float _maxDist, } -__kernel void RaycasterTSP(__global __read_only image2d_t _cubeFront, - __global __read_only image2d_t _cubeBack, - __global __write_only image2d_t _output, - __global __read_only image3d_t _textureAtlas, +__kernel void RaycasterTSP(__read_only image2d_t _cubeFront, + __read_only image2d_t _cubeBack, + __write_only image2d_t _output, + __read_only image3d_t _textureAtlas, __constant struct KernelConstants *_constants, - __global __read_only image2d_t _transferFunction, + __read_only image2d_t _transferFunction, //__global __read_only float *_transferFunction, __global __read_only int *_tsp, __global __read_only int *_brickList, diff --git a/kernels/TSPTraversal.cl b/kernels/TSPTraversal.cl index 252d8ffef8..0ea26357b4 100644 --- a/kernels/TSPTraversal.cl +++ b/kernels/TSPTraversal.cl @@ -9,11 +9,66 @@ struct TraversalConstants { float spatialTolerance_; }; +float3 CartesianToSpherical(float3 _cartesian); +int OctreeRootNodeIndex(); +int LeftBST(int _bstNodeIndex, int _numValuesPerNode, int _numOTNodes, + bool _bstRoot, __global __read_only int *_tsp); +int RightBST(int _bstNodeIndex, int _numValuesPerNode, int _numOTNodes, + bool _bstRoot, __global __read_only int *_tsp); +int ChildNodeIndex(int _bstNodeIndex, + int *_timespanStart, + int *_timespanEnd, + int _timestep, + int _numValuesPerNode, + int _numOTNodes, + bool _bstRoot, + __global __read_only int *_tsp); +int BrickIndex(int _bstNodeIndex, int _numValuesPerNode, + __global __read_only int *_tsp) ; +bool IsBSTLeaf(int _bstNodeIndex, int _numValuesPerNode, + bool _bstRoot, __global __read_only int *_tsp) ; +bool IsOctreeLeaf(int _otNodeIndex, int _numValuesPerNode, + __global __read_only int *_tsp) ; +int OTChildIndex(int _otNodeIndex, int _numValuesPerNode, + int _child, + __global __read_only int *_tsp); +void AddToList(int _brickIndex, + __global volatile int *_reqList); +float TemporalError(int _bstNodeIndex, int _numValuesPerNode, + __global __read_only int *_tsp) ; +float SpatialError(int _bstNodeIndex, int _numValuesPerNode, + __global __read_only int *_tsp); +bool TraverseBST(int _otNodeIndex, + int *_brickIndex, + int _timestep, + __constant struct TraversalConstants *_constants, + __global volatile int *_reqList, + __global __read_only int *_tsp); +int EnclosingChild(float3 _P, float _boxMid, float3 _offset); +void UpdateOffset(float3 *_offset, float _boxDim, int _child) ; +void TraverseOctree(float3 _rayO, + float3 _rayD, + float _maxDist, + __constant struct TraversalConstants *_constants, + __global volatile int *_reqList, + __global __read_only int *_tsp, + const int _timestep); +__kernel void TSPTraversal(__read_only image2d_t _cubeFront, + __read_only image2d_t _cubeBack, + __constant struct TraversalConstants *_constants, + __global __read_only int *_tsp, + __global int *_reqList, + const int _timestep) ; + + + + + // Turn normalized [0..1] cartesian coordinates // to normalized spherical [0..1] coordinates float3 CartesianToSpherical(float3 _cartesian) { // Put cartesian in [-1..1] range first - _cartesian = (float3)(-1.0) + 2.0* _cartesian; + _cartesian = (float3)(-1.0) + 2.0f* _cartesian; float r = length(_cartesian); float theta, phi; if (r == 0.0) { @@ -22,7 +77,7 @@ float3 CartesianToSpherical(float3 _cartesian) { theta = acospi(_cartesian.z/r); phi = (M_PI + atan2(_cartesian.y, _cartesian.x)) / (2.0*M_PI); } - r = r / native_sqrt(3.0); + r = r / native_sqrt(3.0f); // Sampler ignores w component return (float3)(r, theta, phi); } @@ -105,7 +160,7 @@ bool IsOctreeLeaf(int _otNodeIndex, int _numValuesPerNode, int OTChildIndex(int _otNodeIndex, int _numValuesPerNode, int _child, __global __read_only int *_tsp) { - int firstChild = _tsp[_otNodeIndex*_numValuesPerNode + 1]; + int firstChild = _tsp[_otNodeIndex*_numValuesPerNode+1]; return firstChild + _child; } @@ -275,21 +330,26 @@ void TraverseOctree(float3 _rayO, float stepsize = _constants->stepsize_; float3 P = _rayO; // Keep traversing until the sample point goes outside the unit cube - float traversed = 0.0; + float traversed = 0.0f; + + int max_iterations = 50; + int iterations = 0; + bool ok = stepsize > 0.0f && stepsize < fabs(_maxDist); + //while (traversed < _maxDist && iterations < max_iterations) { while (traversed < _maxDist) { // Reset traversal variables - float3 offset = (float3)(0.0); - float boxDim = 1.0; + float3 offset = (float3)(0.0f); + float boxDim = 1.0f; int child; // Init the octree node index to the root int otNodeIndex = OctreeRootNodeIndex(); - + // Start traversing octree // Rely on finding a leaf for loop termination + while (true) { - // See if the BST tree is good enough int brickIndex = 0; bool bstSuccess = TraverseBST(otNodeIndex, @@ -307,7 +367,7 @@ void TraverseOctree(float3 _rayO, AddToList(brickIndex, _reqList); // We are now done with this node, so go to next break; - + // If the BST lookup failed but the octree node is a leaf, // add the brick anyway (it is the BST leaf) } else if (IsOctreeLeaf(otNodeIndex, @@ -319,9 +379,9 @@ void TraverseOctree(float3 _rayO, // If the BST lookup failed and we can traverse the octree, // visit the child that encloses the point } else { - + // Next box dimension - boxDim = boxDim/2.0; + boxDim = boxDim/2.0f; // Current mid point float boxMid = boxDim; @@ -338,23 +398,23 @@ void TraverseOctree(float3 _rayO, UpdateOffset(&offset, boxDim, child); // Update node index to new node - int oldIndex = otNodeIndex; + //int oldIndex = otNodeIndex; otNodeIndex = OTChildIndex(otNodeIndex, _constants->numValuesPerNode_, child, _tsp); - - } - + } } // while traversing // Update - traversed += stepsize; - P += stepsize * _rayD; + traversed = traversed + stepsize; + P = P + stepsize * _rayD; } // while (traversed < maxDist) + + } -__kernel void TSPTraversal(__global __read_only image2d_t _cubeFront, - __global __read_only image2d_t _cubeBack, +__kernel void TSPTraversal(__read_only image2d_t _cubeFront, + __read_only image2d_t _cubeBack, __constant struct TraversalConstants *_constants, __global __read_only int *_tsp, __global int *_reqList, @@ -368,6 +428,7 @@ __kernel void TSPTraversal(__global __read_only image2d_t _cubeFront, // Read from color cube textures float4 cubeFrontColor = read_imagef(_cubeFront, sampler, intCoords); + if (length(cubeFrontColor.xyz) == 0.0) return; float4 cubeBackColor = read_imagef(_cubeBack, sampler, intCoords); diff --git a/kernels/test.cl b/kernels/test.cl new file mode 100644 index 0000000000..98ec1f6e0b --- /dev/null +++ b/kernels/test.cl @@ -0,0 +1,10 @@ + +#ifndef OFFSET +#define OFFSET 0 +#endif + +__kernel void hello(__global int * out) +{ +size_t tid = get_global_id(0); +out[tid] = tid + OFFSET; +} diff --git a/modules/common/common.xml b/modules/common/common.xml deleted file mode 100644 index 4be50769af..0000000000 --- a/modules/common/common.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/modules/common/shaders/powerscale_fs.glsl b/modules/common/shaders/powerscale_fs.glsl deleted file mode 100644 index e5f4e43deb..0000000000 --- a/modules/common/shaders/powerscale_fs.glsl +++ /dev/null @@ -1,107 +0,0 @@ -/** -Copyright (C) 2012-2014 Jonas Strandstedt - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#version 150 - -uniform mat4 ViewProjection; -uniform mat4 ModelTransform; -uniform vec4 campos; -uniform vec4 objpos; -uniform float time; -uniform sampler2D texture1; -uniform sampler2D texture2; -uniform sampler2D texture3; -uniform float TessLevel; -uniform bool Wireframe; -uniform bool Lightsource; -uniform bool UseTexture; - -in vec2 vs_st; -in vec3 vs_stp; -in vec4 vs_normal; -in vec4 vs_color; -in vec4 vs_position; - -out vec4 diffuse; - -const float k = 10.0; - -vec4 psc_normlization(vec4 invec) { - - float xymax = max(invec.x,invec.y); - - if(invec.z > 0.0f || invec.z < 0.0f) { - return invec / abs(invec.z); - } else if (xymax != 0.0f) { - return invec / xymax; - } else { - return invec / -.0; - } -} - -void main() -{ - - // Observable universe is 10^27m, setting the far value to extremely high, aka 30!! ERMAHGERD! - float s_far = 27.0; //= gl_DepthRange.far; // 40 - float s_farcutoff = 12.0; - float s_nearcutoff = 7.0; - float s_near = 0.0f;// gl_DepthRange.near; // 0.1 - float depth; - - // the value can be normalized to 1 - vec4 p = vs_position; - if(vs_position.w <= 0.5) { - //depth = abs(vs_position.z * pow(10, vs_position.w)) / pow(k,s_far); - depth = (vs_position.w+log(abs(vs_position.z)))/pow(k, vs_position.w); - } else if(vs_position.w < 3.0) { - depth = vs_position.w+log(abs(vs_position.z))/pow(k, vs_position.w); - } else { - depth = vs_position.w+log(abs(vs_position.z)); - } - - // DEBUG - float depth_orig = depth; - float x = 0.0f; - float cutoffs = 0.0; - float orig_z = vs_position.z; - - // calculate a normalized depth [0.0 1.0] - if((depth > s_near && depth <= s_nearcutoff) || (depth > s_farcutoff && depth < s_far)) { - - // completely linear interpolation [s_near .. depth .. s_far] - depth = (depth - s_near) / (s_far - s_near); - - } else if(depth > s_nearcutoff && depth < s_farcutoff) { - - // DEBUG - cutoffs = 1.0; - - // interpolate [10^s_nearcutoff .. 10^depth .. 10^s_farcutoff] - // calculate between 0..1 where the depth is - x = (pow(10,depth) - pow(10, s_nearcutoff)) / (pow(10,s_farcutoff) - pow(10, s_nearcutoff)); - - // remap the depth to the 0..1 depth buffer - depth = s_nearcutoff + x * (s_farcutoff - s_nearcutoff); - depth = (depth - s_near) / (s_far - s_near); - - } else { - // where am I? - // do I need to be discarded? - //discard; - } - - - // set the depth - gl_FragDepth = depth; - - // color - diffuse = texture2D(texture1, vs_st); - //diffuse = vec4(1.0,0.0,0.0,1.0); -} \ No newline at end of file diff --git a/modules/common/shaders/powerscale_vs.glsl b/modules/common/shaders/powerscale_vs.glsl deleted file mode 100644 index 4bf86969b3..0000000000 --- a/modules/common/shaders/powerscale_vs.glsl +++ /dev/null @@ -1,100 +0,0 @@ -/** -Copyright (C) 2012-2014 Jonas Strandstedt - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#version 150 - -uniform mat4 ViewProjection; -uniform mat4 ModelTransform; -uniform vec4 campos; -uniform mat4 camrot; -uniform vec2 scaling; -uniform vec4 objpos; -uniform float time; -uniform sampler2D texture1; -uniform sampler2D texture2; -uniform sampler2D texture3; -uniform float TessLevel; -uniform bool Wireframe; -uniform bool Lightsource; -uniform bool UseTexture; - -in vec3 in_position; -in vec2 in_st; -in vec3 in_normal; -in vec4 in_color; -in vec3 in_attribute3f; -in float in_attribute1f; - -out vec2 vs_st; -out vec3 vs_stp; -out vec4 vs_normal; -out vec4 vs_color; -out vec4 vs_position; - -const float k = 10.0; -const float dgr_to_rad = 0.0174532925; - -vec4 psc_addition(vec4 v1, vec4 v2) { - float ds = v2.w - v1.w; - if(ds >= 0) { - float p = pow(k,-ds); - return vec4(v1.x*p + v2.x, v1.y*p + v2.y, v1.z*p + v2.z, v2.w); - } else { - float p = pow(k,ds); - return vec4(v1.x + v2.x*p, v1.y + v2.y*p, v1.z + v2.z*p, v1.w); - } -} - -vec4 psc_to_meter(vec4 v1, vec2 v2) { - return vec4(v1.xyz * v2.x * pow(k,v2.y + v1.w), 1.0); -} - -vec4 psc_scaling(vec4 v1, vec2 v2) { - float ds = v2.y - v1.w; - if(ds >= 0) { - return vec4(v1.xyz * v2.x * pow(k,v1.w), v2.y); - } else { - return vec4(v1.xyz * v2.x * pow(k,v2.y), v1.w); - } -} - -void main() -{ - // set variables - vs_st = in_st; - vs_stp = in_position; - vs_normal = normalize(ModelTransform * vec4(in_normal,1)); - vs_color = in_color; - - // fetch model and view translation - vec4 vertex_translate = ModelTransform[3]; - - // rotate and scale vertex with model transform and add the translation - vec3 local_vertex_pos = mat3(ModelTransform) * in_position + vertex_translate.xyz; - - // PSC addition; local vertex position and the object power scaled world position - vs_position = psc_addition(vec4(local_vertex_pos,0),objpos); - - // PSC addition; rotated and viewscaled vertex and the cmaeras negative position - vs_position = psc_addition(vs_position,vec4(-campos.xyz,campos.w)); - - // rotate the camera - vs_position = camrot * vs_position; - - // rescales the scene to fit inside the view frustum - // is set from the main program, but these are decent values - //vec2 scaling = vec2(1.0, -8.0); - - // project using the rescaled coordinates, - //vec4 vs_position_rescaled = psc_scaling(vs_position, scaling); - vec4 vs_position_rescaled = psc_to_meter(vs_position, scaling); - - // project the position to view space - gl_Position = ViewProjection * vs_position_rescaled; -} \ No newline at end of file diff --git a/openspace-data b/openspace-data index 500458eba3..5675eb89b7 160000 --- a/openspace-data +++ b/openspace-data @@ -1 +1 @@ -Subproject commit 500458eba30fef87fbdc924a8918902d27674125 +Subproject commit 5675eb89b7b93dd5fd6817c0ac2d3b66a54594fc diff --git a/openspace.cfg b/openspace.cfg new file mode 100644 index 0000000000..345ba787d6 --- /dev/null +++ b/openspace.cfg @@ -0,0 +1,13 @@ +return { + paths = { + SGCT = "${BASE_PATH}/config/sgct", + SCRIPTS = "${BASE_PATH}/scripts", + KERNELS = "${BASE_PATH}/kernels", + SHADERS = "${BASE_PATH}/shaders", + OPENSPACE_DATA = "${BASE_PATH}/openspace-data", + TESTDIR = "${BASE_PATH}/src/tests", + SCENEPATH = "${OPENSPACE_DATA}/scene", + CONFIG = "${BASE_PATH}/config" + }, + sgctConfig = "${SGCT}/single.xml", +} \ No newline at end of file diff --git a/modules/common/shaders/pscstandard_fs.glsl b/shaders/pscstandard_fs.glsl similarity index 91% rename from modules/common/shaders/pscstandard_fs.glsl rename to shaders/pscstandard_fs.glsl index 99b734a58d..6a3faef107 100644 --- a/modules/common/shaders/pscstandard_fs.glsl +++ b/shaders/pscstandard_fs.glsl @@ -23,7 +23,7 @@ uniform bool Lightsource; uniform bool UseTexture; in vec2 vs_st; -in vec3 vs_stp; +//in vec3 vs_stp; in vec4 vs_normal; in vec4 vs_position; @@ -55,6 +55,7 @@ void main() float depth; // the value can be normalized to 1 + vec4 p = vs_position; if(vs_position.w <= 0.5) { //depth = abs(vs_position.z * pow(10, vs_position.w)) / pow(k,s_far); @@ -64,6 +65,7 @@ void main() } else { depth = vs_position.w+log(abs(vs_position.z)); } + // DEBUG float depth_orig = depth; @@ -99,10 +101,15 @@ void main() // set the depth gl_FragDepth = depth; + //gl_FragDepth = 0.5; // color - diffuse = texture2D(texture1, vs_st); + diffuse = texture(texture1, vs_st); + //diffuse = vec4(vs_position.z,0.0, 0.0, 1.0); // diffuse = vec4(vs_position.xyz * pow(10, vs_position.w), 1.0); - // diffuse = vec4(vs_st, 0.0, 1.0); + //diffuse = vec4(vs_st, 0.0, 1.0); + //diffuse = vec4(1.0,1.0, 0.0, 1.0); + //diffuse = vec4(depth*5,0.0, 0.0, 1.0); + //diffuse = vec4(vs_position.w,0.0, 0.0, 1.0); //diffuse = vec4(1.0,0.0,0.0,1.0); } \ No newline at end of file diff --git a/modules/common/shaders/pscstandard_vs.glsl b/shaders/pscstandard_vs.glsl similarity index 57% rename from modules/common/shaders/pscstandard_vs.glsl rename to shaders/pscstandard_vs.glsl index b9e794908f..0c588a7ccd 100644 --- a/modules/common/shaders/pscstandard_vs.glsl +++ b/shaders/pscstandard_vs.glsl @@ -1,11 +1,23 @@ /** Copyright (C) 2012-2014 Jonas Strandstedt -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. */ #version 400 core @@ -24,9 +36,10 @@ uniform bool Wireframe; uniform bool Lightsource; uniform bool UseTexture; -in vec4 in_position; -in vec2 in_st; -in vec3 in_normal; +layout(location = 0) in vec4 in_position; +//in vec3 in_position; +layout(location = 1) in vec2 in_st; +layout(location = 2) in vec3 in_normal; out vec2 vs_st; out vec3 vs_stp; @@ -48,7 +61,8 @@ vec4 psc_addition(vec4 v1, vec4 v2) { } vec4 psc_to_meter(vec4 v1, vec2 v2) { - return vec4(v1.xyz * v2.x * pow(k,v2.y + v1.w), 1.0); + float factor = v2.x * pow(k,v2.y + v1.w); + return vec4(v1.xyz * factor, 1.0); } vec4 psc_scaling(vec4 v1, vec2 v2) { @@ -64,31 +78,37 @@ void main() { // set variables vs_st = in_st; - vs_stp = in_position.xyz; - vs_normal = normalize(ModelTransform * vec4(in_normal,1)); + //vs_stp = in_position.xyz; + vs_normal = normalize(ModelTransform * vec4(in_normal,0)); // fetch model and view translation - vec4 vertex_translate = ModelTransform[3]; + //vec4 vertex_translate = ModelTransform[3]; // rotate and scale vertex with model transform and add the translation - vec3 local_vertex_pos = mat3(ModelTransform) * in_position.xyz + vertex_translate.xyz; + vec3 local_vertex_pos = mat3(ModelTransform) * in_position.xyz; + //vec4 lvp = ModelTransform * in_position; // PSC addition; local vertex position and the object power scaled world position vs_position = psc_addition(vec4(local_vertex_pos,in_position.w),objpos); + //vs_position = psc_addition(lvp,objpos); // PSC addition; rotated and viewscaled vertex and the cmaeras negative position vs_position = psc_addition(vs_position,vec4(-campos.xyz,campos.w)); // rotate the camera - vs_position = camrot * vs_position; + local_vertex_pos = mat3(camrot) * vs_position.xyz; + vs_position = vec4(local_vertex_pos, vs_position.w); + //vs_position = camrot* vs_position; // rescales the scene to fit inside the view frustum // is set from the main program, but these are decent values - //vec2 scaling = vec2(1.0, -8.0); + // scaling = vec2(1.0, -8.0); // project using the rescaled coordinates, //vec4 vs_position_rescaled = psc_scaling(vs_position, scaling); vec4 vs_position_rescaled = psc_to_meter(vs_position, scaling); + //vs_position = vs_position_rescaled; + // project the position to view space gl_Position = ViewProjection * vs_position_rescaled; diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 3a65b73669..0fe848c475 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -26,66 +26,60 @@ #set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin) set(SOURCE_ROOT_DIR ${CMAKE_CURRENT_SOURCE_DIR}) -set(HEADER_ROOT_DIR ${CMAKE_CURRENT_SOURCE_DIR}) - -file(GLOB MAIN_SOURCE ${SOURCE_ROOT_DIR}/*.cpp) -set(OPENSPACE_SOURCE ${OPENSPACE_SOURCE} ${MAIN_SOURCE}) -file(GLOB MAIN_HEADER ${SOURCE_ROOT_DIR}/*.h) -set(OPENSPACE_HEADER ${OPENSPACE_HEADER} ${MAIN_HEADER}) -source_group(Main FILES ${MAIN_SOURCE} ${MAIN_HEADER}) +set(HEADER_ROOT_DIR ${CMAKE_SOURCE_DIR}/include) file(GLOB CONFIGURATION_SOURCE ${SOURCE_ROOT_DIR}/configuration/*.cpp) set(OPENSPACE_SOURCE ${OPENSPACE_SOURCE} ${CONFIGURATION_SOURCE}) -file(GLOB CONFIGURATION_HEADER ${HEADER_ROOT_DIR}/configuration/*.h) +file(GLOB CONFIGURATION_HEADER ${HEADER_ROOT_DIR}/openspace/configuration/*.h) set(OPENSPACE_HEADER ${OPENSPACE_HEADER} ${CONFIGURATION_HEADER}) source_group(Configuration FILES ${CONFIGURATION_SOURCE} ${CONFIGURATION_HEADER}) file(GLOB ENGINE_SOURCE ${SOURCE_ROOT_DIR}/engine/*.cpp) set(OPENSPACE_SOURCE ${OPENSPACE_SOURCE} ${ENGINE_SOURCE}) -file(GLOB ENGINE_HEADER ${HEADER_ROOT_DIR}/engine/*.h) +file(GLOB ENGINE_HEADER ${HEADER_ROOT_DIR}/openspace/engine/*.h) set(OPENSPACE_HEADER ${OPENSPACE_HEADER} ${ENGINE_HEADER}) source_group(Engine FILES ${ENGINE_SOURCE} ${ENGINE_HEADER}) file(GLOB INTERACTION_SOURCE ${SOURCE_ROOT_DIR}/interaction/*.cpp) set(OPENSPACE_SOURCE ${OPENSPACE_SOURCE} ${INTERACTION_SOURCE}) -file(GLOB INTERACTION_HEADER ${HEADER_ROOT_DIR}/interaction/*.h) +file(GLOB INTERACTION_HEADER ${HEADER_ROOT_DIR}/openspace/interaction/*.h) set(OPENSPACE_HEADER ${OPENSPACE_HEADER} ${INTERACTION_HEADER}) source_group(Interaction FILES ${INTERACTION_SOURCE} ${INTERACTION_HEADER}) file(GLOB INTERACTION_EXTERNALCONTROL_SOURCE ${SOURCE_ROOT_DIR}/interaction/externalcontrol/*.cpp) set(OPENSPACE_SOURCE ${OPENSPACE_SOURCE} ${INTERACTION_EXTERNALCONTROL_SOURCE}) -file(GLOB INTERACTION_EXTERNALCONTROL_HEADER ${HEADER_ROOT_DIR}/interaction/externalcontrol/*.h) +file(GLOB INTERACTION_EXTERNALCONTROL_HEADER ${HEADER_ROOT_DIR}/openspace/interaction/externalcontrol/*.h) set(OPENSPACE_HEADER ${OPENSPACE_HEADER} ${INTERACTION_EXTERNALCONTROL_HEADER}) source_group(Interaction\\ExternalControl FILES ${INTERACTION_EXTERNALCONTROL_SOURCE} ${INTERACTION_EXTERNALCONTROL_HEADER}) file(GLOB QUERY_SOURCE_CPP ${SOURCE_ROOT_DIR}/query/*.cpp) file(GLOB QUERY_SOURCE_C ${SOURCE_ROOT_DIR}/query/*.c) set(OPENSPACE_SOURCE ${OPENSPACE_SOURCE} ${QUERY_SOURCE_CPP} ${QUERY_SOURCE_C}) -file(GLOB QUERY_HEADER ${HEADER_ROOT_DIR}/query/*.h) +file(GLOB QUERY_HEADER ${HEADER_ROOT_DIR}/openspace/query/*.h) set(OPENSPACE_HEADER ${OPENSPACE_HEADER} ${QUERY_HEADER}) source_group(Query FILES ${QUERY_SOURCE_CPP} ${QUERY_SOURCE_C} ${QUERY_HEADER}) file(GLOB RENDERING_SOURCE ${SOURCE_ROOT_DIR}/rendering/*.cpp) set(OPENSPACE_SOURCE ${OPENSPACE_SOURCE} ${RENDERING_SOURCE}) -file(GLOB RENDERING_HEADER ${HEADER_ROOT_DIR}/rendering/*.h) +file(GLOB RENDERING_HEADER ${HEADER_ROOT_DIR}/openspace/rendering/*.h) set(OPENSPACE_HEADER ${OPENSPACE_HEADER} ${RENDERING_HEADER}) source_group(Rendering FILES ${RENDERING_SOURCE} ${RENDERING_HEADER}) file(GLOB SCENEGRAPH_SOURCE ${SOURCE_ROOT_DIR}/scenegraph/*.cpp) set(OPENSPACE_SOURCE ${OPENSPACE_SOURCE} ${SCENEGRAPH_SOURCE}) -file(GLOB SCENEGRAPH_HEADER ${HEADER_ROOT_DIR}/scenegraph/*.h) +file(GLOB SCENEGRAPH_HEADER ${HEADER_ROOT_DIR}/openspace/scenegraph/*.h ${HEADER_ROOT_DIR}/openspace/scenegraph/*.inl) set(OPENSPACE_HEADER ${OPENSPACE_HEADER} ${SCENEGRAPH_HEADER}) source_group(SceneGraph FILES ${SCENEGRAPH_SOURCE} ${SCENEGRAPH_HEADER}) file(GLOB UTIL_SOURCE ${SOURCE_ROOT_DIR}/util/*.cpp) set(OPENSPACE_SOURCE ${OPENSPACE_SOURCE} ${UTIL_SOURCE}) -file(GLOB UTIL_HEADER ${HEADER_ROOT_DIR}/util/*.h) +file(GLOB UTIL_HEADER ${HEADER_ROOT_DIR}/openspace/util/*.h) set(OPENSPACE_HEADER ${OPENSPACE_HEADER} ${UTIL_HEADER}) source_group(Util FILES ${UTIL_SOURCE} ${UTIL_HEADER}) file(GLOB FLARE_SOURCE ${SOURCE_ROOT_DIR}/flare/*.cpp) set(OPENSPACE_SOURCE ${OPENSPACE_SOURCE} ${FLARE_SOURCE}) -file(GLOB FLARE_HEADER ${HEADER_ROOT_DIR}/flare/*.h) +file(GLOB FLARE_HEADER ${HEADER_ROOT_DIR}/openspace/flare/*.h) set(OPENSPACE_HEADER ${OPENSPACE_HEADER} ${FLARE_HEADER}) source_group(Flare FILES ${FLARE_SOURCE} ${FLARE_HEADER}) @@ -101,27 +95,9 @@ include_directories(${HEADER_ROOT_DIR}) set(OPENSPACE_SOURCE ${OPENSPACE_SOURCE} ${OPENSPACE_EXT_DIR}/tinythread.cpp) include_directories(${GHOUL_ROOT_DIR}/ext/boost) -if (APPLE) - find_library(FRAMEWORK_IOKit - NAMES IOKit - PATHS ${CMAKE_OSX_SYSROOT}/System/Library - PATH_SUFFIXES Frameworks - NO_DEFAULT_PATH - ) - find_library(FRAMEWORK_CoreVideo - NAMES CoreVideo - PATHS ${CMAKE_OSX_SYSROOT}/System/Library - PATH_SUFFIXES Frameworks - NO_DEFAULT_PATH - ) - find_library(FRAMEWORK_Cocoa - NAMES Cocoa - PATHS ${CMAKE_OSX_SYSROOT}/System/Library - PATH_SUFFIXES Frameworks - NO_DEFAULT_PATH - ) - set(SGCT_DEPENDENCIES ${SGCT_DEPENDENCIES} ${FRAMEWORK_IOKit} ${FRAMEWORK_CoreVideo} ${FRAMEWORK_Cocoa}) -endif (APPLE) +find_package(OpenCL REQUIRED) +include_directories(${OPENCL_INCLUDE_DIRS}) + if (APPLE) add_definitions(-D__APPLE__) @@ -136,5 +112,10 @@ if (UNIX AND NOT APPLE) endif (UNIX AND NOT APPLE) -add_executable(OpenSpace ${OPENSPACE_HEADER} ${OPENSPACE_SOURCE}) +include_directories("${HEADER_ROOT_DIR}") + +add_executable(OpenSpace ${SOURCE_ROOT_DIR}/main.cpp ${OPENSPACE_HEADER} ${OPENSPACE_SOURCE}) target_link_libraries(OpenSpace ${DEPENDENT_LIBS}) + +add_subdirectory(tests) + diff --git a/src/openspaceengine.cpp b/src/engine/openspaceengine.cpp similarity index 62% rename from src/openspaceengine.cpp rename to src/engine/openspaceengine.cpp index 8629a235d6..9157fd3ea5 100644 --- a/src/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -22,16 +22,17 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include "openspaceengine.h" +#include // sgct header has to be included before all others due to Windows header #include "sgct.h" -#include "interaction/deviceidentifier.h" -#include "interaction/interactionhandler.h" -#include "rendering/renderengine.h" -#include "util/time.h" -#include "util//spice.h" +#include +#include +#include +#include +#include +#include @@ -39,10 +40,16 @@ #include #include #include +#include +#include +#include +#include -#include -#include -#include +#include +#include +#include +#include +#include using namespace ghoul::filesystem; using namespace ghoul::logging; @@ -87,27 +94,108 @@ OpenSpaceEngine& OpenSpaceEngine::ref() { return *_engine; } -void OpenSpaceEngine::create(int argc, char** argv, int& newArgc, char**& newArgv) { +bool OpenSpaceEngine::registerPathsFromDictionary(const ghoul::Dictionary& dictionary) { + auto path_keys = dictionary.keys(); + for(auto key: path_keys) { + std::string p; + if(dictionary.getValue(key, p)) { + std::stringstream ss; + ss << "${" << key << "}"; + LDEBUG(ss.str() << ": " << p); + FileSys.registerPathToken(ss.str(), p); + } + } + + return true; +} +bool OpenSpaceEngine::registerBasePathFromConfigurationFile(const std::string& filename) { + if( ! FileSys.fileExists(filename)) + return false; + + const std::string absolutePath = FileSys.absolutePath(filename); + + auto last = absolutePath.find_last_of("/"); + if(last == absolutePath.npos) + return false; + + std::string basePath = absolutePath.substr(0, last); + + FileSys.registerPathToken("${BASE_PATH}", basePath); + + return true; +} + +bool OpenSpaceEngine::findConfiguration(std::string& filename) { + if (filename != "") { + return FileSys.fileExists(filename); + } + std::string currentDirectory = FileSys.currentDirectory(); + size_t occurrences = std::count(currentDirectory.begin(), currentDirectory.end(), '/'); + + std::string cfgname = "openspace.cfg"; + + for (int i = 0; i < occurrences; ++i) { + if(i > 0) { + cfgname = "../" + cfgname; + } + + if(FileSys.fileExists(cfgname)) + break; + } + if ( ! FileSys.fileExists(cfgname)) { + return false; + } + + filename = cfgname; + + return true; +} + +void OpenSpaceEngine::create(int argc, char** argv, std::vector& sgctArguments) { // TODO custom assert (ticket #5) assert(_engine == nullptr); - // set the arguments for SGCT - newArgc = 3; - newArgv = new char*[3]; - newArgv[0] = "prog"; - newArgv[1] = "-config"; -#ifdef __WIN32__ - // Windows uses fixed path to OpenSpace data - newArgv[2] = "../../config/single.xml"; -#elif __APPLE__ - // OS X uses local path to OpenSpace data - newArgv[2] = "../../../config/single.xml"; -#else - // Linux is is a bin folder - newArgv[2] = "../config/single.xml"; -#endif + // initialize ghoul logging + LogManager::initialize(LogManager::LogLevel::Debug, true); + LogMgr.addLog(new ConsoleLog); + + // TODO change so initialize is not called in the create function + ghoul::filesystem::FileSystem::initialize(); + + // TODO parse arguments if filename is specified, if not use default + std::string configurationFilePath = ""; + + LDEBUG("Finding configuration"); + if( ! OpenSpaceEngine::findConfiguration(configurationFilePath)) { + LFATAL("Could not find OpenSpace configuration file!"); + assert(false); + } + + LDEBUG("registering base path"); + if( ! OpenSpaceEngine::registerBasePathFromConfigurationFile(configurationFilePath)) { + LFATAL("Could not register base path"); + assert(false); + } + + ghoul::Dictionary configuration; + ghoul::lua::loadDictionary(configurationFilePath, configuration); + if(configuration.hasKey("paths")) { + ghoul::Dictionary pathsDictionary; + if(configuration.getValue("paths", pathsDictionary)) { + OpenSpaceEngine::registerPathsFromDictionary(pathsDictionary); + } + } + + std::string sgctConfigurationPath = "${SGCT}/single.xml"; + if(configuration.hasKey("sgctConfig")) { + configuration.getValue("sgctConfig", sgctConfigurationPath); + } + + sgctArguments.push_back("OpenSpace"); + sgctArguments.push_back("-config"); + sgctArguments.push_back(absPath(sgctConfigurationPath)); - // Create the engine objects + // create objects _engine = new OpenSpaceEngine; _engine->_renderEngine = new RenderEngine; _engine->_interactionHandler = new InteractionHandler; @@ -118,32 +206,19 @@ void OpenSpaceEngine::destroy() { delete _engine; } +bool OpenSpaceEngine::isInitialized() { + return _engine != nullptr; +} + bool OpenSpaceEngine::initialize() { - // Initialize the logmanager - LogManager::initialize(LogManager::LogLevel::Debug, true); - LogMgr.addLog(new ConsoleLog); - - // Initialize the filesystem module and register filesystem paths - ghoul::filesystem::FileSystem::initialize(); -#ifdef __WIN32__ - // Windows: Binary two folders down - FileSys.registerPathToken("${BASE_PATH}", "../.."); -#elif __APPLE__ - // OS X : Binary three folders down - FileSys.registerPathToken("${BASE_PATH}", "../../.."); -#else - // Linux : Binary three folders down - FileSys.registerPathToken("${BASE_PATH}", ".."); -#endif - FileSys.registerPathToken("${SCRIPTS}", "${BASE_PATH}/scripts"); - FileSys.registerPathToken("${OPENSPACE-DATA}", "${BASE_PATH}/openspace-data"); + // Register the filepaths from static function enables easy testing + //registerFilePaths(); - // Initialize configuration - _configurationManager->initialize(); - _configurationManager->loadConfiguration(absPath("${SCRIPTS}/DefaultConfig.lua")); + // initialize the configurationmanager with the default configuration + //_configurationManager->loadConfiguration(absPath("${SCRIPTS}/DefaultConfig.lua")); - // Detect and logOpenCL and OpenGL versions and available devices + // Detect and log OpenCL and OpenGL versions and available devices ghoul::systemcapabilities::SystemCapabilities::initialize(); SysCap.addComponent(new ghoul::systemcapabilities::CPUCapabilitiesComponent); SysCap.addComponent(new ghoul::systemcapabilities::OpenCLCapabilitiesComponent); @@ -155,10 +230,11 @@ bool OpenSpaceEngine::initialize() { Time::init(); Spice::init(); Spice::ref().loadDefaultKernels(); + FactoryManager::initialize(); // TODO add scenegraph file name - // Initilize scene graph and RenderEngine - _renderEngine->initialize(""); + // initialize the RenderEngine, needs ${SCENEPATH} to be set + _renderEngine->initialize(); // Initialize OpenSPace input devices DeviceIdentifier::init(); @@ -166,13 +242,8 @@ bool OpenSpaceEngine::initialize() { _engine->_interactionHandler->connectDevices(); - // Init interface -// _interface = new Interface(this); - -// Choose rendering _volumeRaycaster = new VolumeRaycaster(); _flare = new Flare(); - return true; } @@ -262,81 +333,11 @@ void OpenSpaceEngine::mouseScrollWheelCallback(int pos) { } void OpenSpaceEngine::encode() { - if (_useFlare) _flare->encode(); - if (_useVolumeRaycaster) _volumeRaycaster->encode(); + _flare->encode(); } void OpenSpaceEngine::decode() { - if (_useFlare) _flare->decode(); - if (_useVolumeRaycaster) _volumeRaycaster->decode(); + _flare->decode(); } } // namespace openspace - -/* -void RenderEngine::encode() { - - // allocate a sgct shared double for syncing - sgct::SharedDouble *shDouble = new sgct::SharedDouble(); - - // sync the time - shDouble->setVal(masterTime_); - sharedDataInstance_->writeDouble(shDouble); - - // check that the camera has been allocated - if(mainCamera_ != nullptr) { - - // sync position - psc campos = mainCamera_->getPosition(); - for(int i = 0; i < 4; i++) { - shDouble->setVal(campos[i]); - sharedDataInstance_->writeDouble(shDouble); - } - - // sync view direction - glm::quat camrot = mainCamera_->getRotation(); - for(int i = 0; i < 4; i++) { - shDouble->setVal(camrot[i]); - sharedDataInstance_->writeDouble(shDouble); - } - } - - // deallocate - delete shDouble; - -} - -void RenderEngine::decode() { - - // allocate a sgct shared double for syncing - sgct::SharedDouble *shDouble = new sgct::SharedDouble(); - - // sync the time - sharedDataInstance_->Double(shDouble); - masterTime_ = shDouble->getVal(); - - // check that the camera has been allocated - if(mainCamera_ != nullptr) { - - // sync position - psc campos; - for(int i = 0; i < 4; i++) { - sharedDataInstance_->readDouble(shDouble); - campos[i] = shDouble->getVal(); - } - mainCamera_->setPosition(campos); - - // sync view direction - glm::quat camrot; - for(int i = 0; i < 4; i++) { - sharedDataInstance_->readDouble(shDouble); - camrot[i] = static_cast(shDouble->getVal()); - } - mainCamera_->setRotation(camrot); - } - - // deallocate - delete shDouble; - -} -*/ diff --git a/src/flare/Animator.cpp b/src/flare/Animator.cpp index 595685748a..45aa041bf1 100644 --- a/src/flare/Animator.cpp +++ b/src/flare/Animator.cpp @@ -1,6 +1,6 @@ -#include -#include -#include +#include +#include +#include using namespace osp; diff --git a/src/flare/BrickManager.cpp b/src/flare/BrickManager.cpp index 623b417884..8f41bb7868 100644 --- a/src/flare/BrickManager.cpp +++ b/src/flare/BrickManager.cpp @@ -2,11 +2,11 @@ * Author: Victor Sand (victor.sand@gmail.com) * */ -#include -#include -#include -#include -#include + +#include +#include +#include +#include #include #include //#include @@ -108,9 +108,9 @@ bool BrickManager::ReadHeader() { numValsTot_ = numBrickVals_*numBricksFrame_; fseeko(file_, 0, SEEK_END); - off fileSize = ftello(file_); - off calcFileSize = static_cast(numBricksTree_) * - static_cast(brickSize_) + dataPos_; + off_t fileSize = ftello(file_); + off_t calcFileSize = static_cast(numBricksTree_) * + static_cast(brickSize_) + dataPos_; if (fileSize != calcFileSize) { ERROR("Sizes don't match"); @@ -157,9 +157,11 @@ bool BrickManager::InitAtlas() { dims.push_back(atlasDim_); dims.push_back(atlasDim_); dims.push_back(atlasDim_); - textureAtlas_ = Texture3D::New(dims); + textureAtlas_ = new ghoul::opengl::Texture(glm::size3_t(atlasDim_, atlasDim_, atlasDim_), ghoul::opengl::Texture::Format::RGBA, GL_RGBA, GL_FLOAT); + textureAtlas_->uploadTexture(); + //textureAtlas_ = Texture3D::New(dims); - if (!textureAtlas_->Init()) return false; + //if (!textureAtlas_->Init()) return false; atlasInitialized_ = true; @@ -366,9 +368,9 @@ bool BrickManager::DiskToPBO(BUFFER_INDEX _pboIndex) { static_cast(brickSize_); */ - off offset = dataPos_ + - static_cast(brickIndex) * - static_cast(brickSize_); + off_t offset = dataPos_ + + static_cast(brickIndex) * + static_cast(brickSize_); // Skip reading if all bricks in sequence is already in PBO if (inPBO != sequence) { @@ -448,11 +450,30 @@ bool BrickManager::DiskToPBO(BUFFER_INDEX _pboIndex) { bool BrickManager::PBOToAtlas(BUFFER_INDEX _pboIndex) { glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pboHandle_[_pboIndex]); + glm::size3_t dim = textureAtlas_->dimensions(); + glGetError(); + glBindTexture(GL_TEXTURE_3D, *textureAtlas_); + glTexSubImage3D(GL_TEXTURE_3D, + 0, + 0, + 0, + 0, + dim[0], + dim[1], + dim[2], + GL_RED, + GL_FLOAT, + NULL); + glBindTexture(GL_TEXTURE_3D, 0); + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); + + return (CheckGLError("Texture3D::UpdateSubRegion") == GL_NO_ERROR); + /* if (!textureAtlas_->UpdateSubRegion(0, 0, 0, textureAtlas_->Dim(0), textureAtlas_->Dim(1), textureAtlas_->Dim(2), 0)) return false; - glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - return true; + */ + //return true; } diff --git a/src/flare/CLManager.cpp b/src/flare/CLManager.cpp index 06fe9431a7..39ecdbe7d9 100644 --- a/src/flare/CLManager.cpp +++ b/src/flare/CLManager.cpp @@ -2,22 +2,21 @@ * Author: Victor Sand (victor.sand@gmail.com) * */ -#include -#ifndef _WIN32 - #include -#else - #include - #include - #include -#endif -#include -#include -#include -#include -#include -#include +//#include +#include +#include +#include +#include +#include #include +#include +#include + +namespace { + std::string _loggerCat = "CLManager"; +} + using namespace osp; CLManager::CLManager() { @@ -34,7 +33,7 @@ CLManager::~CLManager() { for (unsigned int i=0; i 1) - devices_[0] = devices_[1]; - - // TODO Support more than one device? - context_ = clCreateContext(contextProperties, 1, &devices_[0], NULL, - NULL, &error_); - - return CheckSuccess(error_, "CreateContext()"); + devices_[0] = _context.device(); + return success; } bool CLManager::CreateCommandQueue() { for (unsigned int i=0; i -#include -#include -#include -#include -#include +//#include +#include +#include +#include +#include +#include +#include -#ifdef _WIN32 -#include -#endif +namespace { + std::string _loggerCat = "CLProgram"; +} using namespace osp; @@ -32,7 +33,7 @@ CLProgram::~CLProgram() { bool CLProgram::CreateProgram(std::string _fileName) { int numChars; char *source = ReadSource(_fileName, numChars); - program_ = clCreateProgramWithSource(clManager_->context_, 1, + program_ = clCreateProgramWithSource(clManager_->_context, 1, (const char**)&source, NULL, &error_); free(source); @@ -41,9 +42,11 @@ bool CLProgram::CreateProgram(std::string _fileName) { bool CLProgram::BuildProgram() { +std::string options = "-cl-opt-disable"; error_ = clBuildProgram(program_, (cl_uint)0, - NULL, NULL, NULL, NULL); + NULL, options.c_str(), NULL, NULL); if (error_ != CL_SUCCESS) { + LDEBUG("Could not build program " << getErrorString(error_)); // Print build log char * log; size_t logSize = 0; @@ -70,7 +73,7 @@ bool CLProgram::CreateKernel() { } -bool CLProgram::AddTexture(unsigned int _argNr, Texture *_texture, +bool CLProgram::AddTexture(unsigned int _argNr, ghoul::opengl::Texture *_texture, GLuint _textureType, cl_mem_flags _permissions) { @@ -86,14 +89,26 @@ bool CLProgram::AddTexture(unsigned int _argNr, Texture *_texture, return false; break; case GL_TEXTURE_2D: - texture = clCreateFromGLTexture2D(clManager_->context_, _permissions, - GL_TEXTURE_2D, 0, - _texture->Handle(), &error_); - break; - case GL_TEXTURE_3D: - texture = clCreateFromGLTexture3D(clManager_->context_, _permissions, - GL_TEXTURE_3D, 0, - _texture->Handle(), &error_); +#ifdef CL_VERSION_1_2 + texture = clCreateFromGLTexture(clManager_->_context, _permissions, + GL_TEXTURE_2D, 0, + *_texture, &error_); +#else + texture = clCreateFromGLTexture2D(clManager_->_context, _permissions, + GL_TEXTURE_2D, 0, + *_texture, &error_); +#endif + break; + case GL_TEXTURE_3D: +#ifdef CL_VERSION_1_2 + texture = clCreateFromGLTexture(clManager_->_context, _permissions, + GL_TEXTURE_3D, 0, + *_texture, &error_); +#else + texture = clCreateFromGLTexture3D(clManager_->_context, _permissions, + GL_TEXTURE_3D, 0, + *_texture, &error_); +#endif break; default: ERROR("Unknown GL texture type"); @@ -109,7 +124,7 @@ bool CLProgram::AddTexture(unsigned int _argNr, Texture *_texture, } -bool CLProgram::AddTexture(unsigned int _argNr, Texture *_texture, +bool CLProgram::AddTexture(unsigned int _argNr, ghoul::opengl::Texture *_texture, GLuint _textureType, cl_mem_flags _permissions, cl_mem& _clTextureMem) { @@ -125,14 +140,26 @@ bool CLProgram::AddTexture(unsigned int _argNr, Texture *_texture, return false; break; case GL_TEXTURE_2D: - _clTextureMem = clCreateFromGLTexture2D(clManager_->context_, _permissions, +#ifdef CL_VERSION_1_2 + _clTextureMem = clCreateFromGLTexture(clManager_->_context, _permissions, GL_TEXTURE_2D, 0, - _texture->Handle(), &error_); + *_texture, &error_); +#else + _clTextureMem = clCreateFromGLTexture2D(clManager_->_context, _permissions, + GL_TEXTURE_2D, 0, + *_texture, &error_); +#endif break; case GL_TEXTURE_3D: - _clTextureMem = clCreateFromGLTexture3D(clManager_->context_, _permissions, - GL_TEXTURE_3D, 0, - _texture->Handle(), &error_); +#ifdef CL_VERSION_1_2 + _clTextureMem = clCreateFromGLTexture(clManager_->_context, _permissions, + GL_TEXTURE_3D, 0, + *_texture, &error_); +#else + _clTextureMem = clCreateFromGLTexture2D(clManager_->_context, _permissions, + GL_TEXTURE_3D, 0, + *_texture, &error_); +#endif break; default: ERROR("Unknown GL texture type"); @@ -176,7 +203,7 @@ bool CLProgram::AddBuffer(unsigned int _argNr, } MemArg ma; ma.size_ = sizeof(cl_mem); - ma.mem_ = clCreateBuffer(clManager_->context_, + ma.mem_ = clCreateBuffer(clManager_->_context, _allocMode | _permissions, (size_t)_sizeInBytes, _hostPtr, @@ -196,10 +223,15 @@ bool CLProgram::ReadBuffer(unsigned int _argNr, ERROR("ReadBuffer(): Could not find mem arg " << _argNr); return false; } - error_ = clEnqueueReadBuffer( - clManager_->commandQueues_[CLManager::EXECUTE], - memArgs_[(cl_uint)_argNr].mem_, _blocking, 0, _sizeInBytes, - _hostPtr, 0, NULL, NULL); + error_ = clEnqueueReadBuffer(clManager_->commandQueues_[CLManager::EXECUTE], + memArgs_[(cl_uint)_argNr].mem_, + _blocking, + 0, + _sizeInBytes, + _hostPtr, + 0, + NULL, + NULL); return clManager_->CheckSuccess(error_, "ReadBuffer"); } @@ -208,25 +240,38 @@ bool CLProgram::ReleaseBuffer(unsigned int _argNr) { ERROR("ReleaseBuffer(): Could not find mem arg " << _argNr); return false; } + //LDEBUG("Releasing memory"); error_ = clReleaseMemObject(memArgs_[(cl_uint)_argNr].mem_); return clManager_->CheckSuccess(error_, "ReleaseBuffer"); } bool CLProgram::PrepareProgram() { - +//ghoulFinishGL(); +/* +#ifdef __APPLE__ + + //glFlushRenderAPPLE(); + glFinish(); + //glFlush(); +#else +*/ + + glFinish(); // Let OpenCL take control of the shared GL textures for (auto it = OGLTextures_.begin(); it != OGLTextures_.end(); ++it) { - error_ = clEnqueueAcquireGLObjects( - clManager_->commandQueues_[CLManager::EXECUTE], 1, - &(it->second), 0, NULL, NULL); - + ghoul::opencl::CLCommandQueue q = clManager_->commandQueues_[CLManager::EXECUTE]; + cl_command_queue clq = q; + error_ = clEnqueueAcquireGLObjects(clq, 1, &(it->second), 0, NULL, NULL); + if (!clManager_->CheckSuccess(error_, "PrepareProgram")) { + LDEBUG("error: " << getErrorString(error_)); ERROR("Failed to enqueue GL object aqcuisition"); ERROR("Failing object: " << it->first); return false; } } +//#endif // Set up kernel arguments of non-shared items for (auto it=memArgs_.begin(); it!=memArgs_.end(); ++it) { @@ -276,14 +321,10 @@ bool CLProgram::LaunchProgram(unsigned int _gx, unsigned int _gy, } bool CLProgram::FinishProgram() { - + +//#ifndef __APPLE__ // Make sure kernel is done - error_ = clFinish(clManager_->commandQueues_[CLManager::EXECUTE]); - if (!clManager_->CheckSuccess(error_, "FinishProgram, clFinish")) { - ERROR("Failed to finish program"); - return false; - } - + // Release shared OGL objects for (auto it=OGLTextures_.begin(); it!=OGLTextures_.end(); ++it) { error_ = clEnqueueReleaseGLObjects( @@ -295,7 +336,20 @@ bool CLProgram::FinishProgram() { return false; } } - + error_ = clFinish(clManager_->commandQueues_[CLManager::EXECUTE]); + if (!clManager_->CheckSuccess(error_, "FinishProgram, clFinish")) { + ERROR("Failed to finish program"); + return false; + } + /* +#else + error_ = clFinish(clManager_->commandQueues_[CLManager::EXECUTE]); + if (!clManager_->CheckSuccess(error_, "FinishProgram, clFinish")) { + ERROR("Failed to finish program"); + return false; + } +#endif +*/ return true; } diff --git a/src/flare/Config.cpp b/src/flare/Config.cpp index e6608a09cd..dad1583edb 100644 --- a/src/flare/Config.cpp +++ b/src/flare/Config.cpp @@ -3,11 +3,12 @@ * */ -#include +#include #include #include #include -#include +#include +#include using namespace osp; @@ -85,9 +86,11 @@ bool Config::Read() { // Save value if (variable == "tsp_filename") { ss >> TSPFilename_; + TSPFilename_ = absPath(TSPFilename_); INFO("TSP file name: " << TSPFilename_); } else if (variable == "transferfunction_filename") { - ss >> TFFilename_; + ss >> TFFilename_; + TFFilename_ = absPath(TFFilename_); INFO("Transfer function file name " << TFFilename_); } else if (variable == "spatial_error_tolerance") { ss >> spatialErrorTolerance_; @@ -115,21 +118,27 @@ bool Config::Read() { INFO("Win height: " << winHeight_); } else if (variable == "raycaster_kernel_filename") { ss >> raycasterKernelFilename_; + raycasterKernelFilename_ = absPath(raycasterKernelFilename_); INFO("Raycaster kernel file name: " << raycasterKernelFilename_); } else if (variable == "tsp_traversal_kernel_filename" ) { ss >> TSPTraversalKernelFilename_; + TSPTraversalKernelFilename_ = absPath(TSPTraversalKernelFilename_); INFO("TSP traversal kernel file name: " <> cubeShaderVertFilename_; + cubeShaderVertFilename_ = absPath(cubeShaderVertFilename_); INFO("Cube vertex shader file name: " << cubeShaderVertFilename_); } else if (variable == "cube_shader_frag_filename") { ss >> cubeShaderFragFilename_; + cubeShaderFragFilename_ = absPath(cubeShaderFragFilename_); INFO("Cube fragment shader file name: " << cubeShaderFragFilename_); } else if (variable == "quad_shader_vert_filename") { ss >> quadShaderVertFilename_; + quadShaderVertFilename_ = absPath(quadShaderVertFilename_); INFO("Quad vertex shader file name: " << quadShaderVertFilename_); } else if (variable == "quad_shader_frag_filename") { ss >> quadShaderFragFilename_; + quadShaderFragFilename_ = absPath(quadShaderFragFilename_); INFO("Cube vertex shader file name: " << quadShaderFragFilename_); } else if (variable == "mouse_pitch_factor") { ss >> mousePitchFactor_; diff --git a/src/flare/MappingKey.cpp b/src/flare/MappingKey.cpp index d1bf79972a..1d8d57ab1e 100644 --- a/src/flare/MappingKey.cpp +++ b/src/flare/MappingKey.cpp @@ -1,4 +1,4 @@ -#include +#include #include #include diff --git a/src/flare/Raycaster.cpp b/src/flare/Raycaster.cpp index eb97bd4066..7c1fc280be 100644 --- a/src/flare/Raycaster.cpp +++ b/src/flare/Raycaster.cpp @@ -3,28 +3,25 @@ * */ +#include #include -#ifndef _WIN32 - #include -#endif +#include #include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include #include -#include -#include +#include +#include #include -#include -#include -#include +#include +#include +#include #include #include // sync() + + using namespace osp; uint32_t ZOrder(uint16_t xPos, uint16_t yPos, uint16_t zPos) { @@ -76,12 +73,14 @@ Raycaster::Raycaster(Config *_config) cubeInitialized_(false), quadInitialized_(false), framebuffersInitialized_(false), - pingPongIndex_(true), - animator_(NULL), pingPong_(0), + animator_(NULL), lastTimestep_(1), + pingPongIndex_(true), brickManager_(NULL), - clManager_(NULL) { + clManager_(NULL), + cubeFrontCLmem(0), + cubeBackCLmem(0) { } Raycaster::~Raycaster() { @@ -147,8 +146,9 @@ bool Raycaster::Render(float _timestep) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Render cube - glUseProgram(cubeShaderProgram_->Handle()); - cubePositionAttrib_ = cubeShaderProgram_->GetAttribLocation("position"); + cubeShaderProgram_->activate(); + //glUseProgram(cubeShaderProgram_->Handle()); + cubePositionAttrib_ = cubeShaderProgram_->attributeLocation("position"); if (cubePositionAttrib_ == -1) { ERROR("Cube position attribute lookup failed"); return false; @@ -272,12 +272,30 @@ bool Raycaster::Render(float _timestep) { // Render to framebuffer using quad glBindFramebuffer(GL_FRAMEBUFFER, sgct::Engine::instance()->getActiveWindowPtr()->getFBOPtr()->getBufferID()); - if (!quadTex_->Bind(quadShaderProgram_, "quadTex", 0)) return false; + glGetError(); + quadShaderProgram_->activate(); + glActiveTexture(GL_TEXTURE0); + int location = quadShaderProgram_->uniformLocation("quadTex"); + //int location = glGetUniformLocation(_shaderProgram->Handle(),_uniformName.c_str()); + if (location == -1) { + ERROR("Uniform " << "quadTex" << " could not be found"); + glUseProgram(0); + return false; + } + + glUniform1i(location, 0); + glBindTexture(GL_TEXTURE_2D, *quadTex_); + glUseProgram(0); + + + //if (!quadTex_->Bind(quadShaderProgram_, "quadTex", 0)) return false; glDisable(GL_CULL_FACE); - glUseProgram(quadShaderProgram_->Handle()); - quadPositionAttrib_ = quadShaderProgram_->GetAttribLocation("position"); + quadShaderProgram_->activate(); + //glUseProgram(quadShaderProgram_->Handle()); + //quadPositionAttrib_ = quadShaderProgram_->GetAttribLocation("position"); + quadPositionAttrib_ = quadShaderProgram_->attributeLocation("position"); if (quadPositionAttrib_ == -1) { ERROR("Quad position attribute lookup failed"); return false; @@ -348,7 +366,8 @@ bool Raycaster::InitPipeline() { // Allocate space for the brick request list // Use 0 as default value brickRequest_.resize(tsp_->NumTotalNodes(), 0); - + + glFinish(); // Run TSP traversal for timestep 0 if (!LaunchTSPTraversal(0)) { ERROR("InitPipeline() - failed to launch TSP traversal"); @@ -357,7 +376,7 @@ bool Raycaster::InitPipeline() { // Finish TSP traversal and read results into brick request if (!clManager_->FinishProgram("TSPTraversal")) return false; - + if (!clManager_->ReadBuffer("TSPTraversal", tspBrickListArg_, reinterpret_cast(&brickRequest_[0]), brickRequest_.size()*sizeof(int), @@ -510,7 +529,7 @@ bool Raycaster::InitFramebuffers() { glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, - cubeFrontTex_->Handle(), + *cubeFrontTex_, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, @@ -532,7 +551,7 @@ bool Raycaster::InitFramebuffers() { glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, - cubeBackTex_->Handle(), + *cubeBackTex_, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, @@ -588,23 +607,29 @@ bool Raycaster::UpdateMatrices() { return true; } -bool Raycaster::BindTransformationMatrices(ShaderProgram * _program) +bool Raycaster::BindTransformationMatrices(ghoul::opengl::ProgramObject * _program) { + if (!_program->setUniform("modelMatrix", model_)) return false; + if (!_program->setUniform("viewMatrix", view_)) return false; + if (!_program->setUniform("projectionMatrix", proj_)) return false; + +/* if (!_program->BindMatrix4f("modelMatrix", &model_[0][0])) return false; if (!_program->BindMatrix4f("viewMatrix", &view_[0][0])) return false; if (!_program->BindMatrix4f("projectionMatrix", &proj_[0][0])) return false; + */ return true; } -void Raycaster::SetCubeFrontTexture(Texture2D *_cubeFrontTexture) { +void Raycaster::SetCubeFrontTexture(ghoul::opengl::Texture *_cubeFrontTexture) { cubeFrontTex_ = _cubeFrontTexture; } -void Raycaster::SetCubeBackTexture(Texture2D *_cubeBackTexture) { +void Raycaster::SetCubeBackTexture(ghoul::opengl::Texture *_cubeBackTexture) { cubeBackTex_ = _cubeBackTexture; } -void Raycaster::SetQuadTexture(Texture2D *_quadTexture) { +void Raycaster::SetQuadTexture(ghoul::opengl::Texture *_quadTexture) { quadTex_ = _quadTexture; } @@ -616,21 +641,19 @@ void Raycaster::SetTSP(TSP *_tsp) { tsp_ = _tsp; } -void Raycaster::SetCubeShaderProgram(ShaderProgram *_cubeShaderProgram) { +void Raycaster::SetCubeShaderProgram(ghoul::opengl::ProgramObject *_cubeShaderProgram) { cubeShaderProgram_ = _cubeShaderProgram; } -void Raycaster::SetQuadShaderProgram(ShaderProgram *_quadShaderProgram) { +void Raycaster::SetQuadShaderProgram(ghoul::opengl::ProgramObject *_quadShaderProgram) { quadShaderProgram_ = _quadShaderProgram; } bool Raycaster::ReloadShaders() { glGetError(); - INFO("Reloading shaders"); - if (!cubeShaderProgram_->DeleteShaders()) return false; - if (!quadShaderProgram_->DeleteShaders()) return false; - if (!cubeShaderProgram_->Reload()) return false; - if (!quadShaderProgram_->Reload()) return false; + INFO("Reloading shaders"); + if (!cubeShaderProgram_->rebuildFromFile()) return false; + if (!quadShaderProgram_->rebuildFromFile()) return false; CheckGLError("ReloadShaders()"); return true; } @@ -670,19 +693,24 @@ bool Raycaster::InitCL() { } if (!clManager_->BuildProgram("TSPTraversal")) return false; if (!clManager_->CreateKernel("TSPTraversal")) return false; - cl_mem cubeFrontCLmem; + //cl_mem cubeFrontCLmem; if (!clManager_->AddTexture("TSPTraversal", tspCubeFrontArg_, cubeFrontTex_, CLManager::TEXTURE_2D, CLManager::READ_ONLY, cubeFrontCLmem)) { return false; } - cl_mem cubeBackCLmem; + //cl_mem cubeBackCLmem; if (!clManager_->AddTexture("TSPTraversal", tspCubeBackArg_, cubeBackTex_, CLManager::TEXTURE_2D, CLManager::READ_ONLY, cubeBackCLmem)) { return false; } + /* + if (!clManager_->AddTexture("TSPTraversal", quadArg_, quadTex_, + CLManager::TEXTURE_2D, + CLManager::WRITE_ONLY)) return false; + */ if (!clManager_->AddBuffer("TSPTraversal", tspTSPArg_, reinterpret_cast(tsp_->Data()), tsp_->Size()*sizeof(int), @@ -690,6 +718,7 @@ bool Raycaster::InitCL() { CLManager::READ_ONLY)) return false; + LDEBUGC("RAYCASTER", config_->RaycasterKernelFilename()); // Raycaster part if (!clManager_->CreateProgram("RaycasterTSP", config_->RaycasterKernelFilename())) { @@ -769,7 +798,18 @@ bool Raycaster::UpdateKernelConstants() { static_cast(tsp_->NumValuesPerNode()); traversalConstants_.numOTNodes_ = static_cast(tsp_->NumOTNodes()); traversalConstants_.temporalTolerance_ = config_->TemporalErrorTolerance(); - traversalConstants_.spatialTolerance_ = config_->SpatialErrorTolerance(); + traversalConstants_.spatialTolerance_ = config_->SpatialErrorTolerance(); + + + std::string _loggerCat = "KOLLA KONSTANTER"; + LDEBUG("traversalConstants_.gridType_: " << traversalConstants_.gridType_); + LDEBUG("traversalConstants_.numOTNodes_: " << traversalConstants_.numOTNodes_); + LDEBUG("traversalConstants_.numTimesteps_: " << traversalConstants_.numTimesteps_); + LDEBUG("traversalConstants_.numValuesPerNode_: " << traversalConstants_.numValuesPerNode_); + LDEBUG("traversalConstants_.spatialTolerance_: " << traversalConstants_.spatialTolerance_); + LDEBUG("traversalConstants_.stepsize_: " << traversalConstants_.stepsize_); + LDEBUG("traversalConstants_.temporalTolerance_: " << traversalConstants_.temporalTolerance_); + if (!clManager_->AddBuffer("RaycasterTSP", constantsArg_, reinterpret_cast(&kernelConstants_), diff --git a/src/flare/Renderer.cpp b/src/flare/Renderer.cpp index 62136d8b74..d64785bdaf 100644 --- a/src/flare/Renderer.cpp +++ b/src/flare/Renderer.cpp @@ -3,7 +3,7 @@ * */ -#include +#include #include using namespace osp; diff --git a/src/flare/ShaderProgram.cpp b/src/flare/ShaderProgram.cpp deleted file mode 100644 index 19b49d5b0b..0000000000 --- a/src/flare/ShaderProgram.cpp +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Author: Victor Sand (victor.sand@gmail.com) - * - */ - -// TODO abstraction of shader binder, maybe a templated ShaderBinder class? -// or string values service -// possibly make a common UniformType class to handle matrices, ints, floats -#include -#ifndef _WIN32 - #include -#else - #include -#endif -#include -#include -#include -#include -#include - -using namespace osp; - -ShaderProgram * ShaderProgram::New() { - return new ShaderProgram(); -} - -ShaderProgram::ShaderProgram() - : vertexShaderSet_(false), - fragmentShaderSet_(false), - programHandle_(0), - vertexSource_(""), - fragmentSource_("") { -} - - -bool ShaderProgram::CreateShader(ShaderType _type, std::string _fileName) { - // Handle different types - // Save source filenames to enable reloading shaders - std::string typeString; - GLuint type; - switch (_type) { - case ShaderProgram::VERTEX: - type = GL_VERTEX_SHADER; - typeString = "vertex"; - vertexSource_ = _fileName; - break; - case ShaderProgram::FRAGMENT: - type = GL_FRAGMENT_SHADER; - typeString = "fragment"; - fragmentSource_ = _fileName; - break; - default: - ERROR("Invalid shader type"); - return false; - } - - INFO("Creating " << typeString << " shader from source file " << _fileName); - - // Create shader - unsigned int handle = glCreateShader(type); - if (glIsShader(handle) == GL_FALSE) { - ERROR("Failed to create shader"); - CheckGLError("CreateShader()"); - return false; - } - - // Read shader source - char *source = ReadTextFile(_fileName); - const char *constSource = source; - glShaderSource(handle, 1, &constSource, NULL); - glCompileShader(handle); - int shaderCompiled; - glGetShaderiv(handle, GL_COMPILE_STATUS, &shaderCompiled); - - if (shaderCompiled != GL_TRUE) { - ERROR("Shader compilation failed"); - CheckGLError("CreateShader()"); - PrintLog(handle); - return false; - } - - // Save shader handle - shaderHandles_.push_back(handle); - free(source); - if (_type == ShaderProgram::VERTEX) vertexShaderSet_ = true; - else if (_type == ShaderProgram::FRAGMENT) fragmentShaderSet_ = true; - return true; -} - -bool ShaderProgram::CreateProgram() { - INFO("Creating shader program"); - - if (!vertexShaderSet_){ - ERROR("Can't create program, vertex shader not set"); - return false; - } - - if (!fragmentShaderSet_) { - ERROR("Can't create program, fragment shader not set"); - return false; - } - - // Create new program - programHandle_ = glCreateProgram(); - - // Attach the shaders - std::vector::iterator it; - for (it=shaderHandles_.begin(); it!=shaderHandles_.end(); it++) - { - glAttachShader(programHandle_, *it); - } - - // Link the program - INFO("Linking shader program"); - glLinkProgram(programHandle_); - int programLinked; - glGetProgramiv(programHandle_, GL_LINK_STATUS, &programLinked); - if (programLinked != GL_TRUE) { - ERROR("Program linking failed"); - CheckGLError("CreateProgram()"); - PrintLog(programHandle_); - return false; - } - - return true; -} - -bool ShaderProgram::PrintLog(unsigned int _handle) const { - int logLength, maxLength; - - // Handle shaders and programs differently - if (glIsShader(_handle)) { - glGetShaderiv(_handle, GL_INFO_LOG_LENGTH, &maxLength); - } else { - glGetProgramiv(_handle, GL_INFO_LOG_LENGTH, &maxLength); - } - - std::vector log(maxLength); - if (glIsShader(_handle)) { - glGetShaderInfoLog(_handle, maxLength, &logLength, (GLchar*)&log[0]); - } else { - glGetProgramInfoLog(_handle, maxLength, &logLength, (GLchar*)&log[0]); - } - - if (logLength > 0) { - DEBUG(&log[0]); - } else { - ERROR("Log length is not over zero"); - return false; - } - - return true; -} - -char * ShaderProgram::ReadTextFile(std::string _fileName) const -{ - FILE * in; - char * content = NULL; - in = fopen(_fileName.c_str(), "r"); - if (in != NULL) { - fseek(in, 0, SEEK_END); - int count = ftell(in); - rewind(in); - content = (char *)malloc(sizeof(char)*(count+1)); - count = fread(content, sizeof(char), count, in); - content[count] = '\0'; - fclose(in); - } else { - ERROR("Could not read file " + _fileName); - } - return content; -} - -bool ShaderProgram::BindMatrix4f(std::string _uniform, float * _matrix) { - glUseProgram(programHandle_); - int location = glGetUniformLocation(programHandle_, _uniform.c_str()); - if (location == -1) { - ERROR("Uniform " << _uniform << " could not be found"); - glUseProgram(0); - return false; - } - glUniformMatrix4fv(location, 1, GL_FALSE, _matrix); - glUseProgram(0); - return CheckGLError("BindMatrix4f()") == GL_NO_ERROR; -} - -// TODO see if glUseProgram must be called before glGetUniformLocation -bool ShaderProgram::BindFloat(std::string _uniform, float _value) { - glUseProgram(programHandle_); - int location = glGetUniformLocation(programHandle_, _uniform.c_str()); - if (location == -1) { - ERROR("Uniform " << _uniform << " could not be found"); - glUseProgram(0); - return false; - } - glUniform1f(location, _value); - glUseProgram(0); - return CheckGLError("BindFloat()") == GL_NO_ERROR; -} - -bool ShaderProgram::BindInt(std::string _uniform, int _value) { - glUseProgram(programHandle_); - int location = glGetUniformLocation(programHandle_, _uniform.c_str()); - if (location == -1) { - ERROR("Uniform " << _uniform << " could not be found"); - glUseProgram(0); - return false; - } - glUniform1i(location, _value); - glUseProgram(0); - return CheckGLError("Bindintf()") == GL_NO_ERROR; -} - -unsigned int ShaderProgram::GetAttribLocation(std::string _attrib) const { - return glGetAttribLocation(programHandle_, _attrib.c_str()); -} - -bool ShaderProgram::Reload() { - if (!vertexShaderSet_ || !fragmentShaderSet_) { - ERROR("Can't reload, shaders not set"); - return false; - } - CreateShader(ShaderProgram::VERTEX, vertexSource_); - CreateShader(ShaderProgram::FRAGMENT, fragmentSource_); - CreateProgram(); - return true; -} - -bool ShaderProgram::DeleteShaders() { - if (!vertexShaderSet_ || !fragmentShaderSet_) { - ERROR("Shader(s) not set, nothing to delete"); - return false; - } - for (unsigned int i=0; i -#include - -namespace osp { - -class Texture2D; - -class ShaderProgram { -public: - enum ShaderType { - VERTEX, - FRAGMENT - }; - static ShaderProgram * New(); - // Create shader from source file - bool CreateShader(ShaderType _type, std::string _fileName); - // Create and link shader program using shaders in shaderHandles_ - bool CreateProgram(); - // Print the log of any shader - bool PrintLog (unsigned int _handle) const; - // Bind a 4x4 float matrix to the shader program - bool BindMatrix4f(std::string _uniformName, float *_matrix); - // Bind a float to the shader program - bool BindFloat(std::string _uniformName, float _value); - // Bind an integer to the shader program - bool BindInt(std::string _uniformName, int _value); - unsigned int Handle() const { return programHandle_; } - // Get location for named attribute - unsigned int GetAttribLocation(std::string _attrib) const; - // Use the last used file name to re-create shader program - bool Reload(); - // Detach and delete shaders - bool DeleteShaders(); -private: - ShaderProgram(); - // Read a shader source text file, return char array - char * ReadTextFile(std::string _fileName) const; - bool vertexShaderSet_; - bool fragmentShaderSet_; - // Handles to shaders created by CreateShader are saved here - std::vector shaderHandles_; - unsigned int programHandle_; - // Keep track of last used source file names - std::string vertexSource_; - std::string fragmentSource_; -}; - -} - -#endif diff --git a/src/flare/TSP.cpp b/src/flare/TSP.cpp index 954cee57e8..14f167f8d6 100644 --- a/src/flare/TSP.cpp +++ b/src/flare/TSP.cpp @@ -3,14 +3,14 @@ * */ -#include -#include +#include +#include #include -#include +#include #include #include #include -#include +#include #include using namespace osp; @@ -165,7 +165,7 @@ bool TSP::CalculateSpatialError() { for (unsigned int brick=0; brick(brick*numBrickVals*sizeof(float)); + off_t offset = dataPos_ + static_cast(brick*numBrickVals*sizeof(float)); fseeko(in, offset, SEEK_SET); fread(reinterpret_cast(&buffer[0]), @@ -212,7 +212,7 @@ bool TSP::CalculateSpatialError() { lb!=coveredLeafBricks.end(); ++lb) { // Read brick - off offset = dataPos_+static_cast((*lb)*numBrickVals*sizeof(float)); + off_t offset = dataPos_+static_cast((*lb)*numBrickVals*sizeof(float)); fseeko(in, offset, SEEK_SET); fread(reinterpret_cast(&buffer[0]), static_cast(numBrickVals)*sizeof(float), 1, in); @@ -323,7 +323,7 @@ bool TSP::CalculateTemporalError() { std::vector voxelStdDevs(numBrickVals); // Read the whole brick to fill the averages - off offset = dataPos_+static_cast(brick*numBrickVals*sizeof(float)); + off_t offset = dataPos_+static_cast(brick*numBrickVals*sizeof(float)); fseeko(in, offset, SEEK_SET); fread(reinterpret_cast(&voxelAverages[0]), static_cast(numBrickVals)*sizeof(float), 1, in); @@ -349,8 +349,8 @@ bool TSP::CalculateTemporalError() { leaf != coveredBricks.end(); ++leaf) { // Sample the leaves at the corresponding voxel position - off sampleOffset = dataPos_ + - static_cast((*leaf*numBrickVals+voxel)*sizeof(float)); + off_t sampleOffset = dataPos_ + + static_cast((*leaf*numBrickVals+voxel)*sizeof(float)); fseeko(in, sampleOffset, SEEK_SET); float sample; fread(reinterpret_cast(&sample), sizeof(float), 1, in); diff --git a/src/flare/Texture.cpp b/src/flare/Texture.cpp deleted file mode 100644 index 9f849a3516..0000000000 --- a/src/flare/Texture.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Author: Victor Sand (victor.sand@gmail.com) - * - */ -#include -#include -#include - -using namespace osp; - -Texture::Texture(std::vector _dim) - : dim_(_dim), - handle_(0), - initialized_(false) { -} - -unsigned int Texture::Dim(unsigned int _axis) const { - if (_axis > dim_.size()) { - ERROR("Texture axis too large"); - return 0; - } - return dim_[_axis]; -} - -bool Texture::Bind(ShaderProgram *_shaderProgram, std::string _uniformName, - unsigned int _texUnit) { - WARNING("Call to default implementation of Texture::Bind"); - return true; -} - -unsigned int Texture::Handle() const { - if (handle_ == 0) { - WARNING("Texture handle is zero"); - } - return handle_; -} - -Texture::~Texture() { - glDeleteTextures(1, &handle_); -} - - diff --git a/src/flare/Texture.h b/src/flare/Texture.h deleted file mode 100644 index 96170f9394..0000000000 --- a/src/flare/Texture.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef TEXTURE_H -#define TEXTURE_H - -/* -Author: Victor Sand (victor.sand@gmail.com) -Wrapper for OpenGL 1D, 2D and 3D textures -*/ - -#include -#include - -namespace osp { - -class ShaderProgram; - -class Texture { -public: - // Get x, y or z dimensions (0, 1, 2 etc) if they exist - unsigned int Dim(unsigned int _axis) const; - // Return handle for OpenGL use - unsigned int Handle() const; - // Initialize, subclasses have to implement - virtual bool Init(float * data) = 0; - // Bind to a ShaderProgram - virtual bool Bind(ShaderProgram * _shaderProgram, - std::string _uniformName, - unsigned int _texUnit); - virtual ~Texture(); - -protected: - Texture(std::vector _dim); - std::vector dim_; - unsigned int handle_; - bool initialized_; -}; - -} - -#endif diff --git a/src/flare/Texture1D.cpp b/src/flare/Texture1D.cpp deleted file mode 100644 index 7760cbed80..0000000000 --- a/src/flare/Texture1D.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Author: Victor Sand (victor.sand@gmail.com) - * - */ -#include -#include -#include -#include - -using namespace osp; - -Texture1D::Texture1D(std::vector _dim) : Texture(_dim) {} - -Texture1D * Texture1D::New(std::vector _dim) { - if (_dim.size() != 1) { - ERROR("Texture1D needs dimension vector of size 1, defaulting to width 1"); - _dim = std::vector(1,1); - } - return new Texture1D(_dim); -} - -bool Texture1D::Init(float *_data) { - INFO("Initializing Texture1D"); - - if (initialized_) { - WARNING("Texture1D already initialized, doing nothing"); - return true; - } - - //glEnable(GL_TEXTURE_1D); - glGenTextures(1, &handle_); - glBindTexture(GL_TEXTURE_1D, handle_); - glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_REPEAT); - glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_BASE_LEVEL, 0); - glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAX_LEVEL, 0); - glTexImage1D(GL_TEXTURE_1D, - 0, // level - GL_RGBA, // internal format - dim_[0], // width, - 0, // border - GL_RGBA, // format - GL_FLOAT, // type - _data); - glBindTexture(GL_TEXTURE_1D, 0); - initialized_ = true; - return CheckGLError("Texture1D::Init()") == GL_NO_ERROR; -} - -bool Texture1D::Bind(ShaderProgram * _shaderProgram, - std::string _uniformName, - unsigned int _texUnit) const { - // TODO unused - return false; -} diff --git a/src/flare/Texture1D.h b/src/flare/Texture1D.h deleted file mode 100644 index c36e6d6933..0000000000 --- a/src/flare/Texture1D.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef TEXTURE1D_H -#define TEXTURE1D_H - -/* -Author: Victor Sand (victor.sand@gmail.com -Wrapper for OpenGL 1D Texture -*/ - -#include -#include - -namespace osp { - -class ShaderProgram; - -class Texture1D : public Texture { -public: - static Texture1D * New(std::vector _dim); - virtual bool Init(float *_data); - virtual bool Bind(ShaderProgram *_shaderProgram, - std::string _uniformName, - unsigned int _texUnit) const; -private: - Texture1D(std::vector dim_); -}; - -} - -#endif - diff --git a/src/flare/Texture2D.cpp b/src/flare/Texture2D.cpp deleted file mode 100644 index 59af50a704..0000000000 --- a/src/flare/Texture2D.cpp +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Author: Victor Sand (victor.sand@gmail.com) - * - */ -#include -#include -#include -#include - -using namespace osp; - -Texture2D::Texture2D(std::vector _dim) : Texture(_dim) { -} - -Texture2D * Texture2D::New(std::vector _dim) { - if (_dim.size() != 2) { - ERROR("Texture2D need a dimension vector of size 2, defaulting to 1x1"); - _dim = std::vector(2, 1); - } - INFO("Creating Texture2D with dimensions: " << _dim[0] << " " << _dim[1]); - return new Texture2D(_dim); -} - -bool Texture2D::Init(float *_data) { - INFO("Initializing Texture2D"); - - if (initialized_) { - WARNING("Texture2D already initialized, doing nothing"); - return true; - } - -// glEnable(GL_TEXTURE_2D); - glGenTextures(1, &handle_); - glBindTexture(GL_TEXTURE_2D, handle_); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); - glTexImage2D(GL_TEXTURE_2D, // target - 0, // level - GL_RGBA, // internal format - dim_[0], // width - dim_[1], // height - 0, // border - GL_RGBA, // format - GL_FLOAT, // type - _data); // data - - glBindTexture(GL_TEXTURE_2D, 0); - initialized_ = true; - return CheckGLError("Texture2D::Init()") == GL_NO_ERROR; -} - -bool Texture2D::Bind(ShaderProgram * _shaderProgram, - std::string _uniformName, - unsigned int _texUnit) const { - if (!initialized_) { - ERROR("Can't bind texture, not initialized"); - return false; - } - - glGetError(); - - glUseProgram(_shaderProgram->Handle()); - glActiveTexture(GL_TEXTURE0 + _texUnit); - //glEnable(GL_TEXTURE_2D); - - int location = glGetUniformLocation(_shaderProgram->Handle(), - _uniformName.c_str()); - if (location == -1) { - ERROR("Uniform " << _uniformName << " could not be found"); - glUseProgram(0); - return false; - } - - glUniform1i(location, _texUnit); - glBindTexture(GL_TEXTURE_2D, handle_); - glUseProgram(0); - return (CheckGLError("Texture2D::Bind() " + _uniformName) == GL_NO_ERROR); - -} - - - - - diff --git a/src/flare/Texture2D.h b/src/flare/Texture2D.h deleted file mode 100644 index 4523b85903..0000000000 --- a/src/flare/Texture2D.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef TEXTURE2D_H_ -#define TEXTURE2D_H_ - -/* -Author: Victor Sand (victor.sand@gmail.com) -Wrapper for OpenGL 2D Texture -*/ - -#include -#include - -namespace osp { - -class ShaderProgram; - -class Texture2D : public Texture { -public: - static Texture2D * New(std::vector _dim); - virtual bool Init(float *_data = 0); - virtual bool Bind(ShaderProgram * _shaderProgram, - std::string _uniformName, - unsigned int _texUnit) const; -private: - Texture2D(std::vector _dim); -}; - -} - -#endif diff --git a/src/flare/Texture3D.cpp b/src/flare/Texture3D.cpp deleted file mode 100644 index 7c57b5d0f6..0000000000 --- a/src/flare/Texture3D.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Author: Victor Sand (victor.sand@gmail.com) - * - */ -#include -#include -#include - -using namespace osp; - -Texture3D::Texture3D(std::vector _dim) : Texture(_dim) {} - -Texture3D * Texture3D::New(std::vector _dim) { - if (_dim.size() != 3) { - ERROR("Texture3D needs a dimension vector of size 3, defaulting to 1x1x1"); - _dim = std::vector(3, 1); - } - return new Texture3D(_dim); -} - -bool Texture3D::Init(float *_data) { - INFO("Initializing Texture3D"); - glGetError(); - - if (initialized_) { - WARNING("Texture3D already initialized, doing nothing"); - return true; - } - - unsigned int maxTextureSize; - glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE, (int*)&maxTextureSize); - if (dim_[0] > maxTextureSize || dim_[1] > maxTextureSize || - dim_[2] > maxTextureSize) { - ERROR("Dimension larger than texture size"); - ERROR("Max texture size: " << maxTextureSize); - ERROR("Dims: " << dim_[0] << " " << dim_[1] << " " << dim_[2]); - return false; - } - - //glEnable(GL_TEXTURE_3D); - if (CheckGLError("Texture3D::Init(): enabling 3D texture") != GL_NO_ERROR) { - return false; - } - glGenTextures(1, &handle_); - glBindTexture(GL_TEXTURE_3D, handle_); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_REPEAT); - glTexImage3D(GL_TEXTURE_3D, 0, GL_R32F, - dim_[0], dim_[1], dim_[2], - 0, GL_RED, GL_FLOAT, static_cast(_data)); - glBindTexture(GL_TEXTURE_3D, 0); - - initialized_ = true; - - return (CheckGLError("Texture3D::Init()") == GL_NO_ERROR); -} - - -bool Texture3D::UpdateSubRegion(unsigned int _xOffset, - unsigned int _yOffset, - unsigned int _zOffset, - unsigned int _xSize, - unsigned int _ySize, - unsigned int _zSize, - float *_data) { - - glGetError(); - glBindTexture(GL_TEXTURE_3D, handle_); - glTexSubImage3D(GL_TEXTURE_3D, - 0, - _xOffset, - _yOffset, - _zOffset, - _xSize, - _ySize, - _zSize, - GL_RED, - GL_FLOAT, - _data); - glBindTexture(GL_TEXTURE_3D, 0); - - return (CheckGLError("Texture3D::UpdateSubRegion") == GL_NO_ERROR); -} - diff --git a/src/flare/Texture3D.h b/src/flare/Texture3D.h deleted file mode 100644 index 468b022f88..0000000000 --- a/src/flare/Texture3D.h +++ /dev/null @@ -1,34 +0,0 @@ -#ifndef TEXTURE3D_H_ -#define TEXTURE3D_H_ - -/* - * Author: Victor Sand (victor.sand@gmail.com) - * - */ - -#include -#include - -namespace osp { - -class ShaderProgram; - -class Texture3D : public Texture { -public: - static Texture3D * New(std::vector _dim); - virtual bool Init(float *_data = 0); - bool UpdateSubRegion(unsigned int _xOffset, - unsigned int _yOffset, - unsigned int _zOffset, - unsigned int _xSize, - unsigned int _ySize, - unsigned int _zSize, - float *_data); -private: - Texture3D(std::vector _dim); -}; - -} - -#endif - diff --git a/src/flare/TextureAtlas.cpp b/src/flare/TextureAtlas.cpp deleted file mode 100644 index 6c6446ca30..0000000000 --- a/src/flare/TextureAtlas.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Author: Victor Sand (victor.sand@gmail.com) - * - */ - -#include -#include -#include - -using namespace osp; - -TextureAtlas::TextureAtlas() - : xBrickDim_(0), yBrickDim_(0), zBrickDim_(0), - xNumBricks_(0), yNumBricks_(0), zNumBricks_(0), - texture_(NULL) { -} - -TextureAtlas * TextureAtlas::New() { - return new TextureAtlas; -} - -TextureAtlas::~TextureAtlas() { - if (texture_ != NULL) { - delete texture_; - } -} - -void TextureAtlas::SetBrickDimensions(unsigned int _xBrickDim, - unsigned int _yBrickDim, - unsigned int _zBrickDim) { - xBrickDim_ = _xBrickDim; - yBrickDim_ = _yBrickDim; - zBrickDim_ = _zBrickDim; -} - -void TextureAtlas::SetNumBricks(unsigned int _xNumBricks, - unsigned int _yNumBricks, - unsigned int _zNumBricks) { - xNumBricks_ = _xNumBricks; - yNumBricks_ = _yNumBricks; - zNumBricks_ = _zNumBricks; -} - -bool TextureAtlas::Init() { - - INFO("Initializing TextureAtlas"); - - if (xBrickDim_ == 0 || yBrickDim_ == 0 || zBrickDim_ == 0) { - ERROR("TextureAtlas::Init() One or more dimensions are zero"); - return false; - } - - if (xNumBricks_ == 0 || yNumBricks_ == 0 || zNumBricks_ == 0) { - ERROR("TextureAtlas::Init() One or more number of bricks are zero"); - return false; - } - - unsigned int numBricksTotal = xNumBricks_*yNumBricks_*zNumBricks_; - - std::vector dims; - dims.push_back(xBrickDim_ * numBricksTotal); - dims.push_back(yBrickDim_); - dims.push_back(zBrickDim_); - - texture_ = Texture3D::New(dims); - if (!texture_->Init()) return false; - - return true; - -} - -bool TextureAtlas::UpdateBrick(unsigned int _brickIndex, real *_brickData) { - - // Bricks should be laid out along the x axis - unsigned int xOffset =_brickIndex * xBrickDim_; - unsigned int yOffset = 0; - unsigned int zOffset = 0; - unsigned int xSize = xBrickDim_; - unsigned int ySize = yBrickDim_; - unsigned int zSize = zBrickDim_; - if (!texture_->UpdateSubRegion(xOffset, yOffset, zOffset, - xSize, ySize, zSize, _brickData)) { - return false; - } - - return true; -} - - diff --git a/src/flare/TextureAtlas.h b/src/flare/TextureAtlas.h deleted file mode 100644 index 3b1d515005..0000000000 --- a/src/flare/TextureAtlas.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Author: Victor Sand - * - */ - -#ifndef TEXTUREATLAS_H_ -#define TEXTUREATLAS_H_ - -#define real float - -namespace osp { - -class Texture3D; - -class TextureAtlas { -public: - static TextureAtlas * New(); - ~TextureAtlas(); - - bool Init(); - void SetBrickDimensions(unsigned int _xBrickDim, - unsigned int _yBrickDim, - unsigned int _zBrickDim); - void SetNumBricks(unsigned int _xNumBricks, - unsigned int _yNumBricks, - unsigned int _zNumBricks); - - // Update a chosen brick with new data - // Assuming the brick data is ordered inorder for an individual brick - bool UpdateBrick(unsigned int _brickIndex, real *_brickData); - - Texture3D * TexturePtr() { return texture_; } - -private: - TextureAtlas(); - TextureAtlas(const TextureAtlas&); - unsigned int xBrickDim_; - unsigned int yBrickDim_; - unsigned int zBrickDim_; - unsigned int xNumBricks_; - unsigned int yNumBricks_; - unsigned int zNumBricks_; - Texture3D * texture_; -}; - -} - -#endif diff --git a/src/flare/TransferFunction.cpp b/src/flare/TransferFunction.cpp index 48fbb7c5e0..c03dedefb2 100644 --- a/src/flare/TransferFunction.cpp +++ b/src/flare/TransferFunction.cpp @@ -3,16 +3,15 @@ * */ -#include +#include #include #include #include #include -#include +#include #include #include #include -#include using namespace osp; @@ -21,7 +20,7 @@ TransferFunction * TransferFunction::New() { } TransferFunction::TransferFunction() : - texture_(NULL), + texture_(nullptr), floatData_(NULL), width_(0), lower_(0.f), @@ -203,8 +202,10 @@ bool TransferFunction::ConstructTexture() { std::vector dim(2); dim[0] = width_; dim[1] = 1; - texture_ = Texture2D::New(dim); - texture_->Init(&floatData_[0]); + texture_ = new ghoul::opengl::Texture(floatData_, glm::size3_t(width_,1,1),ghoul::opengl::Texture::Format::RGBA, GL_RGBA, GL_FLOAT); + texture_->uploadTexture(); + //texture_ = Texture2D::New(dim); + //texture_->Init(&floatData_[0]); generatedTexture_ = true; //delete[] values; diff --git a/src/flare/Utils.cpp b/src/flare/Utils.cpp index fa7a71ffae..cfa61a4e2e 100644 --- a/src/flare/Utils.cpp +++ b/src/flare/Utils.cpp @@ -2,8 +2,8 @@ * Author: Victor Sand (victor.sand@gmail.com) * */ -#include -#include +#include +#include unsigned int osp::CheckGLError(std::string _location) { unsigned int error = glGetError(); diff --git a/src/flare/flare.cpp b/src/flare/flare.cpp index aed421a0e9..d28f378013 100644 --- a/src/flare/flare.cpp +++ b/src/flare/flare.cpp @@ -22,17 +22,16 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include +#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include + +#include +#include +#include +#include +#include +#include #include @@ -41,6 +40,10 @@ #include #include +namespace { + std::string _loggerCat = "Flare"; +} + namespace openspace { using namespace osp; @@ -62,6 +65,11 @@ Flare::~Flare() { delete _animator; } +void exit_msg(std::string m) { + LDEBUG(m); + exit(1); +} + void Flare::render(const Camera *camera, const psc &thisPosition) { // Sync timestep _animator->SetCurrentTimestep(static_cast(_timeStep.getVal())); @@ -76,7 +84,6 @@ void Flare::render(const Camera *camera, const psc &thisPosition) { _raycaster->SetViewParams(_translateX.getVal(), _translateY.getVal(), _translateZ.getVal()); - // Render if (!_raycaster->Render(_elapsedTime.getVal())) exit(1); @@ -110,8 +117,11 @@ void Flare::setupNavigationParameters() { void Flare::initialize() { // Start with reading a config file - _config = Config::New(absPath("${BASE_PATH}/config/flareConfig.txt")); - if (!_config) exit(1); + _config = Config::New(absPath("${CONFIG}/flareConfig.txt")); + if (!_config) { + LDEBUG("!_Config"); + exit(1); + } setupNavigationParameters(); @@ -135,28 +145,91 @@ void Flare::initialize() { // Create TSP structure from file TSP *tsp = TSP::New(_config); - if (!tsp->ReadHeader()) exit(1); + if (!tsp->ReadHeader()) { + LDEBUG("!tsp->ReadHeader()"); + exit(1); + } // Read cache if it exists, calculate otherwise if (tsp->ReadCache()) { INFO("\nUsing cached TSP file"); } else { INFO("\nNo cached TSP file found"); - if (!tsp->Construct()) exit(1); + if (!tsp->Construct()) { + LDEBUG("!tsp->Construct()"); + exit(1); + } if (_config->CalculateError() == 0) { INFO("Not calculating errors"); } else { - if (!tsp->CalculateSpatialError()) exit(1); - if (!tsp->CalculateTemporalError()) exit(1); - if (!tsp->WriteCache()) exit(1); + if (!tsp->CalculateSpatialError()) { + LDEBUG("!tsp->CalculateSpatialError()"); + exit(1); + } + if (!tsp->CalculateTemporalError()) { + LDEBUG("!tsp->CalculateTemporalError()"); + exit(1); + } + if (!tsp->WriteCache()) { + LDEBUG("!tsp->WriteCache()"); + exit(1); + } } } // Create brick manager and init (has to be done after init OpenGL!) BrickManager *brickManager= BrickManager::New(_config); - if (!brickManager->ReadHeader()) exit(1); - if (!brickManager->InitAtlas()) exit(1); + if (!brickManager->ReadHeader()) { + LDEBUG("!brickManager->ReadHeader()"); + exit(1); + } + if (!brickManager->InitAtlas()) { + LDEBUG("!brickManager->InitAtlas()"); + exit(1); + } + + using ghoul::opengl::ShaderObject; + using ghoul::opengl::ProgramObject; + + ProgramObject* cubeShaderProgram = nullptr; + ShaderObject* cubeShaderProgram_vs = new ShaderObject(ShaderObject::ShaderType::ShaderTypeVertex, + _config->CubeShaderVertFilename(), + "cubeShaderProgram_vs" + ); + ShaderObject* cubeShaderProgram_fs = new ShaderObject(ShaderObject::ShaderType::ShaderTypeFragment, + _config->CubeShaderFragFilename(), + "cubeShaderProgram_fs" + ); + + cubeShaderProgram = new ProgramObject; + cubeShaderProgram->attachObject(cubeShaderProgram_vs); + cubeShaderProgram->attachObject(cubeShaderProgram_fs); + + if( ! cubeShaderProgram->compileShaderObjects()) + LDEBUG("Could not compile cubeShaderProgram"); + if( ! cubeShaderProgram->linkProgramObject()) + LDEBUG("Could not link cubeShaderProgram"); + + ProgramObject* quadShaderProgram = nullptr; + ShaderObject* quadShaderProgram_vs = new ShaderObject(ShaderObject::ShaderType::ShaderTypeVertex, + _config->QuadShaderVertFilename(), + "quadShaderProgram_vs" + ); + ShaderObject* quadShaderProgram_fs = new ShaderObject(ShaderObject::ShaderType::ShaderTypeFragment, + _config->QuadShaderFragFilename(), + "quadShaderProgram_fs" + ); + + quadShaderProgram = new ProgramObject; + quadShaderProgram->attachObject(quadShaderProgram_vs); + quadShaderProgram->attachObject(quadShaderProgram_fs); + + if( ! quadShaderProgram->compileShaderObjects()) + LDEBUG("Could not compile quadShaderProgram"); + if( ! quadShaderProgram->linkProgramObject()) + LDEBUG("Could not link quadShaderProgram"); // Create shaders for color cube and output textured quad + /* ShaderProgram *cubeShaderProgram = ShaderProgram::New(); cubeShaderProgram->CreateShader(ShaderProgram::VERTEX, _config->CubeShaderVertFilename()); @@ -170,25 +243,37 @@ void Flare::initialize() { quadShaderProgram->CreateShader(ShaderProgram::FRAGMENT, _config->QuadShaderFragFilename()); quadShaderProgram->CreateProgram(); + */ // Create two textures to hold the color cube std::vector dimensions(2); dimensions[0] = width; dimensions[1] = height; + ghoul::opengl::Texture* cubeFrontTex = new ghoul::opengl::Texture(glm::size3_t(width, height, 1), + ghoul::opengl::Texture::Format::RGBA, GL_RGBA, GL_FLOAT); + cubeFrontTex->uploadTexture(); + ghoul::opengl::Texture* cubeBackTex = new ghoul::opengl::Texture(glm::size3_t(width, height, 1), + ghoul::opengl::Texture::Format::RGBA, GL_RGBA, GL_FLOAT); + cubeBackTex->uploadTexture(); + /* Texture2D *cubeFrontTex = Texture2D::New(dimensions); Texture2D *cubeBackTex = Texture2D::New(dimensions); cubeFrontTex->Init(); cubeBackTex->Init(); - +*/ // Create an output texture to write to - Texture2D *quadTex = Texture2D::New(dimensions); - quadTex->Init(); + ghoul::opengl::Texture* quadTex = new ghoul::opengl::Texture(glm::size3_t(width, height, 1), + ghoul::opengl::Texture::Format::RGBA, GL_RGBA, GL_FLOAT); + quadTex->uploadTexture(); + + //Texture2D *quadTex = Texture2D::New(dimensions); + //quadTex->Init(); // Create transfer functions TransferFunction *transferFunction = TransferFunction::New(); transferFunction->SetInFilename(_config->TFFilename()); - if (!transferFunction->ReadFile()) exit(1); - if (!transferFunction->ConstructTexture()) exit(1); + if (!transferFunction->ReadFile()) exit_msg("!transferFunction->ReadFile()"); + if (!transferFunction->ConstructTexture()) exit_msg("!transferFunction->ConstructTexture()"); // Create animator @@ -203,15 +288,15 @@ void Flare::initialize() { _raycaster = Raycaster::New(_config); _raycaster->SetWinWidth(width); _raycaster->SetWinHeight(height); - if (!_raycaster->InitCube()) exit(1); - if (!_raycaster->InitQuad()) exit(1); + if (!_raycaster->InitCube()) exit_msg("!_raycaster->InitCube()"); + if (!_raycaster->InitQuad()) exit_msg("!_raycaster->InitQuad()"); _raycaster->SetBrickManager(brickManager); _raycaster->SetCubeFrontTexture(cubeFrontTex); _raycaster->SetCubeBackTexture(cubeBackTex); _raycaster->SetQuadTexture(quadTex); _raycaster->SetCubeShaderProgram(cubeShaderProgram); _raycaster->SetQuadShaderProgram(quadShaderProgram); - if (!_raycaster->InitFramebuffers()) exit(1); + if (!_raycaster->InitFramebuffers()) exit_msg("!_raycaster->InitFramebuffers()"); _raycaster->SetAnimator(_animator); _raycaster->AddTransferFunction(transferFunction); @@ -219,8 +304,8 @@ void Flare::initialize() { _raycaster->SetCLManager(clManager); _raycaster->SetTSP(tsp); - if (!_raycaster->InitCL()) exit(1); - if (!_raycaster->InitPipeline()) exit(1); + if (!_raycaster->InitCL()) exit_msg("!_raycaster->InitCL()"); + if (!_raycaster->InitPipeline()) exit_msg("!_raycaster->InitCL()"); } void Flare::keyboard(int key, int action) { @@ -298,8 +383,6 @@ void Flare::preSync() { _currentTime = static_cast(sgct::Engine::getTime()); _elapsedTime.setVal(_currentTime - _oldTime); - _timeStep.setVal(static_cast(_animator->CurrentTimestep())); - // Update automatic model transform if (!_animationPaused.getVal()) { _pitch.setVal(_pitch.getVal() + _config->PitchSpeed()); diff --git a/src/interaction/deviceidentifier.cpp b/src/interaction/deviceidentifier.cpp index dec0b14c79..408402129b 100644 --- a/src/interaction/deviceidentifier.cpp +++ b/src/interaction/deviceidentifier.cpp @@ -1,6 +1,6 @@ // open space includes -#include "deviceidentifier.h" +#include // sgct includes //#include "sgct.h" diff --git a/src/interaction/externalcontrol/externalconnectioncontroller.cpp b/src/interaction/externalcontrol/externalconnectioncontroller.cpp index 54ec5ebac3..4ea86f2fed 100644 --- a/src/interaction/externalcontrol/externalconnectioncontroller.cpp +++ b/src/interaction/externalcontrol/externalconnectioncontroller.cpp @@ -1,4 +1,4 @@ -#include "interaction/externalcontrol/externalconnectioncontroller.h" +#include namespace openspace { diff --git a/src/interaction/externalcontrol/externalcontrol.cpp b/src/interaction/externalcontrol/externalcontrol.cpp index c3cf9b93a2..81d0ec89b7 100644 --- a/src/interaction/externalcontrol/externalcontrol.cpp +++ b/src/interaction/externalcontrol/externalcontrol.cpp @@ -1,6 +1,6 @@ -#include "interaction/externalcontrol/externalcontrol.h" -#include "interaction/interactionhandler.h" -#include "openspaceengine.h" +#include +#include +#include #include namespace openspace { diff --git a/src/interaction/externalcontrol/randomexternalcontrol.cpp b/src/interaction/externalcontrol/randomexternalcontrol.cpp index feca3b9b7d..b15446fb24 100644 --- a/src/interaction/externalcontrol/randomexternalcontrol.cpp +++ b/src/interaction/externalcontrol/randomexternalcontrol.cpp @@ -1,4 +1,4 @@ -#include "interaction/externalcontrol/randomexternalcontrol.h" +#include #include #ifndef __WIN32__ diff --git a/src/interaction/interactionhandler.cpp b/src/interaction/interactionhandler.cpp index 2dbc178d1d..9290b56389 100644 --- a/src/interaction/interactionhandler.cpp +++ b/src/interaction/interactionhandler.cpp @@ -1,11 +1,11 @@ // open space includes -#include "interactionhandler.h" -#include "deviceidentifier.h" -#include "externalcontrol/randomexternalcontrol.h" -#include "externalcontrol/joystickexternalcontrol.h" -#include "query/query.h" -#include "openspaceengine.h" +#include +#include +#include +#include +#include +#include // std includes #include @@ -227,7 +227,7 @@ double InteractionHandler::getDt() { void InteractionHandler::keyboardCallback(int key, int action) { // TODO package in script - const double speed = 0.75; + const double speed = 2.75; const double dt = getDt(); if (key == 'S') { glm::vec3 euler(speed * dt, 0.0, 0.0); @@ -277,6 +277,7 @@ void InteractionHandler::keyboardCallback(int key, int action) { pss dist(speed * dt, 8.0); distance(dist); } + /* if (key == '1') { SceneGraphNode* node = getSceneGraphNode("sun"); @@ -301,7 +302,7 @@ void InteractionHandler::keyboardCallback(int key, int action) { getCamera()->setPosition(node->getWorldPosition() + psc(0.0, 0.0, 0.5, 8.0)); getCamera()->setCameraDirection(glm::vec3(0.0, 0.0, -1.0)); } - +*/ } void InteractionHandler::mouseButtonCallback(int key, int action) { diff --git a/src/main.cpp b/src/main.cpp index e8151dc0ac..ffe798f419 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -48,10 +48,26 @@ void mainDecodeFun(); void mainExternalControlCallback(const char * receivedChars, int size, int clientId); int main(int argc, char **argv) { - int newArgc; - char** newArgv; - openspace::OpenSpaceEngine::create(argc, argv, newArgc, newArgv); - _sgctEngine = new sgct::Engine(newArgc, newArgv); + + // create the OpenSpace engine and get arguments for the sgct engine + std::vector sgctArguments; + openspace::OpenSpaceEngine::create(argc, argv, sgctArguments); + + // create sgct engine c arguments + int newArgc = sgctArguments.size(); + char** newArgv = new char*[newArgc]; + for (int i = 0; i < newArgc; ++i) { + //newArgv[i] = new char[sgctArguments.at(i).length()]; + //std::strcpy(newArgv[i], sgctArguments.at(i).c_str()); + newArgv[i] = const_cast(sgctArguments.at(i).c_str()); + } + + _sgctEngine = new sgct::Engine(newArgc, newArgv); + + // deallocate sgct c arguments + for (int i = 0; i < newArgc; ++i) { + //delete newArgv[i]; + } delete[] newArgv; // Bind functions diff --git a/src/query/query.cpp b/src/query/query.cpp index d905337d17..0fa249df59 100644 --- a/src/query/query.cpp +++ b/src/query/query.cpp @@ -22,9 +22,9 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include "query/query.h" +#include -#include "openspaceengine.h" +#include namespace openspace { diff --git a/src/rendering/renderable.cpp b/src/rendering/renderable.cpp index 0819ce804a..fcf07c5e43 100644 --- a/src/rendering/renderable.cpp +++ b/src/rendering/renderable.cpp @@ -1,16 +1,12 @@ // open space includes -#include "renderable.h" +#include namespace openspace { + +Renderable::Renderable() {} -Renderable::Renderable() { - -} - -Renderable::Renderable(const pss &boundingSphere) { - boundingSphere_ = boundingSphere; -} +Renderable::Renderable(const ghoul::Dictionary& dictionary) {} Renderable::~Renderable() { diff --git a/src/rendering/renderablebody.cpp b/src/rendering/renderablebody.cpp index aa1afda9ed..c35c3cebae 100644 --- a/src/rendering/renderablebody.cpp +++ b/src/rendering/renderablebody.cpp @@ -1,9 +1,9 @@ // open space includes -#include "renderablebody.h" +#include namespace openspace { - +/* RenderableBody::RenderableBody(const pss &radius):Renderable(radius) { programObject_ = nullptr; texture_ = nullptr; @@ -70,5 +70,6 @@ void RenderableBody::render(const Camera *camera, const psc &thisPosition) { void RenderableBody::update() { } +*/ } // namespace openspace \ No newline at end of file diff --git a/src/rendering/renderableplanet.cpp b/src/rendering/renderableplanet.cpp index 31a33c98db..d9bff7dddc 100644 --- a/src/rendering/renderableplanet.cpp +++ b/src/rendering/renderableplanet.cpp @@ -1,23 +1,95 @@ // open space includes -#include "renderableplanet.h" +#include + +#include +#include + +#include +#include + +namespace { + std::string _loggerCat = "RenderablePlanet"; +} namespace openspace { -RenderablePlanet::RenderablePlanet(const pss &radius):Renderable(radius) { - programObject_ = nullptr; - texture_ = nullptr; - - // setup a unit sphere - planet_ = new Planet(radius,30); +RenderablePlanet::RenderablePlanet(const ghoul::Dictionary& dictionary): programObject_(nullptr), + _texturePath(""), + texture_(nullptr), + planet_(nullptr) +{ + double value = 1.0f, exponent= 0.0f; + double segments = 20.0; + + if(dictionary.hasKey("Geometry.Radius.1")) + dictionary.getValue("Geometry.Radius.1", value); + + if(dictionary.hasKey("Geometry.Radius.2")) + dictionary.getValue("Geometry.Radius.2", exponent); + + if(dictionary.hasKey("Geometry.Segments")) + dictionary.getValue("Geometry.Segments", segments); + + // create the power scaled scalar + pss planetSize(value, exponent); + setBoundingSphere(planetSize); + + // get path if available + std::string path = ""; + if(dictionary.hasKey("Path")) { + dictionary.getValue("Path", path); + path += "/"; + } + + if(dictionary.hasKey("Textures.Color")) { + std::string texturePath; + dictionary.getValue("Textures.Color", texturePath); + _texturePath = path + texturePath; + } + + planet_ = new PowerScaledSphere(pss(value, exponent), static_cast(segments)); } RenderablePlanet::~RenderablePlanet() { - delete planet_; + deinitialize(); } -void RenderablePlanet::setProgramObject(ghoul::opengl::ProgramObject *programObject = nullptr) { - assert(programObject) ; +bool RenderablePlanet::initialize() { + + bool completeSuccess = true; + if (programObject_ == nullptr) { + completeSuccess = OsEng.ref().configurationManager().getValue("pscShader", programObject_); + } + + if(_texturePath != "") { + texture_ = ghoul::opengl::loadTexture(_texturePath); + if (texture_) { + LDEBUG("Loaded texture from '" << _texturePath <<"'"); + texture_->uploadTexture(); + } else { + completeSuccess = false; + } + } + planet_->initialize(); + + return completeSuccess; +} + + + +bool RenderablePlanet::deinitialize() { + if(planet_) + delete planet_; + + if(texture_) + delete texture_; + + return true; +} + +void RenderablePlanet::setProgramObject(ghoul::opengl::ProgramObject *programObject) { + assert(programObject); programObject_ = programObject; } @@ -31,7 +103,7 @@ void RenderablePlanet::render(const Camera *camera, const psc &thisPosition) { // check so that the shader is set assert(programObject_); assert(texture_); - + // activate shader programObject_->activate(); @@ -39,9 +111,11 @@ void RenderablePlanet::render(const Camera *camera, const psc &thisPosition) { psc currentPosition = thisPosition; psc campos = camera->getPosition(); glm::mat4 camrot = camera->getViewRotationMatrix(); + pss scaling = camera->getScaling(); // scale the planet to appropriate size since the planet is a unit sphere glm::mat4 transform = glm::mat4(1); + transform = glm::rotate(transform, 4.1f*static_cast(sgct::Engine::instance()->getTime()), glm::vec3(0.0f, 1.0f, 0.0f)); // setup the data to the shader programObject_->setUniform("ViewProjection", camera->getViewProjectionMatrix()); @@ -49,9 +123,9 @@ void RenderablePlanet::render(const Camera *camera, const psc &thisPosition) { programObject_->setUniform("campos", campos.getVec4f()); programObject_->setUniform("objpos", currentPosition.getVec4f()); programObject_->setUniform("camrot", camrot); - programObject_->setUniform("scaling", camera->getScaling()); + programObject_->setUniform("scaling", scaling.getVec2f()); - //// if texture is availible, use it + // Bind texture glActiveTexture(GL_TEXTURE0); texture_->bind(); programObject_->setUniform("texture1", 0); diff --git a/src/rendering/renderengine.cpp b/src/rendering/renderengine.cpp index bd35f6c2ee..66f441b105 100644 --- a/src/rendering/renderengine.cpp +++ b/src/rendering/renderengine.cpp @@ -22,90 +22,82 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include "rendering/renderengine.h" +#include -#include "openspaceengine.h" -#include "scenegraph/scenegraph.h" -#include "scenegraph/scenegraphloader.h" -#include "util/camera.h" +#include +#include +#include #include "sgct.h" +#include + namespace { const std::string _loggerCat = "RenderEngine"; } namespace openspace { -RenderEngine::RenderEngine() - : _mainCamera(nullptr) - , _sceneGraph(nullptr) -{ -} +RenderEngine::RenderEngine() : _mainCamera(nullptr) , _sceneGraph(nullptr) {} RenderEngine::~RenderEngine() { delete _mainCamera; delete _sceneGraph; } -bool RenderEngine::initialize(const std::string& sceneGraph) { - // init camera and set position +bool RenderEngine::initialize() { + + // init camera and set temporary position and scaling _mainCamera = new Camera(); _mainCamera->setScaling(glm::vec2(1.0, -8.0)); - _mainCamera->setPosition(psc(0.0,0.0,1.499823,11.0)); // about the distance from the sun to our moon, will be overritten by the scenegraphloader - + _mainCamera->setPosition(psc(0.0,0.0,1.499823,11.0)); + // if master, setup interaction if (sgct::Engine::instance()->isMaster()) { OsEng.interactionHandler().setCamera(_mainCamera); - - // init interactionhandler and mouse interaction - //keyboardControl_ = new KeyboardExternalControl(RELATIVE_PATH"pyinput/keyboard.py"); - //mouseControl_ = new MouseExternalControl(RELATIVE_PATH"pyinput/mouse.py"); - //InteractionHandler::ref().addExternalControl(mouseControl_); // the interactionhandler is deallocating the object when it terminates - //InteractionHandler::ref().addExternalControl(keyboardControl_); // the interactionhandler is deallocating the object when it terminates - } - // init scenegraph + // initialize scenegraph _sceneGraph = new SceneGraph; - _sceneGraph->init(); - //_sceneGraph = loadSceneGraph(sceneGraph); + _sceneGraph->loadFromModulePath(absPath("${SCENEPATH}")); + _sceneGraph->initialize(); return true; } bool RenderEngine::initializeGL() { - // GL settings - glEnable (GL_DEPTH_TEST); - glEnable(GL_CULL_FACE); - glCullFace(GL_BACK); - - // set the close clip plane and the far clip plane to extreme values while in development - sgct::Engine::instance()->setNearAndFarClippingPlanes(0.1f,100.0f); - //sgct::Engine::setNearAndFarClippingPlanes(0.1f,10000.0f); - //sgct::Engine::getPtr()->setNearAndFarClippingPlanes(0.1f,10000.0f); - // calculating the maximum field of view for the camera, used to determine visibility of objects in the scene graph - if(sgct::Engine::instance()->getWindowPtr(0)->isUsingFisheyeRendering()) { +#define SGCT_WPTR sgct::Engine::instance()->getWindowPtr(0) +using sgct_core::Viewport; + + // TODO: Fix the power scaled coordinates in such a way that these values can be set + // to more realistic values + + // set the close clip plane and the far clip plane to extreme values while in development + //sgct::Engine::instance()->setNearAndFarClippingPlanes(0.1f,100.0f); + sgct::Engine::instance()->setNearAndFarClippingPlanes(0.00001f,100.0f); + + // calculating the maximum field of view for the camera, used to + // determine visibility of objects in the scene graph + if(SGCT_WPTR->isUsingFisheyeRendering()) { // fisheye mode, looking upwards to the "dome" glm::vec4 viewdir(0,1,0,0); // get the tilt and rotate the view - float tilt = sgct::Engine::instance()->getWindowPtr(0)->getFisheyeTilt(); + float tilt = SGCT_WPTR->getFisheyeTilt(); //tilt = tilt * 0.0174532925; // degrees to radians glm::mat4 tiltMatrix = glm::rotate(glm::mat4(1.0f), tilt, glm::vec3(1.0f,0.0f,0.0f)); viewdir = tiltMatrix * viewdir; // set the tilted view and the FOV _mainCamera->setCameraDirection(glm::vec3(viewdir[0],viewdir[1],viewdir[2])); - //mainCamera_->setMaxFov(sgct_core::SGCTSettings::Instance()->getFisheyeFOV()); - _mainCamera->setMaxFov(sgct::Engine::instance()->getWindowPtr(0)->getFisheyeFOV()); + _mainCamera->setMaxFov(SGCT_WPTR->getFisheyeFOV()); } else { - // get corner positions, calculating the forth to easily calculate center + // get corner positions, calculating the forth to easily calculate center glm::vec3 corners[4]; - corners[0] = sgct::Engine::instance()->getWindowPtr(0)->getCurrentViewport()->getViewPlaneCoords(sgct_core::Viewport::LowerLeft); - corners[1] = sgct::Engine::instance()->getWindowPtr(0)->getCurrentViewport()->getViewPlaneCoords(sgct_core::Viewport::UpperLeft); - corners[2] = sgct::Engine::instance()->getWindowPtr(0)->getCurrentViewport()->getViewPlaneCoords(sgct_core::Viewport::UpperRight); + corners[0] = SGCT_WPTR->getCurrentViewport()->getViewPlaneCoords(Viewport::LowerLeft); + corners[1] = SGCT_WPTR->getCurrentViewport()->getViewPlaneCoords(Viewport::UpperLeft); + corners[2] = SGCT_WPTR->getCurrentViewport()->getViewPlaneCoords(Viewport::UpperRight); corners[3] = glm::vec3(corners[2][0],corners[0][1],corners[2][2]); glm::vec3 center = (corners[0] + corners[1] + corners[2] + corners[3]) / 4.0f; @@ -133,7 +125,7 @@ bool RenderEngine::initializeGL() { } _mainCamera->setMaxFov(maxFov); } - + // successful init return true; } @@ -144,52 +136,73 @@ void RenderEngine::postSynchronizationPreDraw() { _mainCamera->compileViewRotationMatrix(); // update and evaluate the scene starting from the root node - //_sceneGraph->update(); - //_sceneGraph->evaluate(_mainCamera); + _sceneGraph->update(); + _mainCamera->setCameraDirection(glm::vec3(0,0,-1)); + _sceneGraph->evaluate(_mainCamera); } void RenderEngine::render() { - // preparing the camera can only be done in the render function - // since the SGCT get matrix functions is only valid in the render function - glm::mat4 projection = sgct::Engine::instance()->getActiveProjectionMatrix(); - glm::mat4 view = sgct::Engine::instance()->getActiveViewMatrix(); - const glm::vec3 eyePosition = sgct_core::ClusterManager::instance()->getUserPtr()->getPos(); - view = glm::translate(view, eyePosition); // make sure the eye is in the center - + // SGCT resets certian settings + glEnable (GL_DEPTH_TEST); + glEnable(GL_CULL_FACE); + // setup the camera for the current frame - //_mainCamera->setViewProjectionMatrix(projection*view); + const glm::vec3 eyePosition = sgct_core::ClusterManager::instance()->getUserPtr()->getPos(); + glm::mat4 view = glm::translate(glm::mat4(1.0), eyePosition); // make sure the eye is in the center + _mainCamera->setViewProjectionMatrix(sgct::Engine::instance()->getActiveModelViewProjectionMatrix()*view); // render the scene starting from the root node - //_sceneGraph->render(_mainCamera); - /* + _sceneGraph->render(_mainCamera); + + // Print some useful information on the master viewport if (sgct::Engine::instance()->isMaster()) { + +// Apple usually has retina screens +#ifdef __APPLE__ +#define FONT_SIZE 18 +#else +#define FONT_SIZE 10 +#endif + const glm::vec2 scaling = _mainCamera->getScaling(); const glm::vec3 viewdirection = _mainCamera->getViewDirection(); const psc position = _mainCamera->getPosition(); - Freetype::print(sgct_text::FontManager::instance()->getFont( "SGCTFont", 10 ), 10, 50, - "Position: (%.5f, %.5f, %.5f, %.5f)", position[0], position[1], position[2], position[3] - ); - Freetype::print(sgct_text::FontManager::instance()->getFont( "SGCTFont", 10 ), 10, 35, - "View direction: (%.3f, %.3f, %.3f)", viewdirection[0], viewdirection[1], viewdirection[2] - ); - Freetype::print(sgct_text::FontManager::instance()->getFont( "SGCTFont", 10 ), 10, 20, - "Scaling: (%.10f, %.2f)", scaling[0], scaling[1] - ); + const psc origin = OsEng.interactionHandler().getOrigin(); + const pss pssl = (position - origin).length(); + + Freetype::print(sgct_text::FontManager::instance()->getFont( "SGCTFont", FONT_SIZE ), + FONT_SIZE, + FONT_SIZE*10, + "Origin: (%.5f, %.5f, %.5f, %.5f)", + origin[0], origin[1], origin[2], origin[3] + ); + Freetype::print(sgct_text::FontManager::instance()->getFont( "SGCTFont", FONT_SIZE ), + FONT_SIZE, + FONT_SIZE*8, + "Camera position: (%.5f, %.5f, %.5f, %.5f)", + position[0], position[1], position[2], position[3] + ); + Freetype::print(sgct_text::FontManager::instance()->getFont( "SGCTFont", FONT_SIZE ), + FONT_SIZE, + FONT_SIZE*6, + "Distance to origin: (%.15f, %.2f)", + pssl[0], pssl[1] + ); + Freetype::print(sgct_text::FontManager::instance()->getFont( "SGCTFont", FONT_SIZE ), + FONT_SIZE, + FONT_SIZE*4, + "View direction: (%.3f, %.3f, %.3f)", + viewdirection[0], viewdirection[1], viewdirection[2] + ); + Freetype::print(sgct_text::FontManager::instance()->getFont( "SGCTFont", FONT_SIZE ), + FONT_SIZE, + FONT_SIZE*2, + "Scaling: (%.10f, %.2f)", + scaling[0], scaling[1] + ); - psc campos = _mainCamera->getPosition(); - psc origin = OsEng.interactionHandler().getOrigin(); - //psc campos = InteractionHandler::ref().getCamera()->getPosition(); - //psc origin = InteractionHandler::ref().getOrigin(); - psc relative = campos - origin; - pss pssl = relative.length(); - //mainCamera_->setScaling(glm::vec2(pssl[0], -pssl[1]+6)); - //mainCamera_->setScaling(glm::vec2(3000.0, -11.0f)); - Freetype::print(sgct_text::FontManager::instance()->getFont( "SGCTFont", 10 ), 10, 65, - "Distance to origin: (%.15f, %.2f)", pssl[0], pssl[1] - ); } - */ } SceneGraph* RenderEngine::sceneGraph() { @@ -199,92 +212,4 @@ SceneGraph* RenderEngine::sceneGraph() { } -/* -void RenderEngine::keyboardCallback(int key, int action) { - const double speed = 0.75; - if (key == 'S') { - double dt = InteractionHandler::ref().getDt(); - glm::vec3 euler(speed * dt, 0.0, 0.0); - glm::quat rot = glm::quat(euler); - InteractionHandler::ref().orbit(rot); - } - if (key == 'W') { - double dt = InteractionHandler::ref().getDt(); - glm::vec3 euler(-speed * dt, 0.0, 0.0); - glm::quat rot = glm::quat(euler); - InteractionHandler::ref().orbit(rot); - } - if (key == 'A') { - double dt = InteractionHandler::ref().getDt(); - glm::vec3 euler(0.0, -speed * dt, 0.0); - glm::quat rot = glm::quat(euler); - InteractionHandler::ref().orbit(rot); - } - if (key == 'D') { - double dt = InteractionHandler::ref().getDt(); - glm::vec3 euler(0.0, speed * dt, 0.0); - glm::quat rot = glm::quat(euler); - InteractionHandler::ref().orbit(rot); - } - if (key == 262) { - double dt = InteractionHandler::ref().getDt(); - glm::vec3 euler(0.0, speed * dt, 0.0); - glm::quat rot = glm::quat(euler); - InteractionHandler::ref().rotate(rot); - } - if (key == 263) { - double dt = InteractionHandler::ref().getDt(); - glm::vec3 euler(0.0, -speed * dt, 0.0); - glm::quat rot = glm::quat(euler); - InteractionHandler::ref().rotate(rot); - } - if (key == 264) { - double dt = InteractionHandler::ref().getDt(); - glm::vec3 euler(speed * dt, 0.0, 0.0); - glm::quat rot = glm::quat(euler); - InteractionHandler::ref().rotate(rot); - } - if (key == 265) { - double dt = InteractionHandler::ref().getDt(); - glm::vec3 euler(-speed * dt, 0.0, 0.0); - glm::quat rot = glm::quat(euler); - InteractionHandler::ref().rotate(rot); - } - if (key == 'R') { - double dt = InteractionHandler::ref().getDt(); - pss dist(3 * -speed * dt, 8.0); - InteractionHandler::ref().distance(dist); - } - if (key == 'F') { - double dt = InteractionHandler::ref().getDt(); - pss dist(3 * speed * dt, 8.0); - InteractionHandler::ref().distance(dist); - } - if (key == '1') { - SceneGraphNode* earth = sceneGraph_->root()->get("sun"); - - InteractionHandler::ref().setFocusNode(earth); - InteractionHandler::ref().getCamera()->setPosition(earth->getWorldPosition() + psc(0.0, 0.0, 0.5, 10.0)); - InteractionHandler::ref().getCamera()->setCameraDirection(glm::vec3(0.0, 0.0, -1.0)); - } - - if (key == '2') { - SceneGraphNode* earth = sceneGraph_->root()->get("earth"); - - InteractionHandler::ref().setFocusNode(earth); - InteractionHandler::ref().getCamera()->setPosition(earth->getWorldPosition() + psc(0.0, 0.0, 1.0, 8.0)); - InteractionHandler::ref().getCamera()->setCameraDirection(glm::vec3(0.0, 0.0, -1.0)); - } - - - if (key == '3') { - SceneGraphNode* earth = sceneGraph_->root()->get("moon"); - - InteractionHandler::ref().setFocusNode(earth); - InteractionHandler::ref().getCamera()->setPosition(earth->getWorldPosition() + psc(0.0, 0.0, 0.5, 8.0)); - InteractionHandler::ref().getCamera()->setCameraDirection(glm::vec3(0.0, 0.0, -1.0)); - } -} -*/ - } // namespace openspace diff --git a/src/rendering/volumeraycaster.cpp b/src/rendering/volumeraycaster.cpp index 9b32747b5e..9918c4bcd8 100644 --- a/src/rendering/volumeraycaster.cpp +++ b/src/rendering/volumeraycaster.cpp @@ -22,7 +22,7 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include +#include #include #include @@ -54,7 +54,7 @@ VolumeRaycaster::~VolumeRaycaster() {} // Initializes the data and setups the correct type of ray caster void VolumeRaycaster::initialize() { // ------ VOLUME READING ---------------- - std::string filename = absPath("${BASE_PATH}/openspace-data/skull.raw"); + std::string filename = absPath("${OPENSPACE_DATA}/skull.raw"); ghoul::RawVolumeReader::ReadHints hints; // TODO: Read hints from .dat file hints._dimensions = glm::ivec3(256, 256, 256); diff --git a/src/scenegraph/constantpositioninformation.cpp b/src/scenegraph/constantpositioninformation.cpp new file mode 100644 index 0000000000..6581ddbb3e --- /dev/null +++ b/src/scenegraph/constantpositioninformation.cpp @@ -0,0 +1,54 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +namespace openspace { + +ConstantPositionInformation::ConstantPositionInformation(const ghoul::Dictionary& dictionary) { + double x = 0.0, y = 0.0, z = 0.0, e = 0.0; + if (dictionary.hasKey("Position.1")) { + dictionary.getValue("Position.1", x); + dictionary.getValue("Position.2", y); + dictionary.getValue("Position.3", z); + dictionary.getValue("Position.4", e); + } + _position = psc(x, y, z, e); +} + +ConstantPositionInformation::~ConstantPositionInformation() {} + +bool ConstantPositionInformation::initialize() { + return true; +} + +const psc& ConstantPositionInformation::position() const { + return _position; +} + +void ConstantPositionInformation::update() { + +} + +} // namespace openspace \ No newline at end of file diff --git a/src/scenegraph/positioninformation.cpp b/src/scenegraph/positioninformation.cpp new file mode 100644 index 0000000000..768a8140bb --- /dev/null +++ b/src/scenegraph/positioninformation.cpp @@ -0,0 +1,33 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +namespace openspace { + +PositionInformation::PositionInformation() {} +PositionInformation::PositionInformation(const ghoul::Dictionary& dictionary) {} +PositionInformation::~PositionInformation() {} + +} // namespace openspace \ No newline at end of file diff --git a/src/scenegraph/scenegraph.cpp b/src/scenegraph/scenegraph.cpp index 69e45291d0..76f2fa4359 100644 --- a/src/scenegraph/scenegraph.cpp +++ b/src/scenegraph/scenegraph.cpp @@ -1,10 +1,33 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ // open space includes -#include "scenegraph/scenegraph.h" -#include "scenegraph/scenegraphloader.h" -#include "rendering/renderablebody.h" -#include "interaction/interactionhandler.h" -#include "util/spice.h" +#include +#include +#include +#include +#include // ghoul includes #include "ghoul/opengl/programobject.h" @@ -12,52 +35,266 @@ #include "ghoul/logging/consolelog.h" #include "ghoul/opengl/texturereader.h" #include "ghoul/opengl/texture.h" + #include +#include +#include +#include +#include + +#include +#include + +namespace { + std::string _loggerCat = "SceneGraph"; +} namespace openspace { - -SceneGraph::SceneGraph() { - root_ = nullptr; + +void printTree(SceneGraphNode* node, std::string pre = "") { + LDEBUGC("Tree", pre << node->nodeName()); + auto children = node->children(); + for(auto child: children) { + printTree(child, pre + " "); + } } + +SceneGraph::SceneGraph(): _focus("Root"), _position("Root"), _root(nullptr) {} SceneGraph::~SceneGraph() { - // deallocate the scene graph - if(root_) - delete root_; - - // deallocate shaders, iterate c++11 style - for (auto& shaderTuple: shaders_) { - - // the shader is in the maps second position - delete shaderTuple.second; - } - + deinitialize(); } -void SceneGraph::init() { - // logger string - std::string _loggerCat = "SceneGraph::init"; - - // SceneGraphLoader *loader = new SceneGraphLoader(&nodes_, &shaders_); - // root_ = loader->loadSceneGraph(absPath("${BASE_PATH}/modules")); - update(); - //pss bs = root_->calculateBoundingSphere(); +bool SceneGraph::initialize() { + LDEBUG("Initializing SceneGraph"); + + using ghoul::opengl::ShaderObject; + using ghoul::opengl::ProgramObject; + using ghoul::opengl::ShaderManager; + + ProgramObject* po = nullptr; + if ( OsEng.ref().configurationManager().hasKey("pscShader") && + OsEng.ref().configurationManager().getValue("pscShader", po)) { + LWARNING("pscShader already in ConfigurationManager, deleting."); + delete po; + po = nullptr; + } + + ShaderObject* powerscale_vs = new ShaderObject(ShaderObject::ShaderType::ShaderTypeVertex, + absPath("${SHADERS}/pscstandard_vs.glsl"), + "PS Vertex" + ); + ShaderObject* powerscale_fs = new ShaderObject(ShaderObject::ShaderType::ShaderTypeFragment, + absPath("${SHADERS}/pscstandard_fs.glsl"), + "PS Fragment" + ); + + po = new ProgramObject; + po->attachObject(powerscale_vs); + po->attachObject(powerscale_fs); + + if( ! po->compileShaderObjects()) + return false; + if( ! po->linkProgramObject()) + return false; + + OsEng.ref().configurationManager().setValue("pscShader", po); + + // Initialize all nodes + for(auto node: _nodes) { + bool success = node->initialize(); + if (success) { + LDEBUG(node->nodeName() << " initialized successfully!"); + } else { + LWARNING(node->nodeName() << " not initialized."); + } + } + + // update the position of all nodes + update(); + + // Calculate the bounding sphere for the scenegraph + _root->calculateBoundingSphere(); + + // set the camera position + auto focusIterator = _allNodes.find(_focus); + auto positionIterator = _allNodes.find(_position); + + if(focusIterator != _allNodes.end() && positionIterator != _allNodes.end()) { + LDEBUG("Camera position is '"<< _position <<"', camera focus is '" << _focus << "'"); + SceneGraphNode* focusNode = focusIterator->second; + SceneGraphNode* positionNode = positionIterator->second; + 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 + psc cameraPosition = positionNode->getPosition(); + cameraPosition += psc(0.0,0.0,1.0,2.0); + c->setPosition(cameraPosition); + c->setCameraDirection(glm::vec3(0,0,-1)); + c->setScaling(glm::vec2(1.0,0.0)); + + // Set the focus node for the interactionhandler + OsEng.interactionHandler().setFocusNode(focusNode); + } + + + return true; +} + +bool SceneGraph::deinitialize() { + + // deallocate the scene graph. Recursive deallocation will occur + if(_root) + delete _root; + _root = nullptr; + + _nodes.erase(_nodes.begin(), _nodes.end()); + _allNodes.erase(_allNodes.begin(), _allNodes.end()); + + _focus = ""; + _position = ""; + + return true; } void SceneGraph::update() { - for(int i = 0; i < nodes_.size(); ++i) { - nodes_[i]->update(); - } + for(auto node: _nodes) { + node->update(); + } } void SceneGraph::evaluate(Camera *camera) { - root_->evaluate(camera); + _root->evaluate(camera); } void SceneGraph::render(Camera *camera) { - root_->render(camera); + _root->render(camera); } +bool SceneGraph::loadFromModulePath(const std::string& path) { + + LDEBUG("Loading scenegraph nodes"); + if(_root != nullptr) { + LFATAL("Scenegraph already loaded"); + return false; + } + + std::string defaultScene = path + "/default.scene"; + if( ! FileSys.fileExists(defaultScene)) { + LFATAL("Could not find 'default.scene' in '" << path << "'"); + return false; + } + + ghoul::Dictionary dictionary; + + // initialize the root node + _root = new SceneGraphNode(ghoul::Dictionary()); + _root->setName("Root"); + _nodes.push_back(_root); + _allNodes.insert ( std::make_pair("Root", _root)); + + ghoul::lua::loadDictionary(defaultScene, dictionary); + ghoul::Dictionary moduleDictionary; + if(dictionary.getValue("Modules", moduleDictionary)) { + auto keys = moduleDictionary.keys(); + std::sort(keys.begin(), keys.end()); + for (auto key: keys) { + std::string moduleFolder; + if(moduleDictionary.getValue(key, moduleFolder)) { + loadModulesFromModulePath(path +"/"+moduleFolder); + } + } + } + + // TODO: Make it less hard-coded and more flexible when nodes are not found + ghoul::Dictionary cameraDictionary; + if(dictionary.getValue("Camera", cameraDictionary)) { + LDEBUG("Cameradictionary found"); + std::string focus; + std::string position; + + if(cameraDictionary.hasKey("Focus") && cameraDictionary.getValue("Focus", focus)) { + auto focusIterator = _allNodes.find(focus); + if (focusIterator != _allNodes.end()) { + _focus = focus; + LDEBUG("Setting camera focus to '"<< _focus << "'"); + } + } + if(cameraDictionary.hasKey("Position") && cameraDictionary.getValue("Position", position)) { + auto positionIterator = _allNodes.find(position); + if (positionIterator != _allNodes.end()) { + _position = position; + LDEBUG("Setting camera position to '"<< _position << "'"); + } + } + } + + return true; +} + +void SceneGraph::loadModulesFromModulePath(const std::string& modulePath) { + auto pos = modulePath.find_last_of("/"); + if (pos == modulePath.npos) { + LFATAL("Bad format for module path: " << modulePath); + return; + } + + std::string fullModule = modulePath + modulePath.substr(pos) + ".mod"; + LDEBUG("Loading modules from: " << fullModule); + + ghoul::Dictionary moduleDictionary; + ghoul::lua::loadDictionary(fullModule, moduleDictionary); + auto keys = moduleDictionary.keys(); + for (auto key: keys) { + ghoul::Dictionary singleModuleDictionary; + if(moduleDictionary.getValue(key, singleModuleDictionary)) { + std::string moduleName; + if (singleModuleDictionary.getValue("Name", moduleName)) { + std::string parentName; + if ( ! singleModuleDictionary.getValue("Parent", parentName)) { + LWARNING("Could not find 'Parent' key, using 'Root'."); + parentName = "Root"; + } + + auto parentIterator = _allNodes.find(parentName); + if (parentIterator == _allNodes.end()) { + LFATAL("Could not find parent named '"<< parentName << + "' for '" << moduleName << "'." << + " Check module definition order. Skipping module."); + continue; + } + + // allocate SceneGraphNode and initialize with Dictionary + singleModuleDictionary.setValue("Path", modulePath); + SceneGraphNode* node = nullptr; + node = new SceneGraphNode(singleModuleDictionary); + if(node != nullptr) { + // add to internal data structures + _allNodes.insert(std::make_pair(moduleName, node)); + _nodes.push_back(node); + + // set child and parent + SceneGraphNode* parentNode = parentIterator->second; + parentNode->addNode(node); + } + } + } + } + + // Print the tree + printTree(_root); +} + +void SceneGraph::printChildren() const { + _root->print(); +} + +SceneGraphNode* SceneGraph::root() const { + return _root; +} } // namespace openspace \ No newline at end of file diff --git a/src/scenegraph/scenegraph.h b/src/scenegraph/scenegraph.h deleted file mode 100644 index 8e5e8f34d8..0000000000 --- a/src/scenegraph/scenegraph.h +++ /dev/null @@ -1,46 +0,0 @@ -#ifndef SCENEGRAPH_H -#define SCENEGRAPH_H - -// open space includes -#include "scenegraph/scenegraphnode.h" - -// std includes -#include -#include - -// ghoul includes -#include "ghoul/opengl/programobject.h" - -namespace openspace { - -class SceneGraph { -public: - - // constructors & destructor - SceneGraph(); - ~SceneGraph(); - - void init(); - - void update(); - void evaluate(Camera *camera); - void render(Camera *camera); - - void printChildren() const { - root_->print(); - } - - SceneGraphNode* root() const { return root_; } - void setRoot(SceneGraphNode* root) { root_ = root; } - -private: - - SceneGraphNode *root_; - std::vector nodes_; - std::map shaders_; - -}; - -} // namespace openspace - -#endif \ No newline at end of file diff --git a/src/scenegraph/scenegraphloader.cpp b/src/scenegraph/scenegraphloader.cpp deleted file mode 100644 index fbe0e78777..0000000000 --- a/src/scenegraph/scenegraphloader.cpp +++ /dev/null @@ -1,439 +0,0 @@ - -#include "openspaceengine.h" -// open space includes -#include "scenegraph/scenegraphloader.h" -#include "rendering/renderablebody.h" -#include "rendering/renderableplanet.h" -#include "interaction/interactionhandler.h" -#include "util/spice.h" - -// ghoul includes -#include "ghoul/logging/logmanager.h" -#include "ghoul/logging/consolelog.h" -#include "ghoul/opengl/texturereader.h" -#include "ghoul/opengl/texture.h" - -// std includes -#include - -namespace openspace { -/* - -SceneGraph* loadSceneGraph(const std::string& sceneGraphPath) { - SceneGraph* result = new SceneGraph; - //result->setRo - - return result; -} - - - -SceneGraphLoader::SceneGraphLoader(std::vector *nodes, std::map *commonShaders) { - root_ = nullptr; - nodes_ = nodes; - commonShaders_ = commonShaders; -} - -SceneGraphLoader::~SceneGraphLoader() { -} - -SceneGraphNode* SceneGraphLoader::loadSceneGraph(const std::string &path) { - - assert(commonShaders_); - - std::string _loggerCat = "SceneGraphLoader::loadSceneGraph"; - - // initializes the scene graph - root_ = new SceneGraphNode(); - - // loading all common stuff - tinyxml2::XMLDocument commonXML; - std::string commonPath = path + "/common/common.xml"; - commonXML.LoadFile(commonPath.c_str()); - - // loading the shaders - tinyxml2::XMLElement* shaders = commonXML.FirstChildElement( "shaders" ); - if(shaders) { - tinyxml2::XMLElement* shader = shaders->FirstChildElement( "shader" ); - for(;shader; shader = shader->NextSiblingElement( "shader" )) { - if(shader->Attribute("identifier")) { - std::string identifier = shader->Attribute("identifier"); - ghoul::opengl::ProgramObject *programObject = nullptr; - if(getShader(&programObject,path + "/common/", shader )) - commonShaders_->insert( std::make_pair(identifier, programObject) ); - } - } - } - - tinyxml2::XMLDocument scenegraphXML; - std::string scenegraphPath = path + "/scenegraph.xml"; - scenegraphXML.LoadFile(scenegraphPath.c_str()); - - // loading the scenegraph - tinyxml2::XMLElement* root = scenegraphXML.FirstChildElement( "root" ); - if(root) { - tinyxml2::XMLElement* node = root->FirstChildElement( "node" ); - loadSceneGraphTree(node, root_, path); - } - - return root_; -} - -// ugly -void SceneGraphLoader::loadSceneGraphTree(tinyxml2::XMLElement* node, SceneGraphNode *current, const std::string &path) { - // ghoul logger - std::string _loggerCat = "SceneGraphLoader::loadSceneGraphTree"; - - for(;node; node = node->NextSiblingElement( "node" )) { - SceneGraphNode *thisNode = nullptr; - std::string name = ""; - if(node->Attribute("module")) { - name = node->Attribute("module"); - thisNode = loadSceneGraphNodeFromFile(name, current, path); - } else { - thisNode = loadSceneGraphNode(node, "", current, path); - } - - if(thisNode) { - tinyxml2::XMLElement* children = node->FirstChildElement( "node" ); - if(children) { - loadSceneGraphTree(children, thisNode, path); - } - nodes_->push_back(thisNode); - - // camera stuff - tinyxml2::XMLElement* camera = node->FirstChildElement( "camera" ); - if(camera && camera->Attribute("setting")) { - std::string setting = camera->Attribute("setting"); - if(setting == "focus") { - // HACK - OsEng.interactionHandler().setFocusNode(thisNode->parent()); - LINFO("Setting camera focus: " << name); - } else if(setting == "position") { - OsEng.interactionHandler().getCamera()->setPosition(thisNode->getWorldPosition()); - LINFO("Setting camera position: " << name); - } - } - - - } else { - LERROR("Could not load SceneGraphNode [ " << name << " ], ignoring all children!"); - } - - } -} - -SceneGraphNode * SceneGraphLoader::loadSceneGraphNodeFromFile(std::string name, SceneGraphNode *parent, const std::string &path) { - std::string _loggerCat = "SceneGraphLoader::loadSceneGraphNode"; - - // path and name - std::string nodePath = path + "/" + name + "/" + name + ".xml"; - tinyxml2::XMLDocument nodeXML; - nodeXML.LoadFile(nodePath.c_str()); - - return loadSceneGraphNode(nodeXML.FirstChildElement( "module" ), name, parent, path + "/" + name); -} - -SceneGraphNode * SceneGraphLoader::loadSceneGraphNode(tinyxml2::XMLElement *xmlnode, std::string name, SceneGraphNode *parent, const std::string &path) { - - assert(commonShaders_); - - std::string _loggerCat = "SceneGraphLoader::loadSceneGraphNode"; - - // the node - SceneGraphNode *thisNode = nullptr; - - // load the properties - tinyxml2::XMLElement* moduleElement = xmlnode; - if(moduleElement) { - - thisNode = new SceneGraphNode(); - - // load spice - getSpice(thisNode, parent, moduleElement->FirstChildElement( "spice" )); - - tinyxml2::XMLElement* renderableElement = moduleElement->FirstChildElement( "renderable" ); - if(renderableElement && renderableElement->Attribute("type")) { - std::string type = renderableElement->Attribute("type"); - if(type == "RenderableBody") { - - RenderableBody *renderable = nullptr; - - // load radius - pss radius; - - // the radii element takes priority when setting the radius - if( getRadii(&radius, renderableElement->FirstChildElement( "radii" )) || thisNode->getSpiceID() > 0) { - double radii[3]; - int n; - if(Spice::ref().getRadii(thisNode->getSpiceName(),radii,&n)) { - - // multiply with factor 1000, spice uses km as standard and Open Space uses m - radius = pss::CreatePSS(radii[0]*1000.0); - } else { - LERROR("Tried to use spice raddi but failed for: " << name); - delete thisNode; - return nullptr; - } - } else { - LERROR("Could not find radiiElement or spice id for: " << name << " " << thisNode->getSpiceID() ); - delete thisNode; - return nullptr; - } - - - LINFO("Adding renderable: "<< name); - // load texture and shader - ghoul::opengl::Texture *texture = nullptr; - ghoul::opengl::ProgramObject *program = nullptr; - - tinyxml2::XMLElement* textureElement = renderableElement->FirstChildElement( "texture" ); - if(textureElement) { - if( ! getTexture(&texture, path, textureElement->FirstChildElement( "file" ))) { - LERROR("Could not load texture " << name); - } - } else { - LERROR("Could not find texture for: " << name); - } - - // load shader - if( ! getShader(&program, path, renderableElement->FirstChildElement( "shader" ))) { - LERROR("Could not find shader for: " << name); - } - - if( ! texture || ! program) { - delete thisNode; - return nullptr; - } - - // create the renderable - renderable = new RenderableBody(radius); - renderable->setTexture(texture); - renderable->setProgramObject(program); - thisNode->setRenderable(renderable); - - } else if(type == "RenderablePlanet") { - - RenderablePlanet *renderable = nullptr; - - // load radius - pss radius; - - // the radii element takes priority when setting the radius - if( getRadii(&radius, renderableElement->FirstChildElement( "radii" )) || thisNode->getSpiceID() > 0) { - double radii[3]; - int n; - if(Spice::ref().getRadii(thisNode->getSpiceName(),radii,&n)) { - - // multiply with factor 1000, spice uses km as standard and Open Space uses m - radius = pss::CreatePSS(radii[0]*1000.0); - } else { - LERROR("Tried to use spice raddi but failed for: " << name); - delete thisNode; - return nullptr; - } - } else { - LERROR("Could not find radiiElement or spice id for: " << name << " " << thisNode->getSpiceID() ); - delete thisNode; - return nullptr; - } - - - LINFO("Adding renderable: "<< name); - // load texture and shader - ghoul::opengl::Texture *texture = nullptr; - ghoul::opengl::ProgramObject *program = nullptr; - - tinyxml2::XMLElement* textureElement = renderableElement->FirstChildElement( "texture" ); - if(textureElement) { - if( ! getTexture(&texture, path, textureElement->FirstChildElement( "file" ))) { - LERROR("Could not load texture " << name); - } - } else { - LERROR("Could not find texture for: " << name); - } - - // load shader - if( ! getShader(&program, path, renderableElement->FirstChildElement( "shader" ))) { - LERROR("Could not find shader for: " << name); - } - - if( ! texture || ! program) { - delete thisNode; - return nullptr; - } - - // create the renderable - renderable = new RenderablePlanet(radius); - renderable->setTexture(texture); - renderable->setProgramObject(program); - thisNode->setRenderable(renderable); - LINFO("Adding renderablePlanet"); - } - } - - // set identifier and add to parent - thisNode->setName(name); - parent->addNode(thisNode); - return thisNode; - - } else { - LERROR("Unable to open properties element"); - return nullptr; - } -} - - -bool SceneGraphLoader::getSpice(SceneGraphNode *node, SceneGraphNode *parent, tinyxml2::XMLElement *xmlnode) { - std::string _loggerCat = "SceneGraphLoader::getSpice"; - if(xmlnode && node) { - tinyxml2::XMLElement* identifierElement = xmlnode->FirstChildElement( "identifier" ); - if(identifierElement && identifierElement->Attribute("string")) { - std::string identifier = identifierElement->Attribute("string"); - - int spiceID; - int spiceIDFound; - Spice::ref().bod_NameToInt(identifierElement->Attribute("string"), &spiceID, &spiceIDFound); - if(spiceIDFound) { - - // The spice id exists, save the identifier - node->setSpiceName(identifier); - - int parentSpice = 0; // sun barycenter - if(parent) { - if( parent->getSpiceID() != 0) - parentSpice = parent->getSpiceID(); - } - node->setSpiceID(spiceID,parentSpice); - return true; - } else { - LERROR("Could not find spice ID "); - } - } else { - LERROR("Could not find spice identifier element in xml "); - } - } - return false; -} - -bool SceneGraphLoader::getRadii(pss *radii, tinyxml2::XMLElement *xmlnode) { - std::string _loggerCat = "SceneGraphLoader::getRadii"; - if(xmlnode ) { - double value = 0.0; - double power = 0.0; - if(xmlnode->Attribute("value")) { - value = xmlnode->DoubleAttribute("value"); - if(xmlnode->Attribute("power")) - power = xmlnode->DoubleAttribute("power"); - *radii = pss(value, power); - return true; - } - } - return false; -} - -bool SceneGraphLoader::getTexture(ghoul::opengl::Texture **texture, const std::string &path, tinyxml2::XMLElement *xmlnode) { - std::string _loggerCat = "SceneGraphLoader::getTexture"; - if(xmlnode && xmlnode->Attribute("path")) { - std::string texturePath = path + "/" + xmlnode->Attribute("path"); - *texture = ghoul::opengl::loadTexture(texturePath); - - // if textures where accessed, upload them to the graphics card. This check needs to be done to avoid crash. - if(texture) { - LINFO("Uploading tetxure: "<< texturePath); - (*texture)->uploadTexture(); - //ghoul::opengl::Texture *tmp = new ghoul::opengl::Texture(*texture); - //texture = tmp; - return true; - } else { - LERROR("Could not load texture: "<< texturePath); - } - } else { - LERROR("Could not find file element"); - } - return false; -} - -bool SceneGraphLoader::getShader(ghoul::opengl::ProgramObject **program, const std::string &path, tinyxml2::XMLElement *xmlnode) { - std::string _loggerCat = "SceneGraphLoader::getShader"; - if( ! xmlnode) - return false; - - // use a common shader - if(xmlnode->IntAttribute("common") && xmlnode->Attribute( "identifier" )) { - std::string identifier = xmlnode->Attribute( "identifier" ); - std::map::iterator it; - it = commonShaders_->find(identifier); - if(it != commonShaders_->end()) { - *program = it->second; - return true; - } - - LERROR("Could not find common shader: " << identifier); - return false; - - // load and return the shader - } else { - tinyxml2::XMLElement* glsl_vs = xmlnode->FirstChildElement( "vertex" ); - tinyxml2::XMLElement* glsl_fs = xmlnode->FirstChildElement( "fragment" ); - if(glsl_vs && glsl_fs) { - if(glsl_vs->Attribute("path") && glsl_fs->Attribute("path")) { - std::string vs_path = glsl_vs->Attribute("path"); - std::string fs_path = glsl_fs->Attribute("path"); - - vs_path = path + vs_path; - fs_path = path + fs_path; - ghoul::opengl::ProgramObject *programObject = new ghoul::opengl::ProgramObject(); - ghoul::opengl::ShaderObject *vs = new ghoul::opengl::ShaderObject(ghoul::opengl::ShaderObject::ShaderType::ShaderTypeVertex, vs_path); - ghoul::opengl::ShaderObject *fs = new ghoul::opengl::ShaderObject(ghoul::opengl::ShaderObject::ShaderType::ShaderTypeFragment, fs_path); - programObject->attachObject(vs); - programObject->attachObject(fs); - - // check for bindings - tinyxml2::XMLElement* bindings = xmlnode->FirstChildElement( "bindings" ); - if(bindings) { - - tinyxml2::XMLElement* attributes = bindings->FirstChildElement( "attribute" ); - for(;attributes; attributes = attributes->NextSiblingElement( "attribute" )) { - if(attributes->Attribute("name") && attributes->Attribute("position")) { - std::string name = attributes->Attribute("name"); - int position = attributes->IntAttribute("position"); - programObject->bindAttributeLocation(name,position); - } - } - tinyxml2::XMLElement* fragdata = bindings->FirstChildElement( "fragdata" ); - for(;fragdata; fragdata = fragdata->NextSiblingElement( "fragdata" )) { - if(fragdata->Attribute("name") && fragdata->Attribute("position")) { - std::string name = fragdata->Attribute("name"); - int position = fragdata->IntAttribute("position"); - programObject->bindFragDataLocation(name,position); - } - } - } - - if(programObject->compileShaderObjects()) { - if(programObject->linkProgramObject()) { - *program = programObject; - LINFO("Common shader successfully loaded!"); - return true; - } else { - LERROR("Common shader could not be linked!"); - } - } else { - LERROR("Common shader could not be compiled!"); - } - - if(programObject) - delete programObject; - - return false; - } - } - } - - LERROR("Could not load shader"); - return false; -} - */ - -} // namespace openspace \ No newline at end of file diff --git a/src/scenegraph/scenegraphloader.h b/src/scenegraph/scenegraphloader.h deleted file mode 100644 index f4117fb521..0000000000 --- a/src/scenegraph/scenegraphloader.h +++ /dev/null @@ -1,56 +0,0 @@ -#ifndef SCENEGRAPHLOADER_H -#define SCENEGRAPHLOADER_H - -// open space includes -#include "scenegraph/scenegraphnode.h" - -// std includes -#include -#include -#include - -// ghoul includes -#include "ghoul/opengl/programobject.h" -#include "ghoul/opengl/texture.h" - -// sgct includes -//#include "ext/tinyxml2.h" - -namespace openspace { - /* - -class SceneGraph; - -SceneGraph* loadSceneGraph(const std::string& sceneGraphPath); - -class SceneGraphLoader { -public: - - // constructors & destructor - SceneGraphLoader(std::vector *nodes, std::map *commonShaders); - ~SceneGraphLoader(); - - SceneGraphNode *loadSceneGraph(const std::string &path); - -private: - - SceneGraphNode *root_; - std::map *commonShaders_; - std::vector *nodes_; - - // private methods - void loadSceneGraphTree(tinyxml2::XMLElement* node, SceneGraphNode *current, const std::string &path); - SceneGraphNode * loadSceneGraphNodeFromFile(std::string name, SceneGraphNode *parent, const std::string &path); - SceneGraphNode * loadSceneGraphNode(tinyxml2::XMLElement *xmlnode, std::string name, SceneGraphNode *parent, const std::string &path); - - bool getSpice(SceneGraphNode *node,SceneGraphNode *parent, tinyxml2::XMLElement *xmlnode); - bool getRadii(pss *radii, tinyxml2::XMLElement *xmlnode); - bool getTexture(ghoul::opengl::Texture **texture, const std::string &path, tinyxml2::XMLElement *xmlnode); - bool getShader(ghoul::opengl::ProgramObject **program, const std::string &path, tinyxml2::XMLElement *xmlnode); - -}; - */ - -} // namespace openspace - -#endif \ No newline at end of file diff --git a/src/scenegraph/scenegraphnode.cpp b/src/scenegraph/scenegraphnode.cpp index 3af3cfba86..8643854621 100644 --- a/src/scenegraph/scenegraphnode.cpp +++ b/src/scenegraph/scenegraphnode.cpp @@ -1,125 +1,186 @@ - +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + // open space includes -#include "scenegraph/scenegraphnode.h" -#include "util/spice.h" +#include +#include // ghoul includes -#include "ghoul/logging/logmanager.h" -#include "ghoul/logging/consolelog.h" +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace { + std::string _loggerCat = "SceneGraphNode"; +} namespace openspace { -SceneGraphNode::SceneGraphNode() { - - nodeName_ = ""; - - // init pointers with nullptr - renderable_ = nullptr; - parent_ = nullptr; - boundingSphereVisible_ = false; - renderableVisible_ = false; - - // spice not used when spiceID_ is 0, 0 is the sun barycenter - spiceID_ = 0; - parentSpiceID_ = 0; +SceneGraphNode::SceneGraphNode(const ghoul::Dictionary& dictionary): + _parent(nullptr), _nodeName("Unnamed OpenSpace SceneGraphNode"), _position(nullptr), + _renderable(nullptr), _renderableVisible(false), _boundingSphereVisible(false) +{ + ghoul::Dictionary localDictionary = dictionary; + + // set the _nodeName if available + localDictionary.getValue("Name", _nodeName); + + std::string path = ""; + localDictionary.getValue("Path", path); + + if(localDictionary.hasKey("Renderable")) { + if(safeCreationWithDictionary(&_renderable, "Renderable", &localDictionary, path)) { + LDEBUG(_nodeName << ": Successful creation of renderable!"); + } else { + LDEBUG(_nodeName << ": Failed to create renderable!"); + } + } + if(localDictionary.hasKey("Position")) { + if(safeCreationWithDictionary(&_position, "Position", &localDictionary, path)) { + LDEBUG(_nodeName << ": Successful creation of position!"); + } else { + LDEBUG(_nodeName << ": Failed to create position!"); + } + } + + if (_position == nullptr) { + _position = new ConstantPositionInformation(ghoul::Dictionary()); + _position->initialize(); + } } SceneGraphNode::~SceneGraphNode() { - // logger string - std::string _loggerCat = "SceneGraphNode::~SceneGraphNode()"; - LDEBUG("Deallocating: " << nodeName_); + deinitialize(); +} +bool SceneGraphNode::initialize() { + if(_renderable != nullptr) + _renderable->initialize(); + + // deallocate position + if(_position != nullptr) + _position->initialize(); + return true; +} + + +bool SceneGraphNode::deinitialize() { + LDEBUG("Deinitialize: " << _nodeName); + // deallocate the renderable - if(renderable_) - delete renderable_; - + if(_renderable != nullptr) + delete _renderable; + + // deallocate position + if(_position != nullptr) + delete _position; + // deallocate the child nodes and delete them, iterate c++11 style - for( auto &child: children_) { + for( auto child: _children) delete child; - } - - // empty the vector - children_.erase (children_.begin(),children_.end()); + + // empty the children vector + _children.erase(_children.begin(), _children.end()); + + // reset variables + _parent = nullptr; + _renderable = nullptr; + _position = nullptr; + _nodeName = "Unnamed OpenSpace SceneGraphNode"; + _renderableVisible = false; + _boundingSphereVisible = false; + _boundingSphere = pss(0.0,0.0); + + return true; } // essential void SceneGraphNode::update() { - - if(spiceID_ > 0) { - double state[3]; - //double orientation[3][3]; - Spice::ref().spk_getPosition(spiceID_, parentSpiceID_, state); - - // multiply with factor 1000, spice uses km as standard and Open Space uses m - position_ = psc::CreatePSC(state[0]*1000.0,state[1]*1000.0,state[2]*1000.0); - - // update rotation - //if(Spice::ref().spk_getOrientation(spiceName_,orientation)) { - // printf("%s\n",spiceName_); - // printf("%.5f %.5f %.5f \n", orientation[0][0], orientation[0][1], orientation[0][2]); - // printf("%.5f %.5f %.5f \n", orientation[1][0], orientation[1][1], orientation[1][2]); - // printf("%.5f %.5f %.5f \n", orientation[2][0], orientation[2][1], orientation[2][2]); - //} - } - - if(renderable_) { - renderable_->update(); - } + _position->update(); } -void SceneGraphNode::evaluate(const Camera *camera, const psc & parentPosition) { +void SceneGraphNode::evaluate(const Camera *camera, const psc& parentPosition) { - const psc thisPosition = parentPosition + position_; + const psc thisPosition = parentPosition + _position->position(); const psc camPos = camera->getPosition(); const psc toCamera = thisPosition - camPos; - + // init as not visible - boundingSphereVisible_ = true; - renderableVisible_ = false; - + _boundingSphereVisible = false; + _renderableVisible = false; + // check if camera is outside the node boundingsphere - if(toCamera.length() > boundingSphere_) { + if(toCamera.length() > _boundingSphere) { // check if the boudningsphere is visible before avaluating children - if( ! sphereInsideFrustum(thisPosition, boundingSphere_, camera)) { + if( ! sphereInsideFrustum(thisPosition, _boundingSphere, camera)) { // the node is completely outside of the camera view, stop evaluating this node return; } - } - boundingSphereVisible_ = true; - // inside boudningsphere or parts of the sphere is visible, individual children needs to be evaluated + } + + // inside boudningsphere or parts of the sphere is visible, individual + // children needs to be evaluated + _boundingSphereVisible = true; // this node has an renderable - if(renderable_) { + if(_renderable) { // check if the renderable boundingsphere is visible - renderableVisible_ = sphereInsideFrustum(thisPosition, renderable_->getBoundingSphere(), camera); + _renderableVisible = sphereInsideFrustum(thisPosition, _renderable->getBoundingSphere(), camera); } // evaluate all the children, tail-recursive function(?) - for(auto &child: children_) { - child->evaluate(camera,thisPosition); + for(auto &child: _children) { + child->evaluate(camera,psc()); } - + } void SceneGraphNode::render(const Camera *camera, const psc & parentPosition) { - const psc thisPosition = parentPosition + position_; + const psc thisPosition = parentPosition + _position->position(); // check if camera is outside the node boundingsphere - if( ! boundingSphereVisible_) { + if( ! _boundingSphereVisible) { return; - } - if(renderableVisible_) { - if (nodeName_ == "earth") - nodeName_ = nodeName_; - renderable_->render(camera,thisPosition); + } + if(_renderableVisible) { + //LDEBUG("Render"); + _renderable->render(camera,thisPosition); } // evaluate all the children, tail-recursive function(?) - for(auto &child: children_) { + + for(auto &child: _children) { child->render(camera,thisPosition); } @@ -127,93 +188,84 @@ void SceneGraphNode::render(const Camera *camera, const psc & parentPosition) { // set & get void SceneGraphNode::addNode(SceneGraphNode *child) { - // add a child node and set this node to be the parent - child->setParent(this); - children_.push_back(child); + + child->setParent(this); + _children.push_back(child); } void SceneGraphNode::setName(const std::string &name) { - nodeName_ = name; + _nodeName = name; } void SceneGraphNode::setParent(SceneGraphNode *parent) { - parent_ = parent; -} - -void SceneGraphNode::setPosition(const psc &position) { - position_ = position; -} - -void SceneGraphNode::setSpiceID(const int spiceID, const int parentSpiceID) { - spiceID_ = spiceID; - parentSpiceID_ = parentSpiceID; - update(); -} - -void SceneGraphNode::setSpiceName(const std::string &name) { - spiceName_ = name; -} - -const int SceneGraphNode::getSpiceID() const { - return spiceID_; -} - -const std::string & SceneGraphNode::getSpiceName() { - return spiceName_; + _parent = parent; } const psc &SceneGraphNode::getPosition() const { - return position_; + return _position->position(); } psc SceneGraphNode::getWorldPosition() const { // recursive up the hierarchy if there are parents available - if(parent_) { - return position_ + parent_->getWorldPosition(); + if(_parent) { + return _position->position() + _parent->getWorldPosition(); } else { - return position_; + return _position->position(); } } + +std::string SceneGraphNode::nodeName() const { + return _nodeName; +} + +SceneGraphNode* SceneGraphNode::parent() const { + return _parent; +} +const std::vector& SceneGraphNode::children() const { + return _children; +} + // bounding sphere pss SceneGraphNode::calculateBoundingSphere() { // set the vounding sphere to 0.0 - boundingSphere_ = 0.0; + _boundingSphere = 0.0; - if(children_.size() > 0) { // node + if(_children.size() > 0) { // node pss maxChild; // loop though all children and find the one furthest away/with the largest bounding sphere - for(size_t i = 0; i < children_.size(); ++i) { + for(size_t i = 0; i < _children.size(); ++i) { // when positions is dynamix, change this part to fins the most distant position - pss child = children_.at(i)->getPosition().length() + children_.at(i)->calculateBoundingSphere(); + pss child = _children.at(i)->getPosition().length() + + _children.at(i)->calculateBoundingSphere(); if(child > maxChild) { maxChild = child; } } - boundingSphere_ += maxChild; + _boundingSphere += maxChild; } else { // leaf // if has a renderable, use that boundingsphere - if(renderable_) - boundingSphere_ += renderable_->getBoundingSphere(); + if(_renderable) + _boundingSphere += _renderable->getBoundingSphere(); } - return boundingSphere_; + return _boundingSphere; } // renderable void SceneGraphNode::setRenderable(Renderable *renderable) { - renderable_ = renderable; + _renderable = renderable; update(); } const Renderable * SceneGraphNode::getRenderable() const{ - return renderable_; + return _renderable; } // private helper methods @@ -228,13 +280,6 @@ bool SceneGraphNode::sphereInsideFrustum(const psc s_pos, const pss & s_rad, con // the vector to the object from the new position psc D = s_pos - U; - // check if outside the maximum angle - if (nodeName_ == "earth") { - //psc tmp = s_pos - camera->getPosition(); - - //LINFOC("", "Angle: " << psc_camdir.angle(D)); - //LINFOC("", "Pos: " << tmp.getVec4f()[0] << " " << tmp.getVec4f()[1] << " " << tmp.getVec4f()[2] << " " << tmp.getVec4f()[3]); - } const double a = psc_camdir.angle(D); if ( a < camera->getMaxFov()) { @@ -254,5 +299,24 @@ bool SceneGraphNode::sphereInsideFrustum(const psc s_pos, const pss & s_rad, con } +SceneGraphNode* SceneGraphNode::get(const std::string& name) { + if (_nodeName == name) + return this; + else + for (auto it : _children) { + SceneGraphNode* tmp = it->get(name); + if (tmp != nullptr) { + return tmp; + } + } + return nullptr; +} + +void SceneGraphNode::print() const { + std::cout << _nodeName << std::endl; + for (auto it : _children) { + it->print(); + } +} } // namespace openspace \ No newline at end of file diff --git a/src/scenegraph/scenegraphnode.h b/src/scenegraph/scenegraphnode.h deleted file mode 100644 index efeb8158ab..0000000000 --- a/src/scenegraph/scenegraphnode.h +++ /dev/null @@ -1,93 +0,0 @@ -#ifndef SCENEGRAPHNODE_H -#define SCENEGRAPHNODE_H - -// open space includes -#include "rendering/renderable.h" - -// std includes -#include -#include -#include - -namespace openspace { - -class SceneGraphNode { -public: - - // constructors & destructor - SceneGraphNode(); - ~SceneGraphNode(); - - // essential - void update(); - void evaluate(const Camera *camera, const psc &parentPosition = psc()); - void render(const Camera *camera, const psc &parentPosition = psc()); - - // set & get - void addNode(SceneGraphNode *child); - void setName(const std::string &name); - void setParent(SceneGraphNode *parent); - void setPosition(const psc &position); - void setSpiceID(const int spiceID, const int parentSpiceID); - void setSpiceName(const std::string &name); - const int getSpiceID() const; - const std::string & getSpiceName(); - const psc& getPosition() const; - psc getWorldPosition() const; - std::string nodeName() const { return nodeName_; } - - SceneGraphNode* parent() const { return parent_; } - const std::vector& children() const { return children_; } - - // bounding sphere - pss calculateBoundingSphere(); - - SceneGraphNode* get(const std::string& name) { - if (nodeName_ == name) - return this; - else - for (auto it : children_) - return it->get(name); - return nullptr; - } - - void print() const { - std::cout << nodeName_ << std::endl; - for (auto it : children_) { - it->print(); - } - } - - // renderable - void setRenderable(Renderable *renderable); - const Renderable * getRenderable() const; - -private: - - // essential - std::vector children_; - SceneGraphNode *parent_; - psc position_; - std::string nodeName_; - - // renderable - Renderable *renderable_; - bool renderableVisible_; - - // bounding sphere - bool boundingSphereVisible_; - pss boundingSphere_; - - // spice - std::string spiceName_; - int spiceID_; - int parentSpiceID_; - - // private helper methods - bool sphereInsideFrustum(const psc s_pos, const pss & s_rad, const Camera *camera); - -}; - -} // namespace openspace - -#endif \ No newline at end of file diff --git a/src/scenegraph/spicepositioninformation.cpp b/src/scenegraph/spicepositioninformation.cpp new file mode 100644 index 0000000000..bce3cea116 --- /dev/null +++ b/src/scenegraph/spicepositioninformation.cpp @@ -0,0 +1,69 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +namespace openspace { + +SpicePositionInformation::SpicePositionInformation(const ghoul::Dictionary& dictionary): _targetName(""), + _originName(""), + _target(0), + _origin(0), + _position() +{ + dictionary.getValue("Body", _targetName); + dictionary.getValue("Observer", _originName); +} +SpicePositionInformation::~SpicePositionInformation() {} + +bool SpicePositionInformation::initialize() { + + if (_targetName != "" && _originName != "") { + int bsuccess = 0; + int osuccess = 0; + Spice::ref().bod_NameToInt(_targetName, &_target, &bsuccess); + Spice::ref().bod_NameToInt(_originName, &_origin, &osuccess); + + if (bsuccess && osuccess) { + return true; + } + } + + return false; +} + +const psc& SpicePositionInformation::position() const { + return _position; +} + +void SpicePositionInformation::update() { + double state[3]; + + Spice::ref().spk_getPosition(_target, _origin, state); + _position = psc::CreatePSC(state[0], state[1], state[2]); +} + +} // namespace openspace \ No newline at end of file diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt new file mode 100644 index 0000000000..23d2ace4b7 --- /dev/null +++ b/src/tests/CMakeLists.txt @@ -0,0 +1,38 @@ +######################################################################################### +# # +# OpenSpace # +# # +# Copyright (c) 2014 # +# # +# Permission is hereby granted, free of charge, to any person obtaining a copy of this # +# software and associated documentation files (the "Software"), to deal in the Software # +# without restriction, including without limitation the rights to use, copy, modify, # +# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to # +# permit persons to whom the Software is furnished to do so, subject to the following # +# conditions: # +# # +# The above copyright notice and this permission notice shall be included in all copies # +# or substantial portions of the Software. # +# # +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # +# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A # +# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # +# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF # +# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE # +# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # +######################################################################################### + +option(OPENSPACE_HAVE_TESTS "Activate the OpenSpace unit tests" ON) +if (OPENSPACE_HAVE_TESTS) + add_definitions(-DOPENSPACE_HAVE_TESTS) + + include_directories("${GHOUL_ROOT_DIR}/ext/gtest/include") + include_directories("${GHOUL_ROOT_DIR}/include") + file(GLOB_RECURSE OPENSPACE_TEST_FILES ${HEADER_ROOT_DIR}/openspace/tests/*.inl) + + source_group(OpenSpaceSource FILES ${OPENSPACE_SOURCE} ${OPENSPACE_HEADER}) + + add_executable(OpenSpaceTest ${SOURCE_ROOT_DIR}/tests/main.cpp ${OPENSPACE_TEST_FILES} ${OPENSPACE_HEADER} ${OPENSPACE_SOURCE}) + target_link_libraries(OpenSpaceTest gtest ${DEPENDENT_LIBS}) + +endif (OPENSPACE_HAVE_TESTS) diff --git a/src/tests/ScenegraphTest/common/common.mod b/src/tests/ScenegraphTest/common/common.mod new file mode 100644 index 0000000000..908bdaf746 --- /dev/null +++ b/src/tests/ScenegraphTest/common/common.mod @@ -0,0 +1,11 @@ +{ + -- Solar System module + { + Name = "SolarSystem", + Parent = "Root", + Position = { + Type = "static", + Position = { 0, 0, 0, 0} + } + }, +} \ No newline at end of file diff --git a/src/tests/ScenegraphTest/default.scene b/src/tests/ScenegraphTest/default.scene new file mode 100644 index 0000000000..0839eb3f6c --- /dev/null +++ b/src/tests/ScenegraphTest/default.scene @@ -0,0 +1,12 @@ + + +{ + Camera = { + Focus = "Earth", + Position = "Earth" + }, + Modules = { + "common", + "earth" + } +} \ No newline at end of file diff --git a/src/tests/ScenegraphTest/earth/earth.mod b/src/tests/ScenegraphTest/earth/earth.mod new file mode 100644 index 0000000000..0b7fccf822 --- /dev/null +++ b/src/tests/ScenegraphTest/earth/earth.mod @@ -0,0 +1,83 @@ +{ + -- Earth barycenter module + { + Name = "EarthBarycenter", + Parent = "SolarSystem", + Static = "true", + Position = { + Type = "Kepler", + Inclination = 0.00041, + AscendingNode = 349.2, + Perihelion = 102.8517, + SemiMajorAxis = 1.00002, + DailyMotion = 0.9855796, + Eccentricity = 0.0166967, + MeanLongitude = 328.40353 + } + }, + + -- dummy earth module + --[[ + { + Name = "DummyEarth", + Parent = "Root", + Renderable = { + Type = "RenderablePlanet", + Geometry = { + Type = "SimpleSphere", + --Radius = { 1.0, 1 } -- not sure if correct; supposed 6371km in meters in pss + Radius = { 1.0, 1} -- not sure if correct; supposed 6371km in meters in pss + }, + Textures = { + Type = "simple", + Color = "textures/earth_nasa_lowres.png", + Depth = "textures/earth_depth.png" + }, + }, + Position = { + Type = "Static", + Position = { 0, 0, -1, 1} + } + }, + ]]-- + + -- Earth module + { + Name = "Earth", + Parent = "EarthBarycenter", + Renderable = { + Type = "RenderablePlanet", + Geometry = { + Type = "SimpleSphere", + --Radius = { 6.371, 6 }, + Radius = { 1.0, 1}, + Segments = 10 + }, + Textures = { + Type = "simple", + Color = "textures/earth_nasa_lowres.png", + Depth = "textures/earth_depth.png" + }, + Atmosphere = { + Type = "Nishita", -- for example, values missing etc etc + MieFactor = 1.0, + MieColor = {1.0, 1.0, 1.0} + } + }, + Position = { + Type = "Spice", + Body = "EARTH", + Reference = "ECLIPJ2000", + Observer = "EARTH BARYCENTER", + Kernels = { + "kernels/earth.bsp" + } + }, + Rotation = { + Type = "Spice", + Frame = "IAU_EARTH", + Reference = "ECLIPJ2000" + }, + GuiName = "/Solar/Planets/Earth" + } +} \ No newline at end of file diff --git a/src/tests/ScenegraphTest/earth/textures/earth_nasa_lowres.jpg b/src/tests/ScenegraphTest/earth/textures/earth_nasa_lowres.jpg new file mode 100644 index 0000000000..f888c06156 Binary files /dev/null and b/src/tests/ScenegraphTest/earth/textures/earth_nasa_lowres.jpg differ diff --git a/src/tests/ScenegraphTest/earth/textures/earth_nasa_lowres.png b/src/tests/ScenegraphTest/earth/textures/earth_nasa_lowres.png new file mode 100644 index 0000000000..4ab4d3cd4a Binary files /dev/null and b/src/tests/ScenegraphTest/earth/textures/earth_nasa_lowres.png differ diff --git a/src/tests/main.cpp b/src/tests/main.cpp new file mode 100644 index 0000000000..e75abc7a68 --- /dev/null +++ b/src/tests/main.cpp @@ -0,0 +1,83 @@ +/***************************************************************************************** + * * + * GHOUL * + * General Helpful Open Utility Library * + * * + * Copyright (c) 2012-2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include "gtest/gtest.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +using namespace ghoul::cmdparser; +using namespace ghoul::filesystem; +using namespace ghoul::logging; + +namespace { + std::string _loggerCat = "OpenSpaceTest"; +} + +int main(int argc, char** argv) { + LogManager::initialize(LogManager::LogLevel::Debug); + LogMgr.addLog(new ConsoleLog); + + FileSystem::initialize(); + std::string configurationFilePath = ""; + LDEBUG("Finding configuration"); + if( ! openspace::OpenSpaceEngine::findConfiguration(configurationFilePath)) { + LFATAL("Could not find OpenSpace configuration file!"); + assert(false); + } + + LDEBUG("registering base path"); + if( ! openspace::OpenSpaceEngine::registerBasePathFromConfigurationFile(configurationFilePath)) { + LFATAL("Could not register base path"); + assert(false); + } + + ghoul::Dictionary configuration; + ghoul::lua::loadDictionary(configurationFilePath, configuration); + if(configuration.hasKey("paths")) { + ghoul::Dictionary pathsDictionary; + if(configuration.getValue("paths", pathsDictionary)) { + openspace::OpenSpaceEngine::registerPathsFromDictionary(pathsDictionary); + } + } + + openspace::Time::init(); + openspace::Spice::init(); + openspace::Spice::ref().loadDefaultKernels(); + openspace::FactoryManager::initialize(); + + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/src/util/camera.cpp b/src/util/camera.cpp index c95b2b5180..8fa0a2976b 100644 --- a/src/util/camera.cpp +++ b/src/util/camera.cpp @@ -1,6 +1,6 @@ // open space includes -#include "camera.h" +#include // sgct includes #include "sgct.h" @@ -8,11 +8,9 @@ namespace openspace { Camera::Camera() { - //glm::vec3 EulerAngles(90, 45, 0); scaling_ = glm::vec2(1.0,0.0); glm::vec3 EulerAngles(0, 0, 0); viewRotation_ = glm::quat(EulerAngles); - //printf("Camera: [%f, %f, %f, %f]\n", viewRotation_[0], viewRotation_[1], viewRotation_[2], viewRotation_[3]); } Camera::~Camera() { @@ -20,7 +18,7 @@ Camera::~Camera() { } void Camera::setPosition(psc pos) { - position_ = pos; + position_ = pos; } const psc& Camera::getPosition() const { @@ -72,7 +70,6 @@ const glm::vec3 & Camera::getViewDirection() const { return viewDirection_; } - const float & Camera::getMaxFov() const { return maxFov_; } diff --git a/src/util/factorymanager.cpp b/src/util/factorymanager.cpp new file mode 100644 index 0000000000..bd708d7568 --- /dev/null +++ b/src/util/factorymanager.cpp @@ -0,0 +1,83 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include +#include + +namespace openspace { + +// Template specializations for the different factories +template<> +ghoul::TemplateFactory* FactoryManager::factoryByType() { + return &_renderableFactory; +} +template<> +ghoul::TemplateFactory* FactoryManager::factoryByType() { + return &_positionInformationFactory; +} + +FactoryManager* FactoryManager::_manager = nullptr; + +void FactoryManager::initialize() { + assert(_manager == nullptr); + if (_manager == nullptr) + _manager = new FactoryManager; + assert(_manager != nullptr); + + // Add Renderables + _manager->factoryByType()-> + registerClass("RenderablePlanet"); + + // Add PositionInformations + _manager->factoryByType()-> + registerClass("Static"); + _manager->factoryByType()-> + registerClass("Spice"); + +} + +void FactoryManager::deinitialize() { + assert(_manager != nullptr); + delete _manager; + _manager = nullptr; +} + +FactoryManager& FactoryManager::ref() { + assert(_manager != nullptr); + return *_manager; +} + +FactoryManager::FactoryManager() { + +} +FactoryManager::~FactoryManager() { + +} + +} // namespace openspace \ No newline at end of file diff --git a/src/util/geometry.cpp b/src/util/geometry.cpp index e6abbd9970..a4f3b8c5b5 100644 --- a/src/util/geometry.cpp +++ b/src/util/geometry.cpp @@ -9,7 +9,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI */ // open space includes -#include "util/geometry.h" +#include gl4::Geometry::Geometry() { diff --git a/src/util/planet.cpp b/src/util/planet.cpp index 328faae25e..725605091b 100644 --- a/src/util/planet.cpp +++ b/src/util/planet.cpp @@ -9,7 +9,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI */ // open space includes -#include "util/planet.h" +#include // sgct includes #include "sgct.h" diff --git a/src/util/powerscaledsphere.cpp b/src/util/powerscaledsphere.cpp new file mode 100644 index 0000000000..00558a8a57 --- /dev/null +++ b/src/util/powerscaledsphere.cpp @@ -0,0 +1,188 @@ +/** +Copyright (C) 2012-2014 Jonas Strandstedt + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +// open space includes +#include + +#include + +namespace { + std::string _loggerCat = "PowerScaledSphere"; +} + +namespace openspace +{ + + +PowerScaledSphere::PowerScaledSphere(const pss radius, int segments) +{ + + static_assert(sizeof(Vertex) == 64 , "The size of the Vertex needs to be 64 for performance"); + + _vBufferID = 0; + _iBufferID = 0; + _vaoID = 0; + _isize = 0; + _vsize = 0; + _varray = nullptr; + _iarray = nullptr; + _mode = GL_TRIANGLES; + + // calculate and allocate memory for number of vertices and incicies + _vsize = (segments +1) * (segments + 1); + _isize = 6*segments*segments; + _varray = new Vertex[_vsize]; + _iarray = new int[_isize]; + + // define PI + const float PI = 3.14159265f; + int nr = 0; + for (int i = 0; i <= segments; i++) + { + // define an extra vertex around the y-axis due to texture mapping + for (int j = 0; j <= segments; j++) + { + + float fi = static_cast(i); + float fj = static_cast(j); + float fsegments = static_cast(segments); + + float r = static_cast(radius[0]); + + // inclenation angle (north to south) + float theta = fi*PI/fsegments; // 0 -> PI + + // azimuth angle (east to west) + float phi = fj*PI*2.0f/fsegments; // 0 -> 2*PI + + float x = r*sin(phi)*sin(theta); // + float y = r*cos(theta); // up + float z = r*cos(phi)*sin(theta); // + + glm::vec3 normal = glm::vec3(x,y,z); + if (!(x == 0.f && y == 0.f && z == 0.f)) + normal = glm::normalize(normal); + + float t1 = fj/fsegments; + float t2 = fi/fsegments; + + _varray[nr].location[0] = x; + _varray[nr].location[1] = y; + _varray[nr].location[2] = z; + _varray[nr].location[3] = static_cast(radius[1]); + _varray[nr].normal[0] = normal[0]; + _varray[nr].normal[1] = normal[1]; + _varray[nr].normal[2] = normal[2]; + + _varray[nr].tex[0] = t1; + _varray[nr].tex[1] = t2; + //LDEBUG("T: (" << t1 << ", " << t2 << ")"); + + nr++; + + } + } + + nr = 0; + // define indicies for all triangles + for (int i = 1; i <= segments; ++i) + { + for (int j = 0; j < segments; ++j) + { + + int t = segments+1; + _iarray[nr] = (t) * (i-1) + j + 0; nr++; + _iarray[nr] = (t) * (i+0) + j + 0; nr++; + _iarray[nr] = (t) * (i+0) + j + 1; nr++; + + _iarray[nr] = (t) * (i-1) + j + 0; nr++; + _iarray[nr] = (t) * (i+0) + j + 1; nr++; + _iarray[nr] = (t) * (i-1) + j + 1; nr++; + } + } + + +} + +PowerScaledSphere::~PowerScaledSphere() { + if(_varray) + delete[] _varray; + + if(_iarray) + delete[] _iarray; + + if(_vBufferID != 0) + glDeleteBuffers(1, &_vBufferID); + + if(_iBufferID != 0) + glDeleteBuffers(1, &_iBufferID); + + if(_vaoID != 0) + glDeleteVertexArrays(1, &_vaoID); +} + +bool PowerScaledSphere::initialize() { + + bool completeSuccess = true; + + // Initialize and upload to graphics card + GLuint errorID; + glGenVertexArrays(1, &_vaoID); + + // First VAO setup + glBindVertexArray(_vaoID); + + glGenBuffers(1, &_vBufferID); + + glBindBuffer(GL_ARRAY_BUFFER, _vBufferID); + glBufferData(GL_ARRAY_BUFFER, _vsize*sizeof(Vertex), _varray, GL_STATIC_DRAW); + + glEnableVertexAttribArray(0); + glEnableVertexAttribArray(1); + glEnableVertexAttribArray(2); + glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), BUFFER_OFFSET( 0)); + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), BUFFER_OFFSET(16)); + glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), BUFFER_OFFSET(24)); + + glGenBuffers(1, &_iBufferID); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _iBufferID); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, _isize*sizeof(int), _iarray, GL_STATIC_DRAW); + + if(_vBufferID == 0) + { + LERROR("Vertex buffer not initialized"); + completeSuccess = false; + } + if(_iBufferID == 0) + { + LERROR("Index buffer not initialized"); + completeSuccess = false; + } + + glBindVertexArray(0); + + errorID = glGetError(); + if(errorID != GL_NO_ERROR) + { + LERROR("OpenGL error: " << glewGetErrorString(errorID)); + LERROR("Attempting to proceed anyway. Expect rendering errors or a crash."); + completeSuccess = false; + } + return completeSuccess; +} + +void PowerScaledSphere::render() { + glBindVertexArray(_vaoID); // select first VAO + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _iBufferID); + glDrawElements(_mode, _isize, GL_UNSIGNED_INT, BUFFER_OFFSET(0)); + glBindVertexArray(0); +} + +} diff --git a/src/util/psc.cpp b/src/util/psc.cpp index 57b95cd903..9c6e95ffdb 100644 --- a/src/util/psc.cpp +++ b/src/util/psc.cpp @@ -1,7 +1,7 @@ // open space includes -#include "util/psc.h" -#include "util/pss.h" +#include +#include // std includes #include @@ -240,6 +240,10 @@ const double psc::angle(const psc &rhs) const { bool psc::operator==(const psc &other) const { return vec_ == other.vec_; } + +bool psc::operator!=(const psc &other) const { + return vec_ != other.vec_; +} bool psc::operator<(const psc &other) const { double ds = this->vec_[3] - other.vec_[3]; @@ -279,5 +283,11 @@ bool psc::operator>=(const psc &other) const { return *this > other || *this == other; } + +std::ostream& operator<<(::std::ostream& os, const psc& rhs) { + os << "(" << rhs[0] << ", " << rhs[1] << ", " << rhs[2] << ", " << rhs[3] << ")"; + return os; +} + } // namespace openspace diff --git a/src/util/pss.cpp b/src/util/pss.cpp index c64018ca21..e5ccd58f4e 100644 --- a/src/util/pss.cpp +++ b/src/util/pss.cpp @@ -1,6 +1,6 @@ // open space includes -#include "util/pss.h" +#include // std includes #include @@ -204,7 +204,12 @@ bool pss::operator<(const pss &other) const { double ds = this->vec_[1] - other.vec_[1]; if(ds >= 0) { double upscaled = other.vec_[0]*pow(k,-ds); - return vec_[0] < upscaled; + return vec_[0] < upscaled; + /* + bool retur =(vec_[0] < upscaled); + std::printf("this: %f, upscaled: %f, this upscaled; @@ -271,5 +276,9 @@ bool pss::operator>=(const double &other) const { return *this > other || *this == other; } +std::ostream& operator<<(::std::ostream& os, const pss& rhs) { + os << "(" << rhs[0] << ", " << rhs[1] << ")"; + return os; +} } // namespace openspace diff --git a/src/util/sphere.cpp b/src/util/sphere.cpp index 9d7da8857c..940fc2044e 100644 --- a/src/util/sphere.cpp +++ b/src/util/sphere.cpp @@ -9,7 +9,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI */ // open space includes -#include "util/sphere.h" +#include gl4::Sphere::Sphere(float radius, int segments, bool tessellation) { diff --git a/src/util/spice.cpp b/src/util/spice.cpp index edffb5918d..3093e28998 100644 --- a/src/util/spice.cpp +++ b/src/util/spice.cpp @@ -1,9 +1,9 @@ // openspace stuff -#include "util/spice.h" -#include "util/time.h" -#include "util/psc.h" -#include "interaction/interactionhandler.h" +#include +#include +#include +#include // spice #include "SpiceUsr.h" @@ -68,7 +68,7 @@ void Spice::loadDefaultKernels() { assert(this_); // load - loadKernel(absPath("${OPENSPACE-DATA}/spice/de430_1850-2150.bsp")); + loadKernel(absPath("${OPENSPACE_DATA}/spice/de430_1850-2150.bsp")); //Summary for: de430_1850-2150.bsp //Bodies: MERCURY BARYCENTER (1) SATURN BARYCENTER (6) MERCURY (199) // VENUS BARYCENTER (2) URANUS BARYCENTER (7) VENUS (299) @@ -79,7 +79,7 @@ void Spice::loadDefaultKernels() { // ----------------------------- ----------------------------- // 1849 DEC 26 00:00:00.000 2150 JAN 22 00:00:00.000 - loadKernel(absPath("${OPENSPACE-DATA}/spice/pck00010.tpc")); + loadKernel(absPath("${OPENSPACE_DATA}/spice/pck00010.tpc")); } bool Spice::loadKernel(const std::string &path) { diff --git a/src/util/time.cpp b/src/util/time.cpp index 15dac045e4..d515affa5a 100644 --- a/src/util/time.cpp +++ b/src/util/time.cpp @@ -1,7 +1,7 @@ // open space includes -#include "util/time.h" -#include "interaction/interactionhandler.h" +#include +#include // std includes #include @@ -18,7 +18,7 @@ Time::Time() { time_ = 0.0; // load spice time kernel - furnsh_c (absPath("${OPENSPACE-DATA}/spice/naif0010.tls").c_str()); + furnsh_c (absPath("${OPENSPACE_DATA}/spice/naif0010.tls").c_str()); // convert UTC to ET str2et_c ( "2006 JAN 31 01:00", &time_ ); @@ -29,7 +29,7 @@ Time::~Time() { } void Time::init() { - assert( ! this_); + assert( this_ == nullptr); this_ = new Time(); } diff --git a/src/util/vbo.cpp b/src/util/vbo.cpp index 63fac01e94..604978dc1d 100644 --- a/src/util/vbo.cpp +++ b/src/util/vbo.cpp @@ -9,7 +9,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI */ // open space includes -#include "util/vbo.h" +#include // ghoul includes #include "ghoul/logging/logmanager.h" @@ -52,7 +52,7 @@ void gl4::VBO::init() // if arrays not set from sub-class initialize with a colored quad if(_vsize == 0 || _isize == 0 || _varray == NULL || _iarray == NULL) { - //LOG("VBO: Init color quad\n"); + LDEBUG("VBO: Init color quad"); _mode = GL_TRIANGLES; _vsize = 4; @@ -122,7 +122,7 @@ void gl4::VBO::init() } - GLuint errorID = glGetError(); + GLuint errorID; glGenVertexArrays(1, &_vaoID); // First VAO setup