Merge branch 'feature/scenegraphmodification' into feature/iSWA

This commit is contained in:
Sebastian Piwell
2016-04-08 10:23:44 -04:00
9 changed files with 933 additions and 756 deletions
+17 -15
View File
@@ -65,7 +65,7 @@ public:
* Load the scenegraph from the provided folder
*/
void scheduleLoadSceneFile(const std::string& sceneDescriptionFilePath);
void clearSceneGraph();
void clearSceneGraph();
void loadModule(const std::string& modulePath);
@@ -95,20 +95,22 @@ public:
*/
SceneGraphNode* sceneGraphNode(const std::string& name) const;
std::vector<SceneGraphNode*> allSceneGraphNodes();
std::vector<SceneGraphNode*> allSceneGraphNodes();
/**
* Returns the Lua library that contains all Lua functions available to change the
* scene graph. The functions contained are
* - openspace::luascriptfunctions::property_setValue
* - openspace::luascriptfunctions::property_getValue
* \return The Lua library that contains all Lua functions available to change the
* scene graph
*/
static scripting::ScriptEngine::LuaLibrary luaLibrary();
SceneGraph& sceneGraph();
/**
* Returns the Lua library that contains all Lua functions available to change the
* scene graph. The functions contained are
* - openspace::luascriptfunctions::property_setValue
* - openspace::luascriptfunctions::property_getValue
* \return The Lua library that contains all Lua functions available to change the
* scene graph
*/
static scripting::ScriptEngine::LuaLibrary luaLibrary();
private:
bool loadSceneInternal(const std::string& sceneDescriptionFilePath);
bool loadSceneInternal(const std::string& sceneDescriptionFilePath);
void writePropertyDocumentation(const std::string& filename, const std::string& type);
@@ -120,10 +122,10 @@ private:
//std::vector<SceneGraphNode*> _nodes;
//std::map<std::string, SceneGraphNode*> _allNodes;
std::string _sceneGraphToLoad;
std::string _sceneGraphToLoad;
std::mutex _programUpdateLock;
std::set<ghoul::opengl::ProgramObject*> _programsToUpdate;
std::mutex _programUpdateLock;
std::set<ghoul::opengl::ProgramObject*> _programsToUpdate;
std::vector<std::unique_ptr<ghoul::opengl::ProgramObject>> _programs;
typedef std::map<std::string, ghoul::Dictionary> NodeMap;
-3
View File
@@ -25,9 +25,6 @@
#ifndef __SCENEGRAPH_H__
#define __SCENEGRAPH_H__
#include <ghoul/misc/dictionary.h>
#include <unordered_map>
#include <vector>
namespace openspace {
@@ -198,6 +198,8 @@ void RenderablePlaneProjection::loadTexture() {
if (_texturePath != "") {
std::unique_ptr<ghoul::opengl::Texture> texture = ghoul::io::TextureReader::ref().loadTexture(absPath(_texturePath));
if (texture) {
if (texture->format() == ghoul::opengl::Texture::Format::Red)
texture->setSwizzleMask({ GL_RED, GL_RED, GL_RED, GL_ONE });
texture->uploadTexture();
// TODO: AnisotropicMipMap crashes on ATI cards ---abock
//texture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap);
@@ -29,6 +29,7 @@
#include <openspace/engine/configurationmanager.h>
#include <ghoul/io/texture/texturereader.h>
#include <ghoul/opengl/textureconversion.h>
//#include <ghoul/opengl/textureunit.h>
#include <ghoul/filesystem/filesystem.h>
#include <openspace/scene/scenegraphnode.h>
@@ -50,30 +51,30 @@
namespace {
const std::string _loggerCat = "RenderablePlanetProjection";
const std::string keyProjObserver = "Projection.Observer";
const std::string keyProjTarget = "Projection.Target";
const std::string keyProjAberration = "Projection.Aberration";
const std::string keyInstrument = "Instrument.Name";
const std::string keyInstrumentFovy = "Instrument.Fovy";
const std::string keyInstrumentAspect = "Instrument.Aspect";
const std::string keyInstrumentNear = "Instrument.Near";
const std::string keyInstrumentFar = "Instrument.Far";
const std::string keySequenceDir = "Projection.Sequence";
const std::string _loggerCat = "RenderablePlanetProjection";
const std::string keyProjObserver = "Projection.Observer";
const std::string keyProjTarget = "Projection.Target";
const std::string keyProjAberration = "Projection.Aberration";
const std::string keyInstrument = "Instrument.Name";
const std::string keyInstrumentFovy = "Instrument.Fovy";
const std::string keyInstrumentAspect = "Instrument.Aspect";
const std::string keyInstrumentNear = "Instrument.Near";
const std::string keyInstrumentFar = "Instrument.Far";
const std::string keySequenceDir = "Projection.Sequence";
const std::string keySequenceType = "Projection.SequenceType";
const std::string keyPotentialTargets = "PotentialTargets";
const std::string keyTranslation = "DataInputTranslation";
const std::string keyTranslation = "DataInputTranslation";
const std::string keyFrame = "Frame";
const std::string keyGeometry = "Geometry";
const std::string keyShading = "PerformShading";
const std::string keyBody = "Body";
const std::string _mainFrame = "GALACTIC";
const std::string keyFrame = "Frame";
const std::string keyGeometry = "Geometry";
const std::string keyShading = "PerformShading";
const std::string keyBody = "Body";
const std::string _mainFrame = "GALACTIC";
const std::string sequenceTypeImage = "image-sequence";
const std::string sequenceTypePlaybook = "playbook";
const std::string sequenceTypeHybrid = "hybrid";
const std::string sequenceTypeHybrid = "hybrid";
}
@@ -83,40 +84,40 @@ namespace openspace {
RenderablePlanetProjection::RenderablePlanetProjection(const ghoul::Dictionary& dictionary)
: Renderable(dictionary)
, _colorTexturePath("planetTexture", "RGB Texture")
, _projectionTexturePath("projectionTexture", "RGB Texture")
, _colorTexturePath("planetTexture", "RGB Texture")
, _projectionTexturePath("projectionTexture", "RGB Texture")
, _rotation("rotation", "Rotation", 0, 0, 360)
, _fadeProjection("fadeProjections", "Image Fading Factor", 0.f, 0.f, 1.f)
, _fadeProjection("fadeProjections", "Image Fading Factor", 0.f, 0.f, 1.f)
, _performProjection("performProjection", "Perform Projections", true)
, _clearAllProjections("clearAllProjections", "Clear Projections", false)
, _clearAllProjections("clearAllProjections", "Clear Projections", false)
, _programObject(nullptr)
, _fboProgramObject(nullptr)
, _fboProgramObject(nullptr)
, _texture(nullptr)
, _textureOriginal(nullptr)
, _textureOriginal(nullptr)
, _textureProj(nullptr)
, _textureWhiteSquare(nullptr)
, _textureWhiteSquare(nullptr)
, _geometry(nullptr)
, _capture(false)
, _clearingImage(absPath("${OPENSPACE_DATA}/scene/common/textures/clear.png"))
, _capture(false)
, _clearingImage(absPath("${OPENSPACE_DATA}/scene/common/textures/clear.png"))
{
std::string name;
bool success = dictionary.getValue(SceneGraphNode::KeyName, name);
ghoul_assert(success, "");
std::string name;
bool success = dictionary.getValue(SceneGraphNode::KeyName, name);
ghoul_assert(success, "");
_defaultProjImage = absPath("textures/defaultProj.png");
_defaultProjImage = absPath("textures/defaultProj.png");
ghoul::Dictionary geometryDictionary;
success = dictionary.getValue(
keyGeometry, geometryDictionary);
if (success) {
geometryDictionary.setValue(SceneGraphNode::KeyName, name);
_geometry = planetgeometryprojection::PlanetGeometryProjection::createFromDictionary(geometryDictionary);
}
keyGeometry, geometryDictionary);
if (success) {
geometryDictionary.setValue(SceneGraphNode::KeyName, name);
_geometry = planetgeometryprojection::PlanetGeometryProjection::createFromDictionary(geometryDictionary);
}
dictionary.getValue(keyFrame, _frame);
dictionary.getValue(keyBody, _target);
if (_target != "")
setBody(_target);
dictionary.getValue(keyFrame, _frame);
dictionary.getValue(keyBody, _target);
if (_target != "")
setBody(_target);
bool b1 = dictionary.getValue(keyInstrument, _instrumentID);
bool b2 = dictionary.getValue(keyProjObserver, _projectorID);
@@ -153,81 +154,81 @@ RenderablePlanetProjection::RenderablePlanetProjection(const ghoul::Dictionary&
// TODO: textures need to be replaced by a good system similar to the geometry as soon
// as the requirements are fixed (ab)
std::string texturePath = "";
success = dictionary.getValue("Textures.Color", texturePath);
if (success){
_colorTexturePath = absPath(texturePath);
}
success = dictionary.getValue("Textures.Project", texturePath);
if (success){
_projectionTexturePath = absPath(texturePath);
}
addPropertySubOwner(_geometry);
addProperty(_rotation);
addProperty(_fadeProjection);
addProperty(_performProjection);
addProperty(_clearAllProjections);
success = dictionary.getValue("Textures.Color", texturePath);
if (success){
_colorTexturePath = absPath(texturePath);
}
success = dictionary.getValue("Textures.Project", texturePath);
if (success){
_projectionTexturePath = absPath(texturePath);
}
addPropertySubOwner(_geometry);
addProperty(_rotation);
addProperty(_fadeProjection);
addProperty(_performProjection);
addProperty(_clearAllProjections);
addProperty(_colorTexturePath);
_colorTexturePath.onChange(std::bind(&RenderablePlanetProjection::loadTexture, this));
addProperty(_projectionTexturePath);
_projectionTexturePath.onChange(std::bind(&RenderablePlanetProjection::loadProjectionTexture, this));
addProperty(_colorTexturePath);
_colorTexturePath.onChange(std::bind(&RenderablePlanetProjection::loadTexture, this));
addProperty(_projectionTexturePath);
_projectionTexturePath.onChange(std::bind(&RenderablePlanetProjection::loadProjectionTexture, this));
SequenceParser* parser;
SequenceParser* parser;
// std::string sequenceSource;
bool _foundSequence = dictionary.getValue(keySequenceDir, _sequenceSource);
if (_foundSequence) {
bool _foundSequence = dictionary.getValue(keySequenceDir, _sequenceSource);
if (_foundSequence) {
_sequenceSource = absPath(_sequenceSource);
_foundSequence = dictionary.getValue(keySequenceType, _sequenceType);
//Important: client must define translation-list in mod file IFF playbook
if (dictionary.hasKey(keyTranslation)){
ghoul::Dictionary translationDictionary;
//get translation dictionary
dictionary.getValue(keyTranslation, translationDictionary);
_foundSequence = dictionary.getValue(keySequenceType, _sequenceType);
//Important: client must define translation-list in mod file IFF playbook
if (dictionary.hasKey(keyTranslation)){
ghoul::Dictionary translationDictionary;
//get translation dictionary
dictionary.getValue(keyTranslation, translationDictionary);
if (_sequenceType == sequenceTypePlaybook) {
parser = new HongKangParser(name,
if (_sequenceType == sequenceTypePlaybook) {
parser = new HongKangParser(name,
_sequenceSource,
_projectorID,
translationDictionary,
_potentialTargets);
openspace::ImageSequencer2::ref().runSequenceParser(parser);
}
else if (_sequenceType == sequenceTypeImage) {
parser = new LabelParser(name,
_projectorID,
translationDictionary,
_potentialTargets);
openspace::ImageSequencer2::ref().runSequenceParser(parser);
}
else if (_sequenceType == sequenceTypeImage) {
parser = new LabelParser(name,
_sequenceSource,
translationDictionary);
openspace::ImageSequencer2::ref().runSequenceParser(parser);
}
else if (_sequenceType == sequenceTypeHybrid) {
//first read labels
parser = new LabelParser(name,
openspace::ImageSequencer2::ref().runSequenceParser(parser);
}
else if (_sequenceType == sequenceTypeHybrid) {
//first read labels
parser = new LabelParser(name,
_sequenceSource,
translationDictionary);
openspace::ImageSequencer2::ref().runSequenceParser(parser);
openspace::ImageSequencer2::ref().runSequenceParser(parser);
std::string _eventFile;
bool foundEventFile = dictionary.getValue("Projection.EventFile", _eventFile);
if (foundEventFile){
//then read playbook
_eventFile = absPath(_eventFile);
parser = new HongKangParser(name,
std::string _eventFile;
bool foundEventFile = dictionary.getValue("Projection.EventFile", _eventFile);
if (foundEventFile){
//then read playbook
_eventFile = absPath(_eventFile);
parser = new HongKangParser(name,
_eventFile,
_projectorID,
translationDictionary,
_potentialTargets);
openspace::ImageSequencer2::ref().runSequenceParser(parser);
}
else{
LWARNING("No eventfile has been provided, please check modfiles");
}
}
}
else{
LWARNING("No playbook translation provided, please make sure all spice calls match playbook!");
}
_projectorID,
translationDictionary,
_potentialTargets);
openspace::ImageSequencer2::ref().runSequenceParser(parser);
}
else{
LWARNING("No eventfile has been provided, please check modfiles");
}
}
}
else{
LWARNING("No playbook translation provided, please make sure all spice calls match playbook!");
}
}
}
@@ -254,71 +255,71 @@ bool RenderablePlanetProjection::initialize() {
"${SHADERS}/fboPass_fs.glsl");
loadTexture();
loadProjectionTexture();
loadProjectionTexture();
completeSuccess &= (_texture != nullptr);
completeSuccess &= (_textureOriginal != nullptr);
completeSuccess &= (_textureProj != nullptr);
completeSuccess &= (_textureWhiteSquare != nullptr);
completeSuccess &= (_textureOriginal != nullptr);
completeSuccess &= (_textureProj != nullptr);
completeSuccess &= (_textureWhiteSquare != nullptr);
completeSuccess &= _geometry->initialize(this);
if (completeSuccess)
completeSuccess &= auxiliaryRendertarget();
completeSuccess &= auxiliaryRendertarget();
return completeSuccess;
}
bool RenderablePlanetProjection::auxiliaryRendertarget(){
bool completeSuccess = true;
if (!_texture) return false;
bool completeSuccess = true;
if (!_texture) return false;
GLint defaultFBO;
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO);
GLint defaultFBO;
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO);
// setup FBO
glGenFramebuffers(1, &_fboID);
glBindFramebuffer(GL_FRAMEBUFFER, _fboID);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, *_texture, 0);
// check FBO status
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE)
completeSuccess &= false;
// switch back to window-system-provided framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO);
// setup FBO
glGenFramebuffers(1, &_fboID);
glBindFramebuffer(GL_FRAMEBUFFER, _fboID);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, *_texture, 0);
// check FBO status
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE)
completeSuccess &= false;
// switch back to window-system-provided framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO);
// SCREEN-QUAD
const GLfloat size = 1.0f;
const GLfloat w = 1.0f;
const GLfloat vertex_data[] = {
-size, -size, 0.0f, w, 0, 1,
size, size, 0.0f, w, 1, 0,
-size, size, 0.0f, w, 0, 0,
-size, -size, 0.0f, w, 0, 1,
size, -size, 0.0f, w, 1, 1,
size, size, 0.0f, w, 1, 0,
};
// SCREEN-QUAD
const GLfloat size = 1.0f;
const GLfloat w = 1.0f;
const GLfloat vertex_data[] = {
-size, -size, 0.0f, w, 0, 1,
size, size, 0.0f, w, 1, 0,
-size, size, 0.0f, w, 0, 0,
-size, -size, 0.0f, w, 0, 1,
size, -size, 0.0f, w, 1, 1,
size, size, 0.0f, w, 1, 0,
};
glGenVertexArrays(1, &_quad); // generate array
glBindVertexArray(_quad); // bind array
glGenBuffers(1, &_vertexPositionBuffer); // generate buffer
glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); // bind buffer
glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW);
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, reinterpret_cast<void*>(0));
glEnableVertexAttribArray(4);
glVertexAttribPointer(4, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, reinterpret_cast<void*>(sizeof(GLfloat) * 4));
glGenVertexArrays(1, &_quad); // generate array
glBindVertexArray(_quad); // bind array
glGenBuffers(1, &_vertexPositionBuffer); // generate buffer
glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); // bind buffer
glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW);
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, reinterpret_cast<void*>(0));
glEnableVertexAttribArray(4);
glVertexAttribPointer(4, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, reinterpret_cast<void*>(sizeof(GLfloat) * 4));
return completeSuccess;
return completeSuccess;
}
bool RenderablePlanetProjection::deinitialize(){
_texture = nullptr;
_textureProj = nullptr;
_textureOriginal = nullptr;
_textureWhiteSquare = nullptr;
delete _geometry;
_geometry = nullptr;
_textureProj = nullptr;
_textureOriginal = nullptr;
_textureWhiteSquare = nullptr;
delete _geometry;
_geometry = nullptr;
RenderEngine& renderEngine = OsEng.renderEngine();
if (_programObject) {
@@ -329,117 +330,117 @@ bool RenderablePlanetProjection::deinitialize(){
return true;
}
bool RenderablePlanetProjection::isReady() const {
return _geometry && _programObject && _texture && _textureWhiteSquare;
return _geometry && _programObject && _texture && _textureWhiteSquare;
}
void RenderablePlanetProjection::imageProjectGPU(){
glDisable(GL_DEPTH_TEST);
// keep handle to the current bound FBO
GLint defaultFBO;
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO);
// keep handle to the current bound FBO
GLint defaultFBO;
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO);
GLint m_viewport[4];
glGetIntegerv(GL_VIEWPORT, m_viewport);
//counter = 0;
glBindFramebuffer(GL_FRAMEBUFFER, _fboID);
// set blend eq
glEnable(GL_BLEND);
glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD);
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ZERO);
GLint m_viewport[4];
glGetIntegerv(GL_VIEWPORT, m_viewport);
//counter = 0;
glBindFramebuffer(GL_FRAMEBUFFER, _fboID);
// set blend eq
glEnable(GL_BLEND);
glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD);
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ZERO);
glViewport(0, 0, static_cast<GLsizei>(_texture->width()), static_cast<GLsizei>(_texture->height()));
_fboProgramObject->activate();
glViewport(0, 0, static_cast<GLsizei>(_texture->width()), static_cast<GLsizei>(_texture->height()));
_fboProgramObject->activate();
ghoul::opengl::TextureUnit unitFbo;
unitFbo.activate();
_textureProj->bind();
_fboProgramObject->setUniform("texture1" , unitFbo);
ghoul::opengl::TextureUnit unitFbo2;
unitFbo2.activate();
_textureOriginal->bind();
_fboProgramObject->setUniform("texture2", unitFbo2);
_fboProgramObject->setUniform("projectionFading", _fadeProjection);
ghoul::opengl::TextureUnit unitFbo;
unitFbo.activate();
_textureProj->bind();
_fboProgramObject->setUniform("texture1" , unitFbo);
ghoul::opengl::TextureUnit unitFbo2;
unitFbo2.activate();
_textureOriginal->bind();
_fboProgramObject->setUniform("texture2", unitFbo2);
_fboProgramObject->setUniform("projectionFading", _fadeProjection);
_fboProgramObject->setUniform("ProjectorMatrix", _projectorMatrix);
_fboProgramObject->setUniform("ModelTransform" , _transform);
_fboProgramObject->setUniform("_scaling" , _camScaling);
_fboProgramObject->setUniform("boresight" , _boresight);
_fboProgramObject->setUniform("ProjectorMatrix", _projectorMatrix);
_fboProgramObject->setUniform("ModelTransform" , _transform);
_fboProgramObject->setUniform("_scaling" , _camScaling);
_fboProgramObject->setUniform("boresight" , _boresight);
if (_geometry->hasProperty("radius")){
if (_geometry->hasProperty("radius")){
ghoul::any r = _geometry->property("radius")->get();
if (glm::vec4* radius = ghoul::any_cast<glm::vec4>(&r)){
_fboProgramObject->setUniform("radius", radius);
}
}else{
LERROR("Geometry object needs to provide radius");
}
if (_geometry->hasProperty("segments")){
if (glm::vec4* radius = ghoul::any_cast<glm::vec4>(&r)){
_fboProgramObject->setUniform("radius", radius);
}
}else{
LERROR("Geometry object needs to provide radius");
}
if (_geometry->hasProperty("segments")){
ghoul::any s = _geometry->property("segments")->get();
if (int* segments = ghoul::any_cast<int>(&s)){
_fboProgramObject->setAttribute("segments", segments[0]);
}
}else{
LERROR("Geometry object needs to provide segment count");
}
if (int* segments = ghoul::any_cast<int>(&s)){
_fboProgramObject->setAttribute("segments", segments[0]);
}
}else{
LERROR("Geometry object needs to provide segment count");
}
glBindVertexArray(_quad);
glDrawArrays(GL_TRIANGLES, 0, 6);
_fboProgramObject->deactivate();
//glDisable(GL_BLEND);
glBindVertexArray(_quad);
glDrawArrays(GL_TRIANGLES, 0, 6);
_fboProgramObject->deactivate();
//glDisable(GL_BLEND);
//bind back to default
glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO);
glViewport(m_viewport[0], m_viewport[1],
m_viewport[2], m_viewport[3]);
//bind back to default
glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO);
glViewport(m_viewport[0], m_viewport[1],
m_viewport[2], m_viewport[3]);
glEnable(GL_DEPTH_TEST);
glEnable(GL_DEPTH_TEST);
}
glm::mat4 RenderablePlanetProjection::computeProjectorMatrix(const glm::vec3 loc, glm::dvec3 aim, const glm::vec3 up){
//rotate boresight into correct alignment
_boresight = _instrumentMatrix*aim;
glm::vec3 uptmp(_instrumentMatrix*glm::dvec3(up));
//rotate boresight into correct alignment
_boresight = _instrumentMatrix*aim;
glm::vec3 uptmp(_instrumentMatrix*glm::dvec3(up));
// create view matrix
glm::vec3 e3 = glm::normalize(_boresight);
glm::vec3 e1 = glm::normalize(glm::cross(uptmp, e3));
glm::vec3 e2 = glm::normalize(glm::cross(e3, e1));
glm::mat4 projViewMatrix = glm::mat4(e1.x, e2.x, e3.x, 0.f,
e1.y, e2.y, e3.y, 0.f,
e1.z, e2.z, e3.z, 0.f,
-glm::dot(e1, loc), -glm::dot(e2, loc), -glm::dot(e3, loc), 1.f);
// create perspective projection matrix
glm::mat4 projProjectionMatrix = glm::perspective(glm::radians(_fovy), _aspectRatio, _nearPlane, _farPlane);
// bias matrix
glm::mat4 projNormalizationMatrix = glm::mat4(0.5f, 0, 0, 0,
0, 0.5f, 0, 0,
0, 0, 0.5f, 0,
0.5f, 0.5f, 0.5f, 1);
return projNormalizationMatrix*projProjectionMatrix*projViewMatrix;
// create view matrix
glm::vec3 e3 = glm::normalize(_boresight);
glm::vec3 e1 = glm::normalize(glm::cross(uptmp, e3));
glm::vec3 e2 = glm::normalize(glm::cross(e3, e1));
glm::mat4 projViewMatrix = glm::mat4(e1.x, e2.x, e3.x, 0.f,
e1.y, e2.y, e3.y, 0.f,
e1.z, e2.z, e3.z, 0.f,
-glm::dot(e1, loc), -glm::dot(e2, loc), -glm::dot(e3, loc), 1.f);
// create perspective projection matrix
glm::mat4 projProjectionMatrix = glm::perspective(glm::radians(_fovy), _aspectRatio, _nearPlane, _farPlane);
// bias matrix
glm::mat4 projNormalizationMatrix = glm::mat4(0.5f, 0, 0, 0,
0, 0.5f, 0, 0,
0, 0, 0.5f, 0,
0.5f, 0.5f, 0.5f, 1);
return projNormalizationMatrix*projProjectionMatrix*projViewMatrix;
}
void RenderablePlanetProjection::attitudeParameters(double time){
// precomputations for shader
// precomputations for shader
_stateMatrix = SpiceManager::ref().positionTransformMatrix(_frame, _mainFrame, time);
_instrumentMatrix = SpiceManager::ref().positionTransformMatrix(_instrumentID, _mainFrame, time);
_transform = glm::mat4(1);
//90 deg rotation w.r.t spice req.
glm::mat4 rot = glm::rotate(_transform, static_cast<float>(M_PI_2), glm::vec3(1, 0, 0));
glm::mat4 roty = glm::rotate(_transform, static_cast<float>(M_PI_2), glm::vec3(0, -1, 0));
glm::mat4 rotProp = glm::rotate(_transform, static_cast<float>(glm::radians(static_cast<float>(_rotation))), glm::vec3(0, 1, 0));
_transform = glm::mat4(1);
//90 deg rotation w.r.t spice req.
glm::mat4 rot = glm::rotate(_transform, static_cast<float>(M_PI_2), glm::vec3(1, 0, 0));
glm::mat4 roty = glm::rotate(_transform, static_cast<float>(M_PI_2), glm::vec3(0, -1, 0));
glm::mat4 rotProp = glm::rotate(_transform, static_cast<float>(glm::radians(static_cast<float>(_rotation))), glm::vec3(0, 1, 0));
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
_transform[i][j] = static_cast<float>(_stateMatrix[i][j]);
}
}
_transform = _transform * rot * roty * rotProp;
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
_transform[i][j] = static_cast<float>(_stateMatrix[i][j]);
}
}
_transform = _transform * rot * roty * rotProp;
glm::dvec3 bs;
glm::dvec3 bs;
try {
SpiceManager::FieldOfViewResult res = SpiceManager::ref().fieldOfView(_instrumentID);
bs = std::move(res.boresightVector);
@@ -452,99 +453,99 @@ void RenderablePlanetProjection::attitudeParameters(double time){
glm::dvec3 p = SpiceManager::ref().targetPosition(_projectorID, _projecteeID, _mainFrame, _aberration, time, lightTime);
psc position = PowerScaledCoordinate::CreatePowerScaledCoordinate(p.x, p.y, p.z);
//change to KM and add psc camera scaling.
position[3] += (3 + _camScaling[1]);
//change to KM and add psc camera scaling.
position[3] += (3 + _camScaling[1]);
//position[3] += 3;
glm::vec3 cpos = position.vec3();
glm::vec3 cpos = position.vec3();
_projectorMatrix = computeProjectorMatrix(cpos, bs, _up);
_projectorMatrix = computeProjectorMatrix(cpos, bs, _up);
}
void RenderablePlanetProjection::textureBind() {
ghoul::opengl::TextureUnit unit[2];
unit[0].activate();
_texture->bind();
_programObject->setUniform("texture1", unit[0]);
unit[1].activate();
_textureWhiteSquare->bind();
_programObject->setUniform("texture2", unit[1]);
ghoul::opengl::TextureUnit unit[2];
unit[0].activate();
_texture->bind();
_programObject->setUniform("texture1", unit[0]);
unit[1].activate();
_textureWhiteSquare->bind();
_programObject->setUniform("texture2", unit[1]);
}
void RenderablePlanetProjection::project(){
// If high dt -> results in GPU queue overflow
// switching to using a simple queue to distribute
// images 1 image / frame -> projections appear slower
// but less viewable lagg for the sim overall.
// If high dt -> results in GPU queue overflow
// switching to using a simple queue to distribute
// images 1 image / frame -> projections appear slower
// but less viewable lagg for the sim overall.
// Comment out if not using queue and prefer old method -------------
// + in update() function
//if (!imageQueue.empty()){
// Image& img = imageQueue.front();
// RenderablePlanetProjection::attitudeParameters(img.startTime);
// // if image has new path - ie actual image, NOT placeholder
// if (_projectionTexturePath.value() != img.path){
// // rebind and upload
// _projectionTexturePath = img.path;
// }
// imageProjectGPU(); // fbopass
// imageQueue.pop();
//}
// ------------------------------------------------------------------
// Comment out if not using queue and prefer old method -------------
// + in update() function
//if (!imageQueue.empty()){
// Image& img = imageQueue.front();
// RenderablePlanetProjection::attitudeParameters(img.startTime);
// // if image has new path - ie actual image, NOT placeholder
// if (_projectionTexturePath.value() != img.path){
// // rebind and upload
// _projectionTexturePath = img.path;
// }
// imageProjectGPU(); // fbopass
// imageQueue.pop();
//}
// ------------------------------------------------------------------
//---- Old method --- //
// @mm
for (auto const &img : _imageTimes){
RenderablePlanetProjection::attitudeParameters(img.startTime);
if (_projectionTexturePath.value() != img.path){
_projectionTexturePath = img.path; // path to current images
}
imageProjectGPU(); // fbopass
}
_capture = false;
//---- Old method --- //
// @mm
for (auto const &img : _imageTimes){
RenderablePlanetProjection::attitudeParameters(img.startTime);
if (_projectionTexturePath.value() != img.path){
_projectionTexturePath = img.path; // path to current images
}
imageProjectGPU(); // fbopass
}
_capture = false;
}
void RenderablePlanetProjection::clearAllProjections(){
float tmp = _fadeProjection;
_fadeProjection = 1.f;
_projectionTexturePath = _clearingImage;
imageProjectGPU();
_fadeProjection = tmp;
_clearAllProjections = false;
float tmp = _fadeProjection;
_fadeProjection = 1.f;
_projectionTexturePath = _clearingImage;
imageProjectGPU();
_fadeProjection = tmp;
_clearAllProjections = false;
}
void RenderablePlanetProjection::render(const RenderData& data){
if (!_programObject) return;
if (!_textureProj) return;
if (_clearAllProjections) clearAllProjections();
if (!_programObject) return;
if (!_textureProj) return;
if (_clearAllProjections) clearAllProjections();
_camScaling = data.camera.scaling();
_up = data.camera.lookUpVector();
_camScaling = data.camera.scaling();
_up = data.camera.lookUpVector();
if (_capture && _performProjection)
project();
if (_capture && _performProjection)
project();
attitudeParameters(_time);
_imageTimes.clear();
_imageTimes.clear();
double lt;
double lt;
glm::dvec3 p =
openspace::SpiceManager::ref().targetPosition("SUN", _projecteeID, "GALACTIC", {}, _time, lt);
psc sun_pos = PowerScaledCoordinate::CreatePowerScaledCoordinate(p.x, p.y, p.z);
// Main renderpass
_programObject->activate();
// Main renderpass
_programObject->activate();
// setup the data to the shader
_programObject->setUniform("sun_pos", sun_pos.vec3());
_programObject->setUniform("ProjectorMatrix", _projectorMatrix);
_programObject->setUniform("ViewProjection" , data.camera.viewProjectionMatrix());
_programObject->setUniform("ModelTransform" , _transform);
_programObject->setUniform("boresight" , _boresight);
setPscUniforms(*_programObject.get(), data.camera, data.position);
textureBind();
_programObject->setUniform("sun_pos", sun_pos.vec3());
_programObject->setUniform("ProjectorMatrix", _projectorMatrix);
_programObject->setUniform("ViewProjection" , data.camera.viewProjectionMatrix());
_programObject->setUniform("ModelTransform" , _transform);
_programObject->setUniform("boresight" , _boresight);
setPscUniforms(*_programObject.get(), data.camera, data.position);
textureBind();
// render geometry
_geometry->render();
// disable shader
@@ -552,74 +553,80 @@ void RenderablePlanetProjection::render(const RenderData& data){
}
void RenderablePlanetProjection::update(const UpdateData& data){
if (_time >= Time::ref().currentTime()) {
if (_time >= Time::ref().currentTime()) {
// if jump back in time -> empty queue.
imageQueue = std::queue<Image>();
}
}
_time = Time::ref().currentTime();
_capture = false;
_time = Time::ref().currentTime();
_capture = false;
if (openspace::ImageSequencer2::ref().isReady() && _performProjection){
openspace::ImageSequencer2::ref().updateSequencer(_time);
_capture = openspace::ImageSequencer2::ref().getImagePaths(_imageTimes, _projecteeID, _instrumentID);
if (openspace::ImageSequencer2::ref().isReady() && _performProjection){
openspace::ImageSequencer2::ref().updateSequencer(_time);
_capture = openspace::ImageSequencer2::ref().getImagePaths(_imageTimes, _projecteeID, _instrumentID);
}
if (_fboProgramObject && _fboProgramObject->isDirty()) {
_fboProgramObject->rebuildFromFile();
}
// remove these lines if not using queue ------------------------
// @mm
//_capture = true;
//for (auto img : _imageTimes){
// imageQueue.push(img);
//}
//_imageTimes.clear();
// --------------------------------------------------------------
// remove these lines if not using queue ------------------------
// @mm
//_capture = true;
//for (auto img : _imageTimes){
// imageQueue.push(img);
//}
//_imageTimes.clear();
// --------------------------------------------------------------
if (_programObject->isDirty())
_programObject->rebuildFromFile();
}
void RenderablePlanetProjection::loadProjectionTexture() {
_textureProj = nullptr;
if (_colorTexturePath.value() != "") {
_textureProj = std::move(ghoul::io::TextureReader::ref().loadTexture(absPath(_projectionTexturePath)));
if (_textureProj) {
_textureProj->uploadTexture();
_textureProj = nullptr;
if (_colorTexturePath.value() != "") {
_textureProj = ghoul::io::TextureReader::ref().loadTexture(absPath(_projectionTexturePath));
if (_textureProj) {
if (_textureProj->format() == ghoul::opengl::Texture::Format::Red)
_textureProj->setSwizzleMask({ GL_RED, GL_RED, GL_RED, GL_ONE });
_textureProj->uploadTexture();
// TODO: AnisotropicMipMap crashes on ATI cards ---abock
//_textureProj->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap);
_textureProj->setFilter(ghoul::opengl::Texture::FilterMode::Linear);
_textureProj->setWrapping(ghoul::opengl::Texture::WrappingMode::ClampToBorder);
}
}
_textureProj->setWrapping(ghoul::opengl::Texture::WrappingMode::ClampToBorder);
}
}
}
void RenderablePlanetProjection::loadTexture() {
using ghoul::opengl::Texture;
_texture = nullptr;
if (_colorTexturePath.value() != "") {
_texture = std::move(ghoul::io::TextureReader::ref().loadTexture(_colorTexturePath));
_texture = ghoul::io::TextureReader::ref().loadTexture(_colorTexturePath);
if (_texture) {
_texture->uploadTexture();
_texture->setFilter(ghoul::opengl::Texture::FilterMode::Linear);
ghoul::opengl::convertTextureFormat(Texture::Format::RGB, *_texture);
_texture->uploadTexture();
_texture->setFilter(Texture::FilterMode::Linear);
}
}
_textureOriginal = nullptr;
if (_colorTexturePath.value() != "") {
_textureOriginal = ghoul::io::TextureReader::ref().loadTexture(_colorTexturePath);
if (_textureOriginal) {
ghoul::opengl::convertTextureFormat(Texture::Format::RGB, *_texture);
_textureOriginal->uploadTexture();
_textureOriginal->setFilter(Texture::FilterMode::Linear);
}
}
_textureWhiteSquare = nullptr;
if (_colorTexturePath.value() != "") {
_textureWhiteSquare = ghoul::io::TextureReader::ref().loadTexture(_defaultProjImage);
if (_textureWhiteSquare) {
_textureWhiteSquare->uploadTexture();
_textureWhiteSquare->setFilter(Texture::FilterMode::Linear);
}
}
_textureOriginal = nullptr;
if (_colorTexturePath.value() != "") {
_textureOriginal = std::move(ghoul::io::TextureReader::ref().loadTexture(_colorTexturePath));
if (_textureOriginal) {
_textureOriginal->uploadTexture();
_textureOriginal->setFilter(ghoul::opengl::Texture::FilterMode::Linear);
}
}
_textureWhiteSquare = nullptr;
if (_colorTexturePath.value() != "") {
_textureWhiteSquare = std::move(ghoul::io::TextureReader::ref().loadTexture(_defaultProjImage));
if (_textureWhiteSquare) {
_textureWhiteSquare->uploadTexture();
_textureWhiteSquare->setFilter(ghoul::opengl::Texture::FilterMode::Linear);
}
}
}
} // namespace openspace
+232 -232
View File
@@ -79,7 +79,7 @@ using namespace ghoul::cmdparser;
namespace {
const std::string _loggerCat = "OpenSpaceEngine";
const std::string _sgctDefaultConfigFile = "${SGCT}/single.xml";
const std::string _defaultCacheLocation = "${BASE_PATH}/cache";
const std::string _defaultCacheLocation = "${BASE_PATH}/cache";
const std::string _sgctConfigArgumentCommand = "-config";
@@ -88,7 +88,7 @@ namespace {
struct {
std::string configurationName;
std::string sgctConfigurationName;
std::string sgctConfigurationName;
std::string sceneName;
} commandlineArgumentPlaceholders;
}
@@ -113,7 +113,7 @@ OpenSpaceEngine::OpenSpaceEngine(std::string programName,
, _parallelConnection(new network::ParallelConnection)
, _windowWrapper(std::move(windowWrapper))
, _globalPropertyNamespace(new properties::PropertyOwner)
, _isMaster(false)
, _isMaster(false)
, _runTime(0.0)
, _syncBuffer(new SyncBuffer(1024))
{
@@ -147,7 +147,7 @@ OpenSpaceEngine::~OpenSpaceEngine() {
_console = nullptr;
_moduleEngine = nullptr;
_gui = nullptr;
_syncBuffer = nullptr;
_syncBuffer = nullptr;
}
OpenSpaceEngine& OpenSpaceEngine::ref() {
@@ -164,18 +164,18 @@ bool OpenSpaceEngine::create(int argc, char** argv,
ghoul::initialize();
// Initialize the LogManager and add the console log as this will be used every time
// and we need a fall back if something goes wrong between here and when we add the
// logs from the configuration file. If the user requested as specific loglevel in the
// configuration file, we will deinitialize this LogManager and reinitialize it later
// with the correct LogLevel
LogManager::initialize(
// Initialize the LogManager and add the console log as this will be used every time
// and we need a fall back if something goes wrong between here and when we add the
// logs from the configuration file. If the user requested as specific loglevel in the
// configuration file, we will deinitialize this LogManager and reinitialize it later
// with the correct LogLevel
LogManager::initialize(
LogManager::LogLevel::Debug,
ghoul::logging::LogManager::ImmediateFlush::Yes
);
LogMgr.addLog(std::make_unique<ConsoleLog>());
LDEBUG("Initialize FileSystem");
LDEBUG("Initialize FileSystem");
#ifdef __APPLE__
ghoul::filesystem::File app(argv[0]);
@@ -184,33 +184,33 @@ bool OpenSpaceEngine::create(int argc, char** argv,
FileSys.setCurrentDirectory(dirName);
#endif
// Sanity check of values
if (argc < 1 || argv == nullptr) {
LFATAL("No arguments were passed to this function");
return false;
}
// Sanity check of values
if (argc < 1 || argv == nullptr) {
LFATAL("No arguments were passed to this function");
return false;
}
// Create other objects
LDEBUG("Creating OpenSpaceEngine");
// Create other objects
LDEBUG("Creating OpenSpaceEngine");
_engine = new OpenSpaceEngine(std::string(argv[0]), std::move(windowWrapper));
// Query modules for commandline arguments
bool gatherSuccess = _engine->gatherCommandlineArguments();
if (!gatherSuccess)
return false;
// Query modules for commandline arguments
bool gatherSuccess = _engine->gatherCommandlineArguments();
if (!gatherSuccess)
return false;
// Parse commandline arguments
// Parse commandline arguments
sgctArguments = *(_engine->_commandlineParser->setCommandLine(argc, argv));
bool showHelp = _engine->_commandlineParser->execute();
bool showHelp = _engine->_commandlineParser->execute();
if (showHelp) {
_engine->_commandlineParser->displayHelp();
return false;
}
// Find configuration
std::string configurationFilePath = commandlineArgumentPlaceholders.configurationName;
if (configurationFilePath.empty()) {
LDEBUG("Finding configuration");
// Find configuration
std::string configurationFilePath = commandlineArgumentPlaceholders.configurationName;
if (configurationFilePath.empty()) {
LDEBUG("Finding configuration");
try {
configurationFilePath =
ConfigurationManager::findConfiguration(configurationFilePath);
@@ -218,12 +218,12 @@ bool OpenSpaceEngine::create(int argc, char** argv,
catch (const ghoul::RuntimeError& e) {
LFATALC(e.component, e.message);
}
}
configurationFilePath = absPath(configurationFilePath);
LINFO("Configuration Path: '" << configurationFilePath << "'");
}
configurationFilePath = absPath(configurationFilePath);
LINFO("Configuration Path: '" << configurationFilePath << "'");
// Loading configuration from disk
LDEBUG("Loading configuration from disk");
// Loading configuration from disk
LDEBUG("Loading configuration from disk");
try {
_engine->configurationManager().loadFromFile(configurationFilePath);
}
@@ -233,55 +233,55 @@ bool OpenSpaceEngine::create(int argc, char** argv,
return false;
}
// Initialize the requested logs from the configuration file
_engine->configureLogging();
// Initialize the requested logs from the configuration file
_engine->configureLogging();
LINFOC("OpenSpace Version",
OPENSPACE_VERSION_MAJOR << "." <<
OPENSPACE_VERSION_MINOR << "." <<
OPENSPACE_VERSION_PATCH << " (" << OPENSPACE_VERSION_STRING << ")");
// Create directories that doesn't exist
auto tokens = FileSys.tokens();
for (const std::string& token : tokens) {
if (!FileSys.directoryExists(token)) {
std::string p = absPath(token);
LDEBUG("Directory '" << p << "' does not exist, creating.");
// Create directories that doesn't exist
auto tokens = FileSys.tokens();
for (const std::string& token : tokens) {
if (!FileSys.directoryExists(token)) {
std::string p = absPath(token);
LDEBUG("Directory '" << p << "' does not exist, creating.");
FileSys.createDirectory(p, ghoul::filesystem::FileSystem::Recursive::Yes);
}
}
}
}
// Register modules
_engine->_moduleEngine->initialize();
// Create the cachemanager
FileSys.createCacheManager(
// Create the cachemanager
FileSys.createCacheManager(
absPath("${" + ConfigurationManager::KeyCache + "}"), CacheVersion
);
_engine->_console->initialize();
_engine->_console->initialize();
// Register the provided shader directories
ghoul::opengl::ShaderPreprocessor::addIncludePath(absPath("${SHADERS}"));
// Register the provided shader directories
ghoul::opengl::ShaderPreprocessor::addIncludePath(absPath("${SHADERS}"));
// Determining SGCT configuration file
LDEBUG("Determining SGCT configuration file");
std::string sgctConfigurationPath = _sgctDefaultConfigFile;
_engine->configurationManager().getValue(
ConfigurationManager::KeyConfigSgct, sgctConfigurationPath);
// Determining SGCT configuration file
LDEBUG("Determining SGCT configuration file");
std::string sgctConfigurationPath = _sgctDefaultConfigFile;
_engine->configurationManager().getValue(
ConfigurationManager::KeyConfigSgct, sgctConfigurationPath);
if (!commandlineArgumentPlaceholders.sgctConfigurationName.empty()) {
LDEBUG("Overwriting SGCT configuration file with commandline argument: " <<
commandlineArgumentPlaceholders.sgctConfigurationName);
sgctConfigurationPath = commandlineArgumentPlaceholders.sgctConfigurationName;
}
if (!commandlineArgumentPlaceholders.sgctConfigurationName.empty()) {
LDEBUG("Overwriting SGCT configuration file with commandline argument: " <<
commandlineArgumentPlaceholders.sgctConfigurationName);
sgctConfigurationPath = commandlineArgumentPlaceholders.sgctConfigurationName;
}
// Prepend the outgoing sgctArguments with the program name
// as well as the configuration file that sgct is supposed to use
sgctArguments.insert(sgctArguments.begin(), argv[0]);
sgctArguments.insert(sgctArguments.begin() + 1, _sgctConfigArgumentCommand);
sgctArguments.insert(sgctArguments.begin() + 2, absPath(sgctConfigurationPath));
// Prepend the outgoing sgctArguments with the program name
// as well as the configuration file that sgct is supposed to use
sgctArguments.insert(sgctArguments.begin(), argv[0]);
sgctArguments.insert(sgctArguments.begin() + 1, _sgctConfigArgumentCommand);
sgctArguments.insert(sgctArguments.begin() + 2, absPath(sgctConfigurationPath));
return true;
return true;
}
void OpenSpaceEngine::destroy() {
@@ -289,30 +289,30 @@ void OpenSpaceEngine::destroy() {
_engine->_console->deinitialize();
_engine->_scriptEngine->deinitialize();
delete _engine;
ghoul::systemcapabilities::SystemCapabilities::deinitialize();
FactoryManager::deinitialize();
Time::deinitialize();
SpiceManager::deinitialize();
delete _engine;
ghoul::systemcapabilities::SystemCapabilities::deinitialize();
FactoryManager::deinitialize();
Time::deinitialize();
SpiceManager::deinitialize();
LogManager::deinitialize();
LogManager::deinitialize();
ghoul::deinitialize();
}
bool OpenSpaceEngine::initialize() {
// clear the screen so the user don't have to see old buffer contents from the
// graphics card
clearAllWindows();
// clear the screen so the user don't have to see old buffer contents from the
// graphics card
clearAllWindows();
// Detect and log OpenCL and OpenGL versions and available devices
// Detect and log OpenCL and OpenGL versions and available devices
SysCap.addComponent(
std::make_unique<ghoul::systemcapabilities::GeneralCapabilitiesComponent>()
);
SysCap.addComponent(
std::make_unique<ghoul::systemcapabilities::OpenGLCapabilitiesComponent>()
);
SysCap.detectCapabilities();
SysCap.detectCapabilities();
using Verbosity = ghoul::systemcapabilities::SystemCapabilitiesComponent::Verbosity;
Verbosity verbosity = Verbosity::Default;
@@ -328,43 +328,43 @@ bool OpenSpaceEngine::initialize() {
if (verbosityMap.find(v) != verbosityMap.end())
verbosity = verbosityMap[v];
}
SysCap.logCapabilities(verbosity);
SysCap.logCapabilities(verbosity);
std::string requestURL = "";
bool success = configurationManager().getValue(ConfigurationManager::KeyDownloadRequestURL, requestURL);
if (success)
DownloadManager::initialize(requestURL, DownloadVersion);
// Load SPICE time kernel
success = loadSpiceKernels();
if (!success)
return false;
// Load SPICE time kernel
success = loadSpiceKernels();
if (!success)
return false;
// Register Lua script functions
LDEBUG("Registering Lua libraries");
_scriptEngine->addLibrary(RenderEngine::luaLibrary());
_scriptEngine->addLibrary(Scene::luaLibrary());
_scriptEngine->addLibrary(Time::luaLibrary());
_scriptEngine->addLibrary(interaction::InteractionHandler::luaLibrary());
_scriptEngine->addLibrary(LuaConsole::luaLibrary());
_scriptEngine->addLibrary(gui::GUI::luaLibrary());
// Register Lua script functions
LDEBUG("Registering Lua libraries");
_scriptEngine->addLibrary(RenderEngine::luaLibrary());
_scriptEngine->addLibrary(Scene::luaLibrary());
_scriptEngine->addLibrary(Time::luaLibrary());
_scriptEngine->addLibrary(interaction::InteractionHandler::luaLibrary());
_scriptEngine->addLibrary(LuaConsole::luaLibrary());
_scriptEngine->addLibrary(gui::GUI::luaLibrary());
_scriptEngine->addLibrary(network::ParallelConnection::luaLibrary());
// TODO: Maybe move all scenegraph and renderengine stuff to initializeGL
scriptEngine().initialize();
// TODO: Maybe move all scenegraph and renderengine stuff to initializeGL
scriptEngine().initialize();
// If a LuaDocumentationFile was specified, generate it now
const bool hasType = configurationManager().hasKey(ConfigurationManager::KeyLuaDocumentationType);
const bool hasFile = configurationManager().hasKey(ConfigurationManager::KeyLuaDocumentationFile);
if (hasType && hasFile) {
std::string luaDocumentationType;
configurationManager().getValue(ConfigurationManager::KeyLuaDocumentationType, luaDocumentationType);
std::string luaDocumentationFile;
configurationManager().getValue(ConfigurationManager::KeyLuaDocumentationFile, luaDocumentationFile);
// If a LuaDocumentationFile was specified, generate it now
const bool hasType = configurationManager().hasKey(ConfigurationManager::KeyLuaDocumentationType);
const bool hasFile = configurationManager().hasKey(ConfigurationManager::KeyLuaDocumentationFile);
if (hasType && hasFile) {
std::string luaDocumentationType;
configurationManager().getValue(ConfigurationManager::KeyLuaDocumentationType, luaDocumentationType);
std::string luaDocumentationFile;
configurationManager().getValue(ConfigurationManager::KeyLuaDocumentationFile, luaDocumentationFile);
luaDocumentationFile = absPath(luaDocumentationFile);
_scriptEngine->writeDocumentation(luaDocumentationFile, luaDocumentationType);
}
luaDocumentationFile = absPath(luaDocumentationFile);
_scriptEngine->writeDocumentation(luaDocumentationFile, luaDocumentationType);
}
bool disableMasterRendering = false;
configurationManager().getValue(
@@ -372,41 +372,41 @@ bool OpenSpaceEngine::initialize() {
_renderEngine->setDisableRenderingOnMaster(disableMasterRendering);
// Load scenegraph
Scene* sceneGraph = new Scene;
_renderEngine->setSceneGraph(sceneGraph);
// Load scenegraph
Scene* sceneGraph = new Scene;
_renderEngine->setSceneGraph(sceneGraph);
// initialize the RenderEngine
// initialize the RenderEngine
_renderEngine->initialize();
sceneGraph->initialize();
sceneGraph->initialize();
std::string sceneDescriptionPath = "";
if (commandlineArgumentPlaceholders.sceneName.empty()) {
success = configurationManager().getValue(
ConfigurationManager::KeyConfigScene, sceneDescriptionPath);
success = configurationManager().getValue(
ConfigurationManager::KeyConfigScene, sceneDescriptionPath);
}
else
sceneDescriptionPath = commandlineArgumentPlaceholders.sceneName;
sceneGraph->scheduleLoadSceneFile(sceneDescriptionPath);
sceneGraph->scheduleLoadSceneFile(sceneDescriptionPath);
_interactionHandler->setKeyboardController(new interaction::KeyboardControllerFixed);
_interactionHandler->setMouseController(new interaction::OrbitalMouseController);
_interactionHandler->setKeyboardController(new interaction::KeyboardControllerFixed);
_interactionHandler->setMouseController(new interaction::OrbitalMouseController);
// Run start up scripts
runStartupScripts();
// Run start up scripts
runStartupScripts();
// Load a light and a monospaced font
// Load a light and a monospaced font
loadFonts();
LINFO("Initializing GUI");
_gui->initialize();
_gui->initialize();
LINFO("Finished initializing");
return true;
return true;
}
bool OpenSpaceEngine::isInitialized() {
return _engine != nullptr;
return _engine != nullptr;
}
void OpenSpaceEngine::clearAllWindows() {
@@ -416,13 +416,13 @@ void OpenSpaceEngine::clearAllWindows() {
bool OpenSpaceEngine::gatherCommandlineArguments() {
// TODO: Get commandline arguments from all modules
commandlineArgumentPlaceholders.configurationName = "";
commandlineArgumentPlaceholders.configurationName = "";
_commandlineParser->addCommand(std::make_unique<SingleCommand<std::string>>(
&commandlineArgumentPlaceholders.configurationName, "-config", "-c",
"Provides the path to the OpenSpace configuration file"
));
commandlineArgumentPlaceholders.sgctConfigurationName = "";
commandlineArgumentPlaceholders.sgctConfigurationName = "";
_commandlineParser->addCommand(std::make_unique<SingleCommand<std::string>>(
&commandlineArgumentPlaceholders.sgctConfigurationName, "-sgct", "-s",
"Provides the path to the SGCT configuration file, overriding the value set in "
@@ -439,27 +439,27 @@ bool OpenSpaceEngine::gatherCommandlineArguments() {
}
bool OpenSpaceEngine::loadSpiceKernels() {
// Load time kernel
std::string timeKernel;
bool success = configurationManager().getValue(ConfigurationManager::KeySpiceTimeKernel, timeKernel);
// Load time kernel
std::string timeKernel;
bool success = configurationManager().getValue(ConfigurationManager::KeySpiceTimeKernel, timeKernel);
// Move this to configurationmanager::completenesscheck ---abock
if (!success) {
LERROR("Configuration file does not contain a '" << ConfigurationManager::KeySpiceTimeKernel << "'");
return false;
}
SpiceManager::KernelHandle id =
SpiceManager::ref().loadKernel(timeKernel);
if (!success) {
LERROR("Configuration file does not contain a '" << ConfigurationManager::KeySpiceTimeKernel << "'");
return false;
}
SpiceManager::KernelHandle id =
SpiceManager::ref().loadKernel(timeKernel);
// Load SPICE leap second kernel
std::string leapSecondKernel;
success = configurationManager().getValue(ConfigurationManager::KeySpiceLeapsecondKernel, leapSecondKernel);
if (!success) {
// Load SPICE leap second kernel
std::string leapSecondKernel;
success = configurationManager().getValue(ConfigurationManager::KeySpiceLeapsecondKernel, leapSecondKernel);
if (!success) {
// Move this to configurationmanager::completenesscheck ---abock
LERROR("Configuration file does not have a '" << ConfigurationManager::KeySpiceLeapsecondKernel << "'");
return false;
}
id = SpiceManager::ref().loadKernel(std::move(leapSecondKernel));
return true;
LERROR("Configuration file does not have a '" << ConfigurationManager::KeySpiceLeapsecondKernel << "'");
return false;
}
id = SpiceManager::ref().loadKernel(std::move(leapSecondKernel));
return true;
}
void OpenSpaceEngine::runScripts(const ghoul::Dictionary& scripts) {
@@ -500,9 +500,9 @@ void OpenSpaceEngine::runScripts(const ghoul::Dictionary& scripts) {
void OpenSpaceEngine::runStartupScripts() {
ghoul::Dictionary scripts;
configurationManager().getValue(
ConfigurationManager::KeyStartupScript, scripts);
ghoul::Dictionary scripts;
configurationManager().getValue(
ConfigurationManager::KeyStartupScript, scripts);
runScripts(scripts);
}
@@ -546,30 +546,30 @@ void OpenSpaceEngine::loadFonts() {
}
void OpenSpaceEngine::configureLogging() {
if (configurationManager().hasKeyAndValue<std::string>(ConfigurationManager::KeyLogLevel)) {
std::string logLevel;
configurationManager().getValue(ConfigurationManager::KeyLogLevel, logLevel);
if (configurationManager().hasKeyAndValue<std::string>(ConfigurationManager::KeyLogLevel)) {
std::string logLevel;
configurationManager().getValue(ConfigurationManager::KeyLogLevel, logLevel);
bool immediateFlush = false;
configurationManager().getValue(ConfigurationManager::KeyLogImmediateFlush, immediateFlush);
bool immediateFlush = false;
configurationManager().getValue(ConfigurationManager::KeyLogImmediateFlush, immediateFlush);
LogManager::LogLevel level = LogManager::levelFromString(logLevel);
LogManager::deinitialize();
LogManager::LogLevel level = LogManager::levelFromString(logLevel);
LogManager::deinitialize();
using ImmediateFlush = ghoul::logging::LogManager::ImmediateFlush;
LogManager::initialize(
level,
immediateFlush ? ImmediateFlush::Yes : ImmediateFlush::No
);
LogMgr.addLog(std::make_unique<ConsoleLog>());
}
LogMgr.addLog(std::make_unique<ConsoleLog>());
}
if (configurationManager().hasKeyAndValue<ghoul::Dictionary>(ConfigurationManager::KeyLogs)) {
ghoul::Dictionary logs;
configurationManager().getValue(ConfigurationManager::KeyLogs, logs);
if (configurationManager().hasKeyAndValue<ghoul::Dictionary>(ConfigurationManager::KeyLogs)) {
ghoul::Dictionary logs;
configurationManager().getValue(ConfigurationManager::KeyLogs, logs);
for (size_t i = 1; i <= logs.size(); ++i) {
ghoul::Dictionary logInfo;
logs.getValue(std::to_string(i), logInfo);
for (size_t i = 1; i <= logs.size(); ++i) {
ghoul::Dictionary logInfo;
logs.getValue(std::to_string(i), logInfo);
try {
LogMgr.addLog(createLog(logInfo));
@@ -577,8 +577,8 @@ void OpenSpaceEngine::configureLogging() {
catch (const ghoul::RuntimeError& e) {
LERRORC(e.component, e.message);
}
}
}
}
}
}
bool OpenSpaceEngine::initializeGL() {
@@ -592,15 +592,15 @@ bool OpenSpaceEngine::initializeGL() {
LERROR(e.what());
}
LINFO("Finished initializing OpenGL");
return success;
return success;
}
bool OpenSpaceEngine::isMaster(){
return _isMaster;
return _isMaster;
}
void OpenSpaceEngine::setMaster(bool master){
_isMaster = master;
_isMaster = master;
}
double OpenSpaceEngine::runTime(){
@@ -612,24 +612,24 @@ void OpenSpaceEngine::setRunTime(double d){
}
void OpenSpaceEngine::preSynchronization() {
FileSys.triggerFilesystemEvents();
FileSys.triggerFilesystemEvents();
if (_isMaster) {
double dt = _windowWrapper->averageDeltaTime();
Time::ref().advanceTime(dt);
Time::ref().preSynchronization();
Time::ref().advanceTime(dt);
Time::ref().preSynchronization();
_interactionHandler->update(dt);
_scriptEngine->preSynchronization();
_scriptEngine->preSynchronization();
_renderEngine->preSynchronization();
_parallelConnection->preSynchronization();
}
}
void OpenSpaceEngine::postSynchronizationPreDraw() {
Time::ref().postSynchronizationPreDraw();
Time::ref().postSynchronizationPreDraw();
_scriptEngine->postSynchronizationPreDraw();
_scriptEngine->postSynchronizationPreDraw();
_renderEngine->postSynchronizationPreDraw();
if (_isMaster && _gui->isEnabled() && _windowWrapper->isRegularRendering()) {
@@ -639,116 +639,116 @@ void OpenSpaceEngine::postSynchronizationPreDraw() {
double dt = _windowWrapper->averageDeltaTime();
_gui->startFrame(static_cast<float>(dt), glm::vec2(drawBufferResolution), mousePosition, mouseButtons);
}
_gui->startFrame(static_cast<float>(dt), glm::vec2(drawBufferResolution), mousePosition, mouseButtons);
}
}
void OpenSpaceEngine::render(const glm::mat4 &projectionMatrix, const glm::mat4 &viewMatrix) {
_renderEngine->render(projectionMatrix, viewMatrix);
if (_isMaster && _windowWrapper->isRegularRendering()) {
if (_isMaster && _windowWrapper->isRegularRendering()) {
if (_console->isVisible())
_console->render();
if (_gui->isEnabled())
_gui->endFrame();
}
_console->render();
if (_gui->isEnabled())
_gui->endFrame();
}
}
void OpenSpaceEngine::postDraw() {
_renderEngine->postDraw();
_renderEngine->postDraw();
}
void OpenSpaceEngine::keyboardCallback(Key key, KeyModifier mod, KeyAction action) {
if (_isMaster) {
if (_gui->isEnabled()) {
bool isConsumed = _gui->keyCallback(key, mod, action);
if (isConsumed)
return;
}
if (_isMaster) {
if (_gui->isEnabled()) {
bool isConsumed = _gui->keyCallback(key, mod, action);
if (isConsumed)
return;
}
if (key == _console->commandInputButton() && (action == KeyAction::Press || action == KeyAction::Repeat))
_console->toggleVisibility();
_console->toggleVisibility();
if (!_console->isVisible()) {
_interactionHandler->keyboardCallback(key, mod, action);
}
else {
_console->keyboardCallback(key, mod, action);
}
}
if (!_console->isVisible()) {
_interactionHandler->keyboardCallback(key, mod, action);
}
else {
_console->keyboardCallback(key, mod, action);
}
}
}
void OpenSpaceEngine::charCallback(unsigned int codepoint, KeyModifier modifier) {
if (_isMaster) {
if (_gui->isEnabled()) {
const bool isConsumed = _gui->charCallback(codepoint, modifier);
if (isConsumed)
return;
}
if (_isMaster) {
if (_gui->isEnabled()) {
const bool isConsumed = _gui->charCallback(codepoint, modifier);
if (isConsumed)
return;
}
if (_console->isVisible()) {
_console->charCallback(codepoint, modifier);
}
}
if (_console->isVisible()) {
_console->charCallback(codepoint, modifier);
}
}
}
void OpenSpaceEngine::mouseButtonCallback(MouseButton button, MouseAction action) {
if (_isMaster) {
if (_gui->isEnabled()) {
const bool isConsumed = _gui->mouseButtonCallback(button, action);
if (_isMaster) {
if (_gui->isEnabled()) {
const bool isConsumed = _gui->mouseButtonCallback(button, action);
if (isConsumed && action != MouseAction::Release)
return;
}
return;
}
_interactionHandler->mouseButtonCallback(button, action);
}
_interactionHandler->mouseButtonCallback(button, action);
}
}
void OpenSpaceEngine::mousePositionCallback(double x, double y) {
if (_isMaster) {
_interactionHandler->mousePositionCallback(x, y);
}
if (_isMaster) {
_interactionHandler->mousePositionCallback(x, y);
}
}
void OpenSpaceEngine::mouseScrollWheelCallback(double pos) {
if (_isMaster) {
if (_gui->isEnabled()) {
const bool isConsumed = _gui->mouseWheelCallback(pos);
if (isConsumed)
return;
}
if (_isMaster) {
if (_gui->isEnabled()) {
const bool isConsumed = _gui->mouseWheelCallback(pos);
if (isConsumed)
return;
}
_interactionHandler->mouseScrollWheelCallback(pos);
}
_interactionHandler->mouseScrollWheelCallback(pos);
}
}
void OpenSpaceEngine::encode() {
if (_syncBuffer) {
Time::ref().serialize(_syncBuffer.get());
_scriptEngine->serialize(_syncBuffer.get());
_renderEngine->serialize(_syncBuffer.get());
_syncBuffer->write();
}
if (_syncBuffer) {
Time::ref().serialize(_syncBuffer.get());
_scriptEngine->serialize(_syncBuffer.get());
_renderEngine->serialize(_syncBuffer.get());
_syncBuffer->write();
}
_networkEngine->publishStatusMessage();
_networkEngine->sendMessages();
}
void OpenSpaceEngine::decode() {
if (_syncBuffer) {
_syncBuffer->read();
if (_syncBuffer) {
_syncBuffer->read();
Time::ref().deserialize(_syncBuffer.get());
_scriptEngine->deserialize(_syncBuffer.get());
_renderEngine->deserialize(_syncBuffer.get());
}
Time::ref().deserialize(_syncBuffer.get());
_scriptEngine->deserialize(_syncBuffer.get());
_renderEngine->deserialize(_syncBuffer.get());
}
}
void OpenSpaceEngine::externalControlCallback(const char* receivedChars, int size,
int clientId)
{
if (size == 0)
return;
if (size == 0)
return;
_networkEngine->handleMessage(std::string(receivedChars, size));
}
+131 -83
View File
@@ -59,8 +59,8 @@
namespace {
const std::string _loggerCat = "Scene";
const std::string _moduleExtension = ".mod";
const std::string _defaultCommonDirectory = "common";
const std::string _commonModuleToken = "${COMMON_MODULE}";
const std::string _defaultCommonDirectory = "common";
const std::string _commonModuleToken = "${COMMON_MODULE}";
const std::string KeyCamera = "Camera";
const std::string KeyFocusObject = "Focus";
@@ -84,28 +84,30 @@ bool Scene::initialize() {
std::unique_ptr<ProgramObject> tmpProgram;
// fboPassthrough program
// fboPassthrough program
tmpProgram = ProgramObject::Build(
"fboPassProgram",
"${SHADERS}/fboPass_vs.glsl",
"${SHADERS}/fboPass_fs.glsl");
if (!tmpProgram)
"${SHADERS}/fboPass_vs.glsl",
"${SHADERS}/fboPass_fs.glsl");
if (!tmpProgram)
return false;
tmpProgram->setIgnoreSubroutineUniformLocationError(ProgramObject::IgnoreError::Yes);
OsEng.configurationManager().setValue("fboPassProgram", tmpProgram.get());
OsEng.configurationManager().setValue("fboPassProgram", tmpProgram.get());
return true;
}
bool Scene::deinitialize() {
clearSceneGraph();
clearSceneGraph();
return true;
}
//bool ONCE = false;
void Scene::update(const UpdateData& data) {
if (!_sceneGraphToLoad.empty()) {
OsEng.renderEngine().scene()->clearSceneGraph();
if (!_sceneGraphToLoad.empty()) {
OsEng.renderEngine().scene()->clearSceneGraph();
try {
bool success = loadSceneInternal(_sceneGraphToLoad);
_sceneGraphToLoad = "";
@@ -114,7 +116,36 @@ void Scene::update(const UpdateData& data) {
LERROR(e.what());
return;
}
}
}
//if (!ONCE) {
// ghoul::Dictionary d = {
// {"Name", std::string("Earth_Pluto")},
// {"Parent", std::string("PlutoBarycenter")},
// {"Renderable", ghoul::Dictionary{
// {"Type", std::string("RenderablePlanet")},
// {"Frame", std::string("IAU_EARTH")},
// {"Body", std::string("EARTH")},
// {"Geometry", ghoul::Dictionary{
// {"Type", std::string("SimpleSphere")},
// {"Radius", glm::vec2(6.3f, 6.0f)},
// {"Segments", 100.0}
// }},
// {"Textures", ghoul::Dictionary{
// {"Type", std::string("simple")},
// { "Color", std::string("C:/alebo68/OpenSpace/data/scene/earth/textures/earth_bluemarble.jpg") },
// { "Night", std::string("C:/alebo68/OpenSpace/data/scene/earth/textures/earth_night.jpg")}
// }}
// }}
// };
// SceneGraphNode* node = SceneGraphNode::createFromDictionary(d);
// node->setParent(sceneGraphNode(d.value<std::string>("Parent")));
// node->initialize();
// _graph.addSceneGraphNode(node);
// ONCE = true;
//}
for (SceneGraphNode* node : _graph.nodes()) {
try {
node->update(data);
@@ -128,7 +159,7 @@ void Scene::update(const UpdateData& data) {
void Scene::evaluate(Camera* camera) {
for (SceneGraphNode* node : _graph.nodes())
node->evaluate(camera);
//_root->evaluate(camera);
//_root->evaluate(camera);
}
void Scene::render(const RenderData& data, RendererTasks& tasks) {
@@ -138,17 +169,17 @@ void Scene::render(const RenderData& data, RendererTasks& tasks) {
}
void Scene::scheduleLoadSceneFile(const std::string& sceneDescriptionFilePath) {
_sceneGraphToLoad = sceneDescriptionFilePath;
_sceneGraphToLoad = sceneDescriptionFilePath;
}
void Scene::clearSceneGraph() {
// deallocate the scene graph. Recursive deallocation will occur
// deallocate the scene graph. Recursive deallocation will occur
_graph.clear();
//if (_root) {
// _root->deinitialize();
// delete _root;
// _root = nullptr;
//}
//if (_root) {
// _root->deinitialize();
// delete _root;
// _root = nullptr;
//}
// _nodes.erase(_nodes.begin(), _nodes.end());
// _allNodes.erase(_allNodes.begin(), _allNodes.end());
@@ -205,9 +236,9 @@ bool Scene::loadSceneInternal(const std::string& sceneDescriptionFilePath) {
}
// update the position of all nodes
// TODO need to check this; unnecessary? (ab)
for (SceneGraphNode* node : _graph.nodes()) {
node->update({ Time::ref().currentTime() });
// TODO need to check this; unnecessary? (ab)
for (SceneGraphNode* node : _graph.nodes()) {
node->update({ Time::ref().currentTime() });
}
for (auto it = _graph.nodes().rbegin(); it != _graph.nodes().rend(); ++it)
@@ -218,7 +249,7 @@ bool Scene::loadSceneInternal(const std::string& sceneDescriptionFilePath) {
//_root->calculateBoundingSphere();
// set the camera position
Camera* c = OsEng.ref().renderEngine().camera();
Camera* c = OsEng.ref().renderEngine().camera();
//auto focusIterator = _allNodes.find(_focus);
auto focusIterator = std::find_if(
_graph.nodes().begin(),
@@ -228,8 +259,8 @@ bool Scene::loadSceneInternal(const std::string& sceneDescriptionFilePath) {
}
);
glm::vec2 cameraScaling(1);
psc cameraPosition(0,0,1,0);
glm::vec2 cameraScaling(1);
psc cameraPosition(0,0,1,0);
//if (_focus->)
if (focusIterator != _graph.nodes().end()) {
@@ -241,26 +272,26 @@ bool Scene::loadSceneInternal(const std::string& sceneDescriptionFilePath) {
// TODO: Set distance and camera direction in some more smart way
// TODO: Set scaling dependent on the position and distance
// set position for camera
const PowerScaledScalar bound = focusNode->calculateBoundingSphere();
const PowerScaledScalar bound = focusNode->calculateBoundingSphere();
// this part is full of magic!
glm::vec2 boundf = bound.vec2();
glm::vec2 boundf = bound.vec2();
//glm::vec2 scaling{1.0f, -boundf[1]};
cameraScaling = glm::vec2(1.f, -boundf[1]);
cameraScaling = glm::vec2(1.f, -boundf[1]);
boundf[0] *= 5.0f;
//psc cameraPosition = focusNode->position();
//psc cameraPosition = focusNode->position();
//cameraPosition += psc(glm::vec4(0.f, 0.f, boundf));
//cameraPosition = psc(glm::vec4(0.f, 0.f, 1.f,0.f));
//cameraPosition = psc(glm::vec4(0.f, 0.f, 1.f,0.f));
cameraPosition = focusNode->position();
cameraPosition += psc(glm::vec4(0.f, 0.f, boundf));
//why this line? (JK)
//cameraPosition = psc(glm::vec4(0.f, 0.f, 1.f, 0.f));
cameraPosition = focusNode->position();
cameraPosition += psc(glm::vec4(0.f, 0.f, boundf));
//why this line? (JK)
//cameraPosition = psc(glm::vec4(0.f, 0.f, 1.f, 0.f));
//c->setPosition(cameraPosition);
//c->setPosition(cameraPosition);
// c->setCameraDirection(glm::vec3(0, 0, -1));
// c->setScaling(scaling);
@@ -270,7 +301,7 @@ bool Scene::loadSceneInternal(const std::string& sceneDescriptionFilePath) {
else
OsEng.interactionHandler().setFocusNode(_graph.rootNode());
glm::vec4 position;
glm::vec4 position;
if (cameraDictionary.hasKeyAndValue<glm::vec4>(KeyPositionObject)) {
try {
position = cameraDictionary.value<glm::vec4>(KeyPositionObject);
@@ -286,32 +317,32 @@ bool Scene::loadSceneInternal(const std::string& sceneDescriptionFilePath) {
catch (const ghoul::Dictionary::DictionaryError& e) {
LERROR("Error loading Camera location: " << e.what());
}
}
}
// the camera position
const SceneGraphNode* fn = OsEng.interactionHandler().focusNode();
// the camera position
const SceneGraphNode* fn = OsEng.interactionHandler().focusNode();
// Check crash for when fn == nullptr
glm::mat4 la = glm::lookAt(cameraPosition.vec3(), fn->worldPosition().vec3(), c->lookUpVector());
glm::mat4 la = glm::lookAt(cameraPosition.vec3(), fn->worldPosition().vec3(), c->lookUpVector());
c->setRotation(la);
c->setPosition(cameraPosition);
c->setScaling(cameraScaling);
c->setRotation(la);
c->setPosition(cameraPosition);
c->setScaling(cameraScaling);
glm::vec3 viewOffset;
if (cameraDictionary.hasKey(KeyViewOffset)
&& cameraDictionary.getValue(KeyViewOffset, viewOffset)) {
glm::quat rot = glm::quat(viewOffset);
c->rotate(rot);
}
glm::vec3 viewOffset;
if (cameraDictionary.hasKey(KeyViewOffset)
&& cameraDictionary.getValue(KeyViewOffset, viewOffset)) {
glm::quat rot = glm::quat(viewOffset);
c->rotate(rot);
}
for (SceneGraphNode* node : _graph.nodes()) {
std::vector<properties::Property*> properties = node->propertiesRecursive();
for (properties::Property* p : properties) {
for (SceneGraphNode* node : _graph.nodes()) {
std::vector<properties::Property*> properties = node->propertiesRecursive();
for (properties::Property* p : properties) {
OsEng.gui()._property.registerProperty(p);
}
}
}
}
// If a LuaDocumentationFile was specified, generate it now
const bool hasType = OsEng.configurationManager().hasKey(ConfigurationManager::KeyPropertyDocumentationType);
@@ -490,7 +521,11 @@ SceneGraphNode* Scene::sceneGraphNode(const std::string& name) const {
}
std::vector<SceneGraphNode*> Scene::allSceneGraphNodes() {
return _graph.nodes();
return _graph.nodes();
}
SceneGraph& Scene::sceneGraph() {
return _graph;
}
void Scene::writePropertyDocumentation(const std::string& filename, const std::string& type) {
@@ -521,34 +556,47 @@ void Scene::writePropertyDocumentation(const std::string& filename, const std::s
}
scripting::ScriptEngine::LuaLibrary Scene::luaLibrary() {
return {
"",
{
{
"setPropertyValue",
&luascriptfunctions::property_setValue,
"string, *",
"Sets a property identified by the URI in "
"the first argument. The second argument can be any type, but it has to "
" agree with the type that the property expects",
return {
"",
{
{
"setPropertyValue",
&luascriptfunctions::property_setValue,
"string, *",
"Sets a property identified by the URI in "
"the first argument. The second argument can be any type, but it has to "
" agree with the type that the property expects",
true
},
{
"getPropertyValue",
&luascriptfunctions::property_getValue,
"string",
"Returns the value the property, identified by "
"the provided URI."
},
{
"loadScene",
&luascriptfunctions::loadScene,
"string",
"Loads the scene found at the file passed as an "
"argument. If a scene is already loaded, it is unloaded first"
}
}
};
},
{
"getPropertyValue",
&luascriptfunctions::property_getValue,
"string",
"Returns the value the property, identified by "
"the provided URI."
},
{
"loadScene",
&luascriptfunctions::loadScene,
"string",
"Loads the scene found at the file passed as an "
"argument. If a scene is already loaded, it is unloaded first"
},
{
"addSceneGraphNode",
&luascriptfunctions::addSceneGraphNode,
"table",
"Loads the SceneGraphNode described in the table and adds it to the "
"SceneGraph"
},
{
"removeSceneGraphNode",
&luascriptfunctions::removeSceneGraphNode,
"string",
"Removes the SceneGraphNode identified by name"
}
}
};
}
} // namespace openspace
+72 -19
View File
@@ -38,34 +38,34 @@ int property_setValue(lua_State* L) {
using ghoul::lua::errorLocation;
using ghoul::lua::luaTypeToString;
int nArguments = lua_gettop(L);
int nArguments = lua_gettop(L);
SCRIPT_CHECK_ARGUMENTS(L, 2, nArguments);
std::string uri = luaL_checkstring(L, -2);
const int type = lua_type(L, -1);
std::string uri = luaL_checkstring(L, -2);
const int type = lua_type(L, -1);
openspace::properties::Property* prop = property(uri);
if (!prop) {
openspace::properties::Property* prop = property(uri);
if (!prop) {
LERROR(errorLocation(L) << "Property with URI '" << uri << "' was not found");
return 0;
}
if (type != prop->typeLua()) {
if (type != prop->typeLua()) {
LERROR(errorLocation(L) << "Property '" << uri <<
"' does not accept input of type '" << luaTypeToString(type) <<
"'. Requested type: '" << luaTypeToString(prop->typeLua()) << "'");
return 0;
}
else{
prop->setLuaValue(L);
prop->setLuaValue(L);
//ensure properties are synced over parallel connection
std::string value;
prop->getStringValue(value);
OsEng.parallelConnection().scriptMessage(prop->fullyQualifiedIdentifier(), value);
}
return 0;
return 0;
}
/**
@@ -78,19 +78,19 @@ int property_getValue(lua_State* L) {
static const std::string _loggerCat = "property_getValue";
using ghoul::lua::errorLocation;
int nArguments = lua_gettop(L);
int nArguments = lua_gettop(L);
SCRIPT_CHECK_ARGUMENTS(L, 1, nArguments);
std::string uri = luaL_checkstring(L, -1);
std::string uri = luaL_checkstring(L, -1);
openspace::properties::Property* prop = property(uri);
if (!prop) {
openspace::properties::Property* prop = property(uri);
if (!prop) {
LERROR(errorLocation(L) << "Property with URL '" << uri << "' was not found");
return 0;
}
else
prop->getLuaValue(L);
return 1;
else
prop->getLuaValue(L);
return 1;
}
/**
@@ -102,14 +102,67 @@ int property_getValue(lua_State* L) {
int loadScene(lua_State* L) {
static const std::string _loggerCat = "loadScene";
int nArguments = lua_gettop(L);
int nArguments = lua_gettop(L);
SCRIPT_CHECK_ARGUMENTS(L, 1, nArguments);
std::string sceneFile = luaL_checkstring(L, -1);
std::string sceneFile = luaL_checkstring(L, -1);
OsEng.renderEngine().scene()->scheduleLoadSceneFile(sceneFile);
OsEng.renderEngine().scene()->scheduleLoadSceneFile(sceneFile);
return 0;
return 0;
}
int addSceneGraphNode(lua_State* L) {
static const std::string _loggerCat = "addSceneGraphNode";
using ghoul::lua::errorLocation;
int nArguments = lua_gettop(L);
SCRIPT_CHECK_ARGUMENTS(L, 1, nArguments);
ghoul::Dictionary d;
try {
ghoul::lua::luaDictionaryFromState(L, d);
}
catch (const ghoul::lua::LuaFormatException& e) {
LERROR(e.what());
return 0;
}
SceneGraphNode* node = SceneGraphNode::createFromDictionary(d);
std::string parent = d.value<std::string>(SceneGraphNode::KeyParentName);
SceneGraphNode* parentNode = OsEng.renderEngine().scene()->sceneGraphNode(parent);
if (!parentNode) {
LERROR(errorLocation(L) << "Could not find parent node '" << parent << "'");
return 0;
}
node->setParent(parentNode);
node->initialize();
OsEng.renderEngine().scene()->sceneGraph().addSceneGraphNode(node);
return 1;
}
int removeSceneGraphNode(lua_State* L) {
static const std::string _loggerCat = "removeSceneGraphNode";
using ghoul::lua::errorLocation;
int nArguments = lua_gettop(L);
SCRIPT_CHECK_ARGUMENTS(L, 1, nArguments);
std::string nodeName = luaL_checkstring(L, -1);
SceneGraphNode* node = OsEng.renderEngine().scene()->sceneGraphNode(nodeName);
if (!node) {
LERROR(errorLocation(L) << "Could not find node '" << nodeName << "'");
return 0;
}
OsEng.renderEngine().scene()->sceneGraph().removeSceneGraphNode(node);
node->deinitialize();
delete node;
return 1;
}
} // namespace luascriptfunctions
+72 -3
View File
@@ -27,12 +27,14 @@
#include <openspace/engine/openspaceengine.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/interaction/interactionhandler.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/lua/lua_helper.h>
#include <stack>
#include <unordered_map>
#ifdef _MSC_VER
#ifdef OPENSPACE_ENABLE_VLD
@@ -43,8 +45,8 @@
namespace {
const std::string _loggerCat = "SceneGraph";
const std::string _moduleExtension = ".mod";
const std::string _defaultCommonDirectory = "common";
const std::string _commonModuleToken = "${COMMON_MODULE}";
const std::string _defaultCommonDirectory = "common";
const std::string _commonModuleToken = "${COMMON_MODULE}";
const std::string KeyPathScene = "ScenePath";
const std::string KeyModules = "Modules";
@@ -352,11 +354,78 @@ bool SceneGraph::sortTopologically() {
}
bool SceneGraph::addSceneGraphNode(SceneGraphNode* node) {
// @TODO rework this ---abock
ghoul_assert(node, "Node must not be nullptr");
SceneGraphNodeInternal* internalNode = new SceneGraphNodeInternal;
internalNode->node = node;
auto it = std::find_if(
_nodes.begin(),
_nodes.end(),
[node](SceneGraphNodeInternal* i) {
return i->node == node->parent();
}
);
if (it == _nodes.end()) {
LERROR("Parent node was not found");
delete internalNode;
return false;
}
(*it)->incomingEdges.push_back(internalNode);
internalNode->outgoingEdges.push_back(*it);
_nodes.push_back(internalNode);
sortTopologically();
return true;
}
bool SceneGraph::removeSceneGraphNode(SceneGraphNode* node) {
// How to handle orphaned nodes? (reparent to root?) --- abock
// @TODO rework this ---abock
ghoul_assert(node, "Node must not be nullptr");
auto it = std::find_if(
_nodes.begin(),
_nodes.end(),
[node](SceneGraphNodeInternal* i) {
return i->node == node;
}
);
if (it == _nodes.end()) {
LERROR("The node '" << node->name() << "' did not exist in the scenegraph");
return false;
}
// Remove internal node from the list of nodes
SceneGraphNodeInternal* internalNode = *it;
_nodes.erase(it);
if (OsEng.interactionHandler().focusNode() == node)
OsEng.interactionHandler().setFocusNode(node->parent());
sortTopologically();
#if 0
SceneGraphNodeInternal* parentInternalNode = nodeByName(node->parent()->name());
ghoul_assert(parentInternalNode, "Could not find internal parent node");
// Reparent its children to its parent
for (SceneGraphNode* c : node->children())
c->setParent(node->parent());
// Reset the dependencies accordingly
// VERY untested ---abock
for (SceneGraphNodeInternal* c : internalNode->incomingEdges) {
parentInternalNode->outgoingEdges.insert(parentInternalNode->outgoingEdges.end(), c->outgoingEdges.begin(), c->outgoingEdges.end());
parentInternalNode->incomingEdges.insert(parentInternalNode->incomingEdges.end(), c->incomingEdges.begin(), c->incomingEdges.end());
}
#endif
return true;
}
+65 -66
View File
@@ -71,7 +71,7 @@ SceneGraphNode* SceneGraphNode::createFromDictionary(const ghoul::Dictionary& di
ghoul::Dictionary renderableDictionary;
dictionary.getValue(KeyRenderable, renderableDictionary);
renderableDictionary.setValue(KeyName, name);
renderableDictionary.setValue(KeyName, name);
result->_renderable = Renderable::createFromDictionary(renderableDictionary);
if (result->_renderable == nullptr) {
@@ -80,7 +80,7 @@ SceneGraphNode* SceneGraphNode::createFromDictionary(const ghoul::Dictionary& di
delete result;
return nullptr;
}
result->addPropertySubOwner(result->_renderable);
result->addPropertySubOwner(result->_renderable);
LDEBUG("Successfully create renderable for '" << result->name() << "'");
}
@@ -95,7 +95,7 @@ SceneGraphNode* SceneGraphNode::createFromDictionary(const ghoul::Dictionary& di
delete result;
return nullptr;
}
//result->addPropertySubOwner(result->_ephemeris);
//result->addPropertySubOwner(result->_ephemeris);
LDEBUG("Successfully create ephemeris for '" << result->name() << "'");
}
@@ -147,18 +147,18 @@ bool SceneGraphNode::deinitialize() {
LDEBUG("Deinitialize: " << name());
if (_renderable) {
_renderable->deinitialize();
_renderable->deinitialize();
delete _renderable;
_renderable = nullptr;
}
_renderable = nullptr;
}
delete _ephemeris;
_ephemeris = nullptr;
// for (SceneGraphNode* child : _children) {
// child->deinitialize();
// delete child;
//}
// child->deinitialize();
// delete child;
//}
_children.clear();
// reset variables
@@ -171,35 +171,35 @@ bool SceneGraphNode::deinitialize() {
}
void SceneGraphNode::update(const UpdateData& data) {
if (_ephemeris) {
if (data.doPerformanceMeasurement) {
glFinish();
if (_ephemeris) {
if (data.doPerformanceMeasurement) {
glFinish();
auto start = std::chrono::high_resolution_clock::now();
_ephemeris->update(data);
_ephemeris->update(data);
glFinish();
auto end = std::chrono::high_resolution_clock::now();
_performanceRecord.updateTimeEphemeris = (end - start).count();
}
else
_ephemeris->update(data);
}
glFinish();
auto end = std::chrono::high_resolution_clock::now();
_performanceRecord.updateTimeEphemeris = (end - start).count();
}
else
_ephemeris->update(data);
}
if (_renderable && _renderable->isReady()) {
if (data.doPerformanceMeasurement) {
glFinish();
auto start = std::chrono::high_resolution_clock::now();
if (_renderable && _renderable->isReady()) {
if (data.doPerformanceMeasurement) {
glFinish();
auto start = std::chrono::high_resolution_clock::now();
_renderable->update(data);
_renderable->update(data);
glFinish();
auto end = std::chrono::high_resolution_clock::now();
_performanceRecord.updateTimeRenderable = (end - start).count();
}
else
_renderable->update(data);
}
glFinish();
auto end = std::chrono::high_resolution_clock::now();
_performanceRecord.updateTimeRenderable = (end - start).count();
}
else
_renderable->update(data);
}
}
void SceneGraphNode::evaluate(const Camera* camera, const psc& parentPosition) {
@@ -222,7 +222,7 @@ void SceneGraphNode::evaluate(const Camera* camera, const psc& parentPosition) {
return;
}
}
*/
*/
#endif
// inside boudningsphere or parts of the sphere is visible, individual
@@ -245,22 +245,22 @@ void SceneGraphNode::evaluate(const Camera* camera, const psc& parentPosition) {
void SceneGraphNode::render(const RenderData& data, RendererTasks& tasks) {
const psc thisPosition = worldPosition();
RenderData newData = {data.camera, thisPosition, data.doPerformanceMeasurement};
RenderData newData = {data.camera, thisPosition, data.doPerformanceMeasurement};
_performanceRecord.renderTime = 0;
_performanceRecord.renderTime = 0;
if (_renderableVisible && _renderable->isVisible() && _renderable->isReady() && _renderable->isEnabled()) {
if (data.doPerformanceMeasurement) {
glFinish();
auto start = std::chrono::high_resolution_clock::now();
if (data.doPerformanceMeasurement) {
glFinish();
auto start = std::chrono::high_resolution_clock::now();
_renderable->render(newData, tasks);
_renderable->render(newData, tasks);
glFinish();
auto end = std::chrono::high_resolution_clock::now();
_performanceRecord.renderTime = (end - start).count();
}
else
_renderable->render(newData, tasks);
glFinish();
auto end = std::chrono::high_resolution_clock::now();
_performanceRecord.renderTime = (end - start).count();
}
else
_renderable->render(newData, tasks);
}
// evaluate all the children, tail-recursive function(?)
@@ -278,8 +278,7 @@ void SceneGraphNode::render(const RenderData& data, RendererTasks& tasks) {
// _children.push_back(child);
//}
void SceneGraphNode::setParent(SceneGraphNode* parent)
{
void SceneGraphNode::setParent(SceneGraphNode* parent) {
_parent = parent;
}
@@ -326,8 +325,8 @@ const std::vector<SceneGraphNode*>& SceneGraphNode::children() const{
// bounding sphere
PowerScaledScalar SceneGraphNode::calculateBoundingSphere(){
// set the bounding sphere to 0.0
_boundingSphere = 0.0;
_boundingSphere = 0.0;
if (!_children.empty()) { // node
PowerScaledScalar maxChild;
@@ -338,7 +337,7 @@ PowerScaledScalar SceneGraphNode::calculateBoundingSphere(){
// position
//PowerScaledScalar child = _children.at(i)->position().length()
// + _children.at(i)->calculateBoundingSphere();
PowerScaledScalar child = _children.at(i)->calculateBoundingSphere();
PowerScaledScalar child = _children.at(i)->calculateBoundingSphere();
if (child > maxChild) {
maxChild = child;
}
@@ -352,8 +351,8 @@ PowerScaledScalar SceneGraphNode::calculateBoundingSphere(){
if(renderableBS > _boundingSphere)
_boundingSphere = renderableBS;
}
//LINFO("Bounding Sphere of '" << name() << "': " << _boundingSphere);
//LINFO("Bounding Sphere of '" << name() << "': " << _boundingSphere);
return _boundingSphere;
}
@@ -372,7 +371,7 @@ const Renderable* SceneGraphNode::renderable() const
}
Renderable* SceneGraphNode::renderable() {
return _renderable;
return _renderable;
}
// private helper methods
@@ -422,21 +421,21 @@ SceneGraphNode* SceneGraphNode::childNode(const std::string& name)
void SceneGraphNode::updateCamera(Camera* camera) const{
psc origin = worldPosition();
//int i = 0;
// the camera position
psc relative = camera->position();
psc focus = camera->focusPosition();
psc relative_focus = relative - focus;
psc origin = worldPosition();
//int i = 0;
// the camera position
psc relative = camera->position();
psc focus = camera->focusPosition();
psc relative_focus = relative - focus;
psc target = origin + relative_focus;
camera->setPosition(target);
camera->setFocusPosition(origin);
psc target = origin + relative_focus;
camera->setPosition(target);
camera->setFocusPosition(origin);
//printf("target: %f, %f, %f, %f\n", target.vec4().x, target.vec4().y, target.vec4().z, target.vec4().w);
//printf("target: %f, %f, %f, %f\n", target.vec4().x, target.vec4().y, target.vec4().z, target.vec4().w);
}
} // namespace openspace