Merged with feature/ABuffer

This commit is contained in:
Hans-Christian Helltegen
2014-06-27 15:49:49 -04:00
54 changed files with 2550 additions and 585 deletions

3
.gitignore vendored
View File

@@ -4,6 +4,9 @@ ext/SGCT
.DS_Store
*.swp
# generated glsl files
*.gglsl
# CMake stuff
CMakeCache.txt
CMakeFiles

View File

@@ -45,7 +45,7 @@ raycaster_stepsize 0.005
raycaster_intensity 1.0
# Animation speed
animator_refresh_interval 0.05
animator_refresh_interval 0.5
# Various paths
raycaster_kernel_filename ${KERNELS}/RaycasterTSP.cl

View File

@@ -6,7 +6,8 @@
<Node address="localhost" port="20401">
<Window fullScreen="false">
<!-- 16:9 aspect ratio -->
<Size x="640" y="360" />
<Size x="1280" y="720" />
<!--<Size x="640" y="310" />-->
<Pos x="500" y="50.0" />
<Viewport>
<Pos x="0.0" y="0.0" />

44
config/sgct/two_nodes.xml Normal file
View File

@@ -0,0 +1,44 @@
<?xml version="1.0" ?>
<Cluster masterAddress="127.0.0.1">
<Node address="127.0.0.1" port="20401">
<Window fullScreen="false">
<Pos x="0" y="300" />
<!-- 16:9 aspect ratio -->
<Size x="640" y="360" />
<Viewport>
<Pos x="0.0" y="0.0" />
<Size x="1.0" y="1.0" />
<Viewplane>
<!-- Lower left -->
<Pos x="-1.778" y="-1.0" z="0.0" />
<!-- Upper left -->
<Pos x="-1.778" y="1.0" z="0.0" />
<!-- Upper right -->
<Pos x="1.778" y="1.0" z="0.0" />
</Viewplane>
</Viewport>
</Window>
</Node>
<Node address="127.0.0.2" port="20402">
<Window fullScreen="false">
<Pos x="640" y="300" />
<!-- 16:9 aspect ratio -->
<Size x="640" y="360" />
<Viewport>
<Pos x="0.0" y="0.0" />
<Size x="1.0" y="1.0" />
<Viewplane>
<!-- Lower left -->
<Pos x="-1.778" y="-1.0" z="0.0" />
<!-- Upper left -->
<Pos x="-1.778" y="1.0" z="0.0" />
<!-- Upper right -->
<Pos x="1.778" y="1.0" z="0.0" />
</Viewplane>
</Viewport>
</Window>
</Node>
<User eyeSeparation="0.065">
<Pos x="0.0" y="0.0" z="4.0" />
</User>
</Cluster>

View File

@@ -0,0 +1,90 @@
/*****************************************************************************************
* *
* 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 __ABUFFER_H__
#define __ABUFFER_H__
#include <openspace/abuffer/abuffer_i.h>
#include <ghoul/opengl/ghoul_gl.h>
#include <ghoul/glm.h>
#include <ghoul/opengl/programobject.h>
#include <ghoul/filesystem/file.h>
namespace ghoul {
namespace opengl {
class Texture;
}
}
namespace openspace {
class ABuffer: public ABuffer_I {
public:
ABuffer();
virtual ~ABuffer();
virtual void resolve();
void addVolume(const std::string& tag,ghoul::opengl::Texture* volume);
void addTransferFunction(const std::string& tag,ghoul::opengl::Texture* transferFunction);
int addSamplerfile(const std::string& filename);
protected:
virtual std::string settings() = 0;
bool initializeABuffer();
void generateShaderSource();
bool updateShader();
std::string openspaceHeaders();
std::string openspaceSamplerCalls();
std::string openspaceSamplers();
unsigned int _width, _height, _totalPixels;
private:
GLuint _screenQuad;
bool _validShader;
std::string _fragmentShaderPath;
ghoul::filesystem::File* _fragmentShaderFile;
ghoul::opengl::ProgramObject* _resolveShader;
std::vector<std::pair<std::string,ghoul::opengl::Texture*> > _volumes;
std::vector<std::pair<std::string,ghoul::opengl::Texture*> > _transferFunctions;
std::vector<ghoul::filesystem::File*> _samplerFiles;
std::vector<std::string> _samplers;
// Development functionality to update shader for changes in several files
std::vector<ghoul::filesystem::File*> _shaderFiles;
}; // ABuffer
} // openspace
#endif // __ABUFFER_H__

View File

@@ -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 __ABUFFERSINGLELINKED_H__
#define __ABUFFERSINGLELINKED_H__
#include <openspace/abuffer/abuffer.h>
namespace openspace {
class ABufferSingleLinked: public ABuffer {
public:
ABufferSingleLinked();
virtual ~ABufferSingleLinked();
virtual bool initialize();
virtual void clear();
virtual void preRender();
virtual void postRender();
virtual std::string settings();
private:
GLuint *_data;
GLuint _anchorPointerTexture;
GLuint _anchorPointerTextureInitializer;
GLuint _atomicCounterBuffer;
GLuint _fragmentBuffer;
GLuint _fragmentTexture;
}; // ABuffer_I
} // openspace
#endif // __ABUFFERSINGLELINKED_H__

View File

@@ -0,0 +1,43 @@
/*****************************************************************************************
* *
* 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 __ABUFFER_I_H__
#define __ABUFFER_I_H__
namespace openspace {
class ABuffer_I {
public:
virtual ~ABuffer_I() {};
virtual bool initialize() = 0;
virtual void clear() = 0;
virtual void preRender() = 0;
virtual void postRender() = 0;
virtual void resolve() = 0;
}; // ABuffer_I
} // openspace
#endif // __ABUFFER_I_H__

View File

@@ -34,6 +34,8 @@
#include <ghoul/opencl/clprogram.h>
#include <ghoul/opencl/clkernel.h>
//#define FLARE_ONLY
#include <openspace/flare/flare.h>
namespace openspace {
@@ -81,6 +83,9 @@ private:
ghoul::Dictionary* _configurationManager;
InteractionHandler* _interactionHandler;
RenderEngine* _renderEngine;
#ifdef FLARE_ONLY
Flare* _flare;
#endif
// ScriptEngine* _scriptEngine;
ghoul::opencl::CLContext _context;

View File

@@ -53,6 +53,7 @@ public:
void keyboard(int key, int action);
void mouse(int button, int action);
void preSync();
void postSyncPreDraw();
void postDraw();
void encode();
void decode();

View File

@@ -32,12 +32,6 @@
#include <ghoul/opengl/programobject.h>
#include <ghoul/filesystem/file.h>
#ifdef __APPLE__
#include <memory>
#else
#include <mutex>
#endif
namespace openspace {
class RenderableFieldlines : public Renderable {
@@ -61,8 +55,6 @@ private:
ghoul::opengl::ProgramObject *_fieldlinesProgram;
GLuint _VAO, _seedpointVAO;
std::mutex* _shaderMutex;
ghoul::filesystem::File* _vertexSourceFile;
ghoul::filesystem::File* _fragmentSourceFile;
@@ -70,6 +62,7 @@ private:
std::vector<GLsizei> _lineCount;
bool _programUpdateOnSave;
bool _update;
void safeShaderCompilation();
};

View File

@@ -27,7 +27,6 @@
// open space includes
#include <openspace/rendering/renderablevolume.h>
#include <openspace/rendering/volumeraycasterbox.h>
// ghoul includes
#include <ghoul/opengl/programobject.h>
@@ -36,11 +35,9 @@
#include <ghoul/io/rawvolumereader.h>
#include <ghoul/filesystem/file.h>
#ifdef __APPLE__
#include <memory>
#else
#include <mutex>
#endif
namespace sgct_utils {
class SGCTBox;
}
namespace openspace {
@@ -58,22 +55,24 @@ public:
private:
ghoul::Dictionary _hintsDictionary;
std::string _filename;
float _stepSize;
ghoul::opengl::Texture* _volume;
ghoul::opengl::ProgramObject* _twopassProgram;
GLuint _screenQuad;
VolumeRaycasterBox* _colorBoxRenderer;
std::string _filename;
std::string _transferFunctionPath;
std::string _samplerFilename;
ghoul::filesystem::File* _transferFunctionFile;
ghoul::opengl::Texture* _volume;
ghoul::opengl::Texture* _transferFunction;
GLuint _boxArray;
ghoul::opengl::ProgramObject *_boxProgram;
sgct_utils::SGCTBox* _box;
glm::vec3 _boxScaling;
GLint _MVPLocation, _modelTransformLocation, _typeLocation;
std::mutex* _shaderMutex;
ghoul::filesystem::File* _vertexSourceFile;
ghoul::filesystem::File* _fragmentSourceFile;
bool _programUpdateOnSave;
void safeShaderCompilation();
bool _updateTransferfunction;
int _id;
};
} // namespace openspace

View File

@@ -30,6 +30,8 @@
#include <memory>
#include <string>
#include <openspace/abuffer/abuffer.h>
namespace openspace {
class Camera;
@@ -45,6 +47,7 @@ public:
SceneGraph* sceneGraph();
Camera* camera() const;
ABuffer* abuffer() const;
// sgct wrapped functions
bool initializeGL();
@@ -58,6 +61,8 @@ public:
private:
Camera* _mainCamera;
SceneGraph* _sceneGraph;
ABuffer* _abuffer;
};
} // namespace openspace

View File

@@ -45,7 +45,7 @@ public:
VolumeRaycasterBox();
~VolumeRaycasterBox();
bool initialize();
void render(const glm::mat4& MVP);
void render(const glm::mat4& MVP, const glm::mat4& transform = glm::mat4(1.0), int type = 0);
ghoul::opengl::Texture* backFace();
ghoul::opengl::Texture* frontFace();
@@ -56,7 +56,7 @@ private:
ghoul::opengl::Texture *_backTexture, *_frontTexture;
ghoul::opengl::ProgramObject *_boxProgram;
sgct_utils::SGCTBox* _boundingBox;
GLint _MVPLocation;
GLint _MVPLocation, _modelTransformLocation, _typeLocation;
glm::size2_t _dimensions;
};

View File

@@ -70,6 +70,7 @@ public:
// bounding sphere
PowerScaledScalar calculateBoundingSphere();
PowerScaledScalar boundingSphere() const;
SceneGraphNode* get(const std::string& name);

View File

@@ -10,6 +10,7 @@ return {
CONFIG = "${BASE_PATH}/config"
},
SGCTConfig = "${SGCT}/single.xml",
--sgctConfig = "${SGCT}/single_sbs_stereo.xml",
--SGCTConfig = "${SGCT}/two_nodes.xml",
--SGCTConfig = "${SGCT}/single_sbs_stereo.xml",
Scene = "${SCENEPATH}/default.scene"
}

View File

@@ -0,0 +1,63 @@
/*****************************************************************************************
* *
* 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. *
****************************************************************************************/
layout (binding = 0, r32ui) uniform uimage2D anchorPointerTexture;
layout (binding = 1, rgba32ui) uniform uimageBuffer fragmentTexture;
layout (binding = 0, offset = 0) uniform atomic_uint atomicCounterBuffer;
ABufferStruct_t createGeometryFragment(vec4 fragColor, vec4 position = vec4(0), float z = gl_FragCoord.z) {
ABufferStruct_t frag;
_col_(frag, fragColor);
_z_(frag, z);
_type_(frag, 0);
_pos_(frag, position);
return frag;
}
void addToBuffer(ABufferStruct_t frag) {
uint index = atomicCounterIncrement(atomicCounterBuffer);
index *= 2;
uint old_head = imageAtomicExchange(anchorPointerTexture, ivec2(gl_FragCoord.xy), index);
_next_(frag,old_head);
uvec4 p1 = uvec4(frag.z, frag.id, frag.rg, frag.ba);
uvec4 p2 = uvec4(floatBitsToUint(frag.position.x),floatBitsToUint(frag.position.y),floatBitsToUint(frag.position.z),floatBitsToUint(frag.position.w));
imageStore(fragmentTexture, int(index), p1);
imageStore(fragmentTexture, int(index+1), p2);
}
ABufferStruct_t loadFromBuffer(uint id) {
uvec4 u1 = imageLoad(fragmentTexture, int(id));
uvec4 u2 = imageLoad(fragmentTexture, int(id+1));
vec4 position = vec4( uintBitsToFloat(u2.x),
uintBitsToFloat(u2.y),
uintBitsToFloat(u2.z),
uintBitsToFloat(u2.w));
return ABufferStruct_t(u1.x, u1.y, u1.z, u1.w, position);
}

View File

@@ -0,0 +1,258 @@
/*****************************************************************************************
* *
* 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. *
****************************************************************************************/
#version 430
// ================================================================================
// Settings
// ================================================================================
#pragma openspace insert SETTINGS
#define LOOP_LIMIT 800
#define MAX_FRAGMENTS 16
#define SHOWFUNC
const float stepSize = 0.01;
const float samplingRate = 1.0;
uniform int SCREEN_WIDTH;
uniform int SCREEN_HEIGHT;
uniform float ALPHA_LIMIT = 0.98;
in vec2 texCoord;
out vec4 color;
// ================================================================================
// Headers,
// volume and transferfunctions uniforms
// ================================================================================
#pragma openspace insert HEADERS
// ================================================================================
// The ABuffer specific includes and definitions
// ================================================================================
#include "abufferStruct.hglsl"
ABufferStruct_t fragments[MAX_FRAGMENTS];
vec3 volume_direction[MAX_VOLUMES];
float volume_length[MAX_VOLUMES];
vec2 volume_zlength[MAX_VOLUMES];
// float volume_zlength[MAX_VOLUMES];
vec3 volume_position[MAX_VOLUMES];
#include "abufferSort.hglsl"
// ================================================================================
// Blend functions
// ================================================================================
vec4 blend(vec4 src, vec4 dst) {
vec4 o;
o.a = src.a + dst.a * (1.0f - src.a);
o.rgb = (src.rgb*src.a + dst.rgb*dst.a* (1.0f - src.a));
return o;
//return mix(src, dst, dst.a*(1.0f - src.a));
}
void blendStep(inout vec4 dst, in vec4 src, in float stepSize) {
src.a = 1.0 - pow(1.0 - src.a, stepSize );
dst.rgb = dst.rgb + (1.0 - dst.a) * src.a * src.rgb;
dst.a = dst.a + (1.0 -dst.a) * src.a;
}
/*
//Color geometry
void blendGeometry(inout vec4 color, ABufferStruct_t frag) {
//vec4 c;
//c.rg = unpackHalf2x16(frag.rg);
//c.ba = unpackHalf2x16(frag.ba);
vec4 c = _col_(frag);
c.a = clamp(c.a, 0.0,1.0);
blend(color, c, 0.01);
return;
}
*/
float globz(float z) {
return z;
// return log(2.0*z-1.0);
// return exp(2.0*z-1.0);
// const float zNear = 0.1f;
// const float zFar = 1.0f;
// //float z_b = texture2D(depthBuffTex, vTexCoord).x;
// float z_b = z;
// float z_n = 2.0 * z_b - 1.0;
// float z_e = 2.0 * zNear * zFar / (zFar + zNear - z_n * (zFar - zNear));
// return z_e;
//return (2.0 * z - near - far) / (far - near);
}
vec4 calculate_final_color(uint frag_count) {
// volumeStepSize[volID] = 0.01;
int currentVolumeBitmask = 0;
vec4 final_color = vec4(0);
if(frag_count == 1 && _type_(fragments[0]) == 0) {
final_color = blend(final_color, _col_(fragments[0]));
return final_color;
}
int frag_count_1 = int(frag_count)-1;
for(int i = 0; i < frag_count_1 && final_color.a < ALPHA_LIMIT; i++) {
//int maxFrags = int(frag_count)-1;
//for(int i = 0; i < frag_count; i++) {
ABufferStruct_t startFrag = fragments[i];
ABufferStruct_t endFrag = fragments[i+1];
//vec4 frag_color = _col_(startFrag);
//vec4 position = _pos_(startFrag);
int type = int(_type_(startFrag));
currentVolumeBitmask = currentVolumeBitmask ^ (type);
if(type == 0)
//blendStep(final_color, _col_(startFrag), stepSize);
final_color = blend(final_color, _col_(startFrag));
if(bool(currentVolumeBitmask)) {
int volID = type -1;
float p = 0.0f;
// const float l = volume_length[volID];
const float S1 = volume_zlength[volID].x;
const float S2 = volume_zlength[volID].y;
const float L = S1 - S2;
const float z1 = globz(_z_(startFrag));
const float z2 = globz(_z_(endFrag));
// const float z1 = _z_(startFrag);
// const float z2 = _z_(endFrag);
const float l = ((z1 - S1) / L - (z2 - S1) / L) * volume_length[volID];
int max_iterations = int(l / volumeStepSize[volID]);
int iterations = 0;
vec3 position;
// const float S1 = volume_zlength[volID].x;
// const float S2 = volume_zlength[volID].y;
// const float L = volume_zlength[volID];
// const vec4 p1 = _pos_(startFrag);
// const vec4 p2 = _pos_(endFrag);
// const float dist = pscLength(p1, p2);
// // const float z1 = _z_(startFrag);
// // const float z2 = _z_(endFrag);
// const float l = (dist / L) * volume_length[volID];
// int max_iterations = int(l / volumeStepSize[volID]);
// int iterations = 0;
// vec3 position;
// MIP
// vec4 tmp, color = vec4(0);
// while(p < l && iterations < LOOP_LIMIT) {
// tmp = texture(volume, volume_position[volID]);
// color = max(color, tmp);
// p+= stepSize;
// volume_position[volID] += direction*stepSize;
// ++iterations;
// }
// vec4 volume_color = vec4(color.r,color.r,color.r,color.r*2.0);
// if(volume_color.a < 0.1) volume_color = vec4(0.0,0.0,0.0,0.0);
// final_color = blend(final_color, volume_color);
// TransferFunction
vec4 color = vec4(0);
for(int k = 0; k < max_iterations && k < LOOP_LIMIT; ++k) {
//while(p < l && iterations < LOOP_LIMIT) {
#pragma openspace insert SAMPLERCALLS
//final_color = blend(final_color, color*stepSize);
//volume_position[volID] += volume_direction[volID]*volumeStepSize[volID];
//p+= stepSize;
//++iterations;
}
}
//blendGeometry(final_color, startFrag);
//if(i == maxFrags -1 && _type_(endFrag) == 0)
// blendGeometry(final_color, endFrag);
// final_color = blend(final_color, frag_color);
if(i == frag_count_1 -1 && _type_(endFrag) == 0)
// if(i == frag_count_1 -1)
final_color = blend(final_color, _col_(endFrag));
}
// final_color = vec4(0);
// int id =3;
// if(id < frag_count)final_color = blend(final_color, _col_(fragments[id]));
// if(frag_count > 0)
// final_color = _col_(fragments[0]);
// ================================================================================
// Transferfunction visualizer
// ================================================================================
#ifdef SHOWFUNC
float showfunc_size = 20.0;
if(gl_FragCoord.y > float(SCREEN_HEIGHT) - showfunc_size) {
float normalizedIntensity = gl_FragCoord.x / float(SCREEN_WIDTH) ;
vec4 tfc = texture(transferFunction1, normalizedIntensity);
final_color = tfc;
} else if(ceil(gl_FragCoord.y) == float(SCREEN_HEIGHT) - showfunc_size) {
const float intensity = 0.4;
final_color = vec4(intensity,intensity,intensity,1.0);
}
#endif
// if(frag_count == 1) {
// final_color = vec4(0.0,0.0,1.0,1.0);
// } else if(frag_count == 2) {
// final_color = vec4(volume_direction[0],1.0);
// } else {
// final_color = vec4(1.0,1.0,1.0,1.0);
// }
return final_color;
}
// ================================================================================
// Main function
// ================================================================================
void main() {
color = vec4(texCoord,0.0,1.0);
int frag_count = build_local_fragments_list();
sort_fragments_list(frag_count);
color = calculate_final_color(frag_count);
}
// ================================================================================
// The samplers implementations
// ================================================================================
#pragma openspace insert SAMPLERS

View File

@@ -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. *
****************************************************************************************/
#version 430
in vec4 position;
out vec2 texCoord;
void main() {
gl_Position = position;
texCoord = 0.5 + position.xy / 2.0;
}

View File

@@ -0,0 +1,115 @@
/*****************************************************************************************
* *
* 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 "abufferAddToBuffer.hglsl"
int build_local_fragments_list() {
uint current;
int frag_count = 0;
current = imageLoad(anchorPointerTexture, ivec2(gl_FragCoord.xy)).x;
while(current != 0 && frag_count < MAX_FRAGMENTS) {
ABufferStruct_t item = loadFromBuffer(current);
current = _next_(item);
fragments[frag_count] = item;
frag_count++;
}
return frag_count;
}
float pscLength(vec4 v1, vec4 v2) {
const float k = 10.0;
float ds = v2.w - v1.w;
vec4 vector;
if(ds >= 0) {
float p = pow(k,-ds);
vector = vec4(v1.x*p - v2.x, v1.y*p - v2.y, v1.z*p - v2.z, v2.w);
} else {
float p = pow(k,ds);
vector = vec4(v1.x - v2.x*p, v1.y - v2.y*p, v1.z - v2.z*p, v1.w);
}
return length(vector.xyz)*pow(k,vector.w);
}
float permute(float i) {
return mod((62.0*i*i + i), 961.0); // permutation polynomial; 62=2*31; 961=31*31
}
void sort_fragments_list(uint frag_count) {
uint i,j;
ABufferStruct_t tmp;
// INSERTION SORT
for(i = 1; i < frag_count; ++i) {
tmp = fragments[i];
for(j = i; j > 0 && _z_(tmp) < _z_(fragments[j-1]); --j) {
fragments[j] = fragments[j-1];
}
fragments[j] = tmp;
}
int ii, jj;
for(ii = 0; ii < MAX_VOLUMES; ++ii) {
bool start = true;
vec3 startColor;
vec4 startPosition;
for(jj = ii; jj < frag_count; ++jj) {
int type = int(_type_(fragments[jj])) - 1;
if(type== ii) {
if(start) {
startColor = _col_(fragments[jj]).rgb;
startPosition = _pos_(fragments[jj]);
volume_zlength[ii].x = _z_(fragments[jj]);
start = false;
} else {
vec3 dir = _col_(fragments[jj]).rgb - startColor;
volume_position[ii] = startColor;
volume_length[ii] = length(dir);
volume_direction[ii] = normalize(dir);
volume_zlength[ii].y = _z_(fragments[jj]);
// volume_zlength[ii] = pscLength(_pos_(fragments[jj]), startPosition);
volumeStepSize[ii] = 1.0/(length(volume_direction[ii]*volume_dim[ii]));
// volume_length[ii] = pscLength(_pos_(fragments[jj]), startPosition);
if(volumeStepSize[ii] < volume_length[ii]) {
// jittering
float x = gl_FragCoord.x;
float y = gl_FragCoord.y;
float jitterValue = float(permute(x + permute(y))) / 961.0;
vec3 frontPosNew = startColor + (jitterValue*volumeStepSize[ii])*volume_direction[ii];
volume_position[ii] = frontPosNew;
}
break;
}
}
}
}
//volume_direction[0] = vec3(1.0,0.0,0.0);
//volume_direction[0] = _col_(fragments[0]).rgb;
}

View File

@@ -0,0 +1,143 @@
/*****************************************************************************************
* *
* 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 ABUFFERSTRUCT_H_HGLSL
#define ABUFFERSTRUCT_H_HGLSL
//=======================================================
// ABufferStruct_t declaration
//=======================================================
// struct ABufferStruct_t {
// uint z; // the depth value
// uint id; // bits 0-28 next, bits 29-32 type
// vec4 color; // packed rgba
// //vec4 position; // packed position
// // uint padding1;
// // uint padding2;
// };
struct ABufferStruct_t {
uint z; // the depth value
uint id; // bits 0-28 next, bits 29-32 type
uint rg; // packed red green color
uint ba; // packed blue alpha color
vec4 position; // position
};
//=======================================================
// Bitwise operations
//=======================================================
const uint mask_1 = 1;
const uint mask_8 = 255;
const uint mask_16 = 65535;
const uint mask_24 = 16777215;
const uint mask_29 = 536870911;
const uint mask_30 = 1073741823;
const uint mask_31 = 2147483647;
const uint mask_32 = 4294967295;
const uint mask_id = mask_16;
const uint shift_id = 0;
const uint mask_type = mask_24 - mask_16;
const uint shift_type = 16;
/*
const uint mask_zid_z = mask_24;
const uint shift_zid_z = 0;
const uint mask_zid_id = mask_29 - mask_24;
const uint shift_zid_id = 24;
const uint mask_zid_type = mask_31 - mask_29;
const uint shift_zid_type = 29;
const uint mask_zid_xxx = mask_32 - mask_31;
const uint shift_zid_xxx = 31;
*/
const uint mask_id_next = mask_29;
const uint shift_id_next = 0;
const uint mask_id_type = mask_32 - mask_29;
const uint shift_id_type = 29;
void bitinsert_u(inout uint pack, uint val, uint mask, uint shift) {
pack &= ~mask;
pack |= (val << shift) & mask;
}
uint bitextract_u(in uint pack, uint mask, uint shift) {
return (pack >> shift) & (mask >> shift);
}
void bitinsert_i(inout int pack, int val, uint mask, uint shift) {
pack &= int( ~mask );
pack |= int( (uint(val) << shift) & mask );
}
int bitextract_i(in int pack, uint mask, uint shift) {
return int( (uint(pack) >> shift) & (mask >> shift) );
}
//=======================================================
// Access functions
//=======================================================
float _z_(ABufferStruct_t frag) {
return uintBitsToFloat(frag.z);
}
void _z_(inout ABufferStruct_t frag, float z) {
frag.z = floatBitsToUint(z);
}
uint _next_(ABufferStruct_t frag) {
return bitextract_u(frag.id, mask_id_next, shift_id_next);
//return frag.id;
}
void _next_(inout ABufferStruct_t frag, uint id) {
bitinsert_u(frag.id, id, mask_id_next, shift_id_next);
//frag.id = id;
}
vec4 _pos_(ABufferStruct_t frag) {
// return vec4(0.0,0.0,0.0,0.0);
return frag.position;
//return unpackUnorm4x8(frag.position);
}
void _pos_(inout ABufferStruct_t frag, vec4 position) {
frag.position = position;
// frag.position = packUnorm4x8(position);
}
vec4 _col_(ABufferStruct_t frag) {
return vec4(unpackUnorm2x16(frag.rg),unpackUnorm2x16(frag.ba));
//return unpackUnorm4x8(frag.color);
}
void _col_(inout ABufferStruct_t frag, vec4 color) {
frag.rg = packUnorm2x16(color.rg);
frag.ba = packUnorm2x16(color.ba);
//frag.color = packUnorm4x8(color);
}
uint _type_(ABufferStruct_t frag) {
return bitextract_u(frag.id, mask_id_type, shift_id_type);
//return frag.type;
}
void _type_(inout ABufferStruct_t frag, uint type) {
bitinsert_u(frag.id, type, mask_id_type, shift_id_type);
//frag.type = type;
}
#endif

View File

@@ -0,0 +1,90 @@
/*****************************************************************************************
* *
* 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 POWERSCALING_FS_H_HGLSL
#define POWERSCALING_FS_H_HGLSL
// Observable universe is 10^27m, setting the far value to extremely high, aka 30!! ERMAHGERD!
const float k = 10.0;
const float s_far = 27.0f; //= gl_DepthRange.far; // 40
const float s_farcutoff = 12.0f;
const float s_nearcutoff = 7.00f;
const float s_near = 0.00f;// gl_DepthRange.near; // 0.1
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;
}
}
float pscDepth(vec4 position) {
float depth = 0.0f;
if(position.w <= 0.5) {
//depth = abs(position.z * pow(10, position.w)) / pow(k,s_far);
depth = (position.w+log(abs(position.z)))/pow(k, position.w);
} else if(position.w < 3.0) {
depth = position.w+log(abs(position.z))/pow(k, position.w);
} else {
depth = position.w+log(abs(position.z));
}
// DEBUG
float depth_orig = depth;
float x = 0.0f;
float cutoffs = 0.0;
float orig_z = 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);
}
return depth;
}
#endif

View File

@@ -0,0 +1,80 @@
/*****************************************************************************************
* *
* 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 POWERSCALING_VS_H_HGLSL
#define POWERSCALING_VS_H_HGLSL
const float k = 10.0;
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) {
float factor = v2.x * pow(k,v2.y + v1.w);
return vec4(v1.xyz * factor, 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);
}
}
vec4 pscTransform(vec4 vertexPosition, vec4 cameraPosition, vec2 scaling, mat4 modelTransform) {
vec3 local_vertex_pos = mat3(modelTransform) * vertexPosition.xyz;
//vec4 lvp = ModelTransform * vertexPosition;
// PSC addition; local vertex position and the object power scaled world position
vec4 position = psc_addition(vec4(local_vertex_pos,vertexPosition.w),objpos);
//position = psc_addition(lvp,objpos);
// PSC addition; rotated and viewscaled vertex and the cmaeras negative position
position = psc_addition(position,vec4(-cameraPosition.xyz,cameraPosition.w));
// rotate the camera
local_vertex_pos = mat3(camrot) * position.xyz;
position = vec4(local_vertex_pos, position.w);
//position = camrot* position;
// rescales the scene to fit inside the view frustum
// is set from the main program, but these are decent values
// scaling = vec2(1.0, -8.0);
// project using the rescaled coordinates,
//vec4 vs_position_rescaled = psc_scaling(position, scaling);
return psc_to_meter(position, scaling);
}
#endif

View File

@@ -1,3 +1,27 @@
/*****************************************************************************************
* *
* 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. *
****************************************************************************************/
#version 330
in vec4 color;

View File

@@ -1,3 +1,27 @@
/*****************************************************************************************
* *
* 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. *
****************************************************************************************/
#version 330
uniform mat4 projectionMatrix;

View File

@@ -1,8 +1,50 @@
#version 400 core
/*****************************************************************************************
* *
* 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. *
****************************************************************************************/
#version 430 core
uniform int volumeType;
in vec3 vPosition;
out vec4 fragColor;
in vec3 worldPosition;
in float s;
#include "ABuffer/abufferStruct.hglsl"
#include "ABuffer/abufferAddToBuffer.hglsl"
#include "PowerScaling/powerScaling_fs.hglsl"
void main() {
fragColor = vec4(vPosition+0.5, 1.0);
vec4 fragColor = vec4(vPosition+0.5, 0.3);
vec4 position = vec4(worldPosition,s);
float depth = pscDepth(position);
ABufferStruct_t frag;
_col_(frag, fragColor);
_z_(frag, depth);
_type_(frag, volumeType);
_pos_(frag, position);
addToBuffer(frag);
discard;
}

View File

@@ -1,11 +1,63 @@
#version 400 core
/*****************************************************************************************
* *
* 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. *
****************************************************************************************/
#version 430 core
layout(location = 0) in vec4 vertPosition;
layout(location = 2) in vec3 vertPosition;
uniform mat4 modelViewProjection;
uniform mat4 modelTransform;
uniform vec4 campos;
uniform mat4 camrot;
uniform vec2 scaling;
uniform vec4 objpos;
uniform float time;
out vec3 vPosition;
out vec3 worldPosition;
out float s;
#include "PowerScaling/powerScaling_vs.hglsl"
void main() {
gl_Position = modelViewProjection * vec4(vertPosition, 1.0);
vPosition = vertPosition;
//vs_st = in_st;
//vs_stp = in_position.xyz;
vPosition = vertPosition.xyz;
// this is wrong for the normal. The normal transform is the transposed inverse of the model transform
//vs_normal = normalize(modelTransform * vec4(in_normal,0));
vec4 position = pscTransform(vertPosition, campos, scaling, modelTransform);
worldPosition = position.xyz;
s = position.w;
// project the position to view space
gl_Position = modelViewProjection * position;
// vPosition = vertPosition.xyz;
// worldPosition = (modelTransform *vec4(vPosition, 1.0)).xyz;
// gl_Position = modelViewProjection *vec4(worldPosition, 1.0);
}

View File

@@ -1,115 +1,49 @@
/**
Copyright (C) 2012-2014 Jonas Strandstedt
/*****************************************************************************************
* *
* 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. *
****************************************************************************************/
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#version 430
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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
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_position;
in vec3 vs_position;
in float s;
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;
}
}
#include "ABuffer/abufferStruct.hglsl"
#include "ABuffer/abufferAddToBuffer.hglsl"
#include "PowerScaling/powerScaling_fs.hglsl"
void main()
{
vec4 position = vec4(vs_position,s);
float depth = pscDepth(position);
vec4 diffuse = texture(texture1, vs_st);
// 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;
ABufferStruct_t frag = createGeometryFragment(diffuse, position, depth);
addToBuffer(frag);
// 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;
//gl_FragDepth = 0.5;
// color
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(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);
discard;
}

View File

@@ -1,25 +1,28 @@
/**
Copyright (C) 2012-2014 Jonas Strandstedt
/*****************************************************************************************
* *
* 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. *
****************************************************************************************/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION 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
#version 430
uniform mat4 ViewProjection;
uniform mat4 ModelTransform;
@@ -28,13 +31,6 @@ 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;
layout(location = 0) in vec4 in_position;
//in vec3 in_position;
@@ -44,72 +40,24 @@ layout(location = 2) in vec3 in_normal;
out vec2 vs_st;
out vec3 vs_stp;
out vec4 vs_normal;
out vec4 vs_position;
out vec3 vs_position;
out float s;
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) {
float factor = v2.x * pow(k,v2.y + v1.w);
return vec4(v1.xyz * factor, 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);
}
}
#include "PowerScaling/powerScaling_vs.hglsl"
void main()
{
// set variables
vs_st = in_st;
//vs_stp = in_position.xyz;
// this is wrong for the normal. The normal transform is the transposed inverse of the model transform
vs_normal = normalize(ModelTransform * vec4(in_normal,0));
// 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.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
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
// 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;
vec4 position = pscTransform(in_position, campos, scaling, ModelTransform);
vs_position = position.xyz;
s = position.w;
// project the position to view space
gl_Position = ViewProjection * vs_position_rescaled;
gl_Position = ViewProjection * position;
}

View File

@@ -1,3 +1,27 @@
/*****************************************************************************************
* *
* 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. *
****************************************************************************************/
#version 330
uniform sampler2D quadTex;

View File

@@ -1,3 +1,27 @@
/*****************************************************************************************
* *
* 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. *
****************************************************************************************/
#version 330
layout(location = 0) in vec2 texCoordinate;

View File

@@ -1,3 +1,27 @@
/*****************************************************************************************
* *
* 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. *
****************************************************************************************/
#version 330
in vec4 position;

View File

@@ -1,3 +1,27 @@
/*****************************************************************************************
* *
* 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. *
****************************************************************************************/
#version 400 core
// Based on http://prideout.net/blog/?p=64

View File

@@ -1,3 +1,27 @@
/*****************************************************************************************
* *
* 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. *
****************************************************************************************/
#version 400 core
// Based on http://prideout.net/blog/?p=64

View File

@@ -1,3 +1,27 @@
/*****************************************************************************************
* *
* 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. *
****************************************************************************************/
#version 400 core
// Based on http://prideout.net/blog/?p=64

View File

@@ -1,3 +1,27 @@
/*****************************************************************************************
* *
* 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. *
****************************************************************************************/
#version 400 core
uniform sampler2D texBack, texFront;

View File

@@ -1,3 +1,27 @@
/*****************************************************************************************
* *
* 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. *
****************************************************************************************/
#version 400 core
layout(location = 0) in vec2 texCoordinate;

View File

@@ -34,6 +34,12 @@ 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 ABUFFER_SOURCE ${SOURCE_ROOT_DIR}/abuffer/*.cpp)
set(OPENSPACE_SOURCE ${OPENSPACE_SOURCE} ${ABUFFER_SOURCE})
file(GLOB ABUFFER_HEADER ${HEADER_ROOT_DIR}/openspace/abuffer/*.h)
set(OPENSPACE_HEADER ${OPENSPACE_HEADER} ${ABUFFER_HEADER})
source_group(ABuffer FILES ${ABUFFER_SOURCE} ${ABUFFER_HEADER})
file(GLOB ENGINE_SOURCE ${SOURCE_ROOT_DIR}/engine/*.cpp)
set(OPENSPACE_SOURCE ${OPENSPACE_SOURCE} ${ENGINE_SOURCE})
file(GLOB ENGINE_HEADER ${HEADER_ROOT_DIR}/openspace/engine/*.h)

323
src/abuffer/abuffer.cpp Normal file
View File

@@ -0,0 +1,323 @@
/*****************************************************************************************
* *
* 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 <openspace/abuffer/abuffer.h>
#include <openspace/engine/openspaceengine.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/logging/logmanager.h>
#include <sgct.h>
#include <iostream>
#include <fstream>
#include <string>
namespace {
std::string _loggerCat = "ABuffer";
std::string padGeneratedString(const std::string& content) {
std::string _content_ = "// GENERATED CONTENT\n" + content + "\n// END GENERATED CONTENT";
return _content_;
}
}
namespace openspace {
ABuffer::ABuffer(): _validShader(true) {
int x1, xSize, y1, ySize;
sgct::Engine::instance()->getActiveWindowPtr()->getCurrentViewportPixelCoords(x1, y1, xSize, ySize);
_width = xSize;
_height = ySize;
_totalPixels = _width * _height;
const std::string fragmentShaderSourcePath = absPath("${SHADERS}/ABuffer/abufferResolveFragment.glsl");
_fragmentShaderFile = new ghoul::filesystem::File(fragmentShaderSourcePath, true);
_fragmentShaderPath = fragmentShaderSourcePath.substr(0, fragmentShaderSourcePath.length()-4) + "gglsl";
}
ABuffer::~ABuffer() {
if(_fragmentShaderFile)
delete _fragmentShaderFile;
if(_resolveShader)
delete _resolveShader;
for(auto file: _samplerFiles) {
delete file;
}
for(auto file: _shaderFiles) {
delete file;
}
}
bool ABuffer::initializeABuffer() {
// ============================
// SHADERS
// ============================
auto shaderCallback = [this](const ghoul::filesystem::File& file) {
_validShader = false;
};
_fragmentShaderFile->setCallback(shaderCallback);
// Development functionality to update shader for changes in several files
auto addFunc = [this, shaderCallback](const std::string& path) {
ghoul::filesystem::File* f = new ghoul::filesystem::File(path, false);
f->setCallback(shaderCallback);
_shaderFiles.push_back(f);
};
addFunc("${SHADERS}/ABuffer/abufferSort.hglsl");
addFunc("${SHADERS}/ABuffer/abufferAddToBuffer.hglsl");
addFunc("${SHADERS}/ABuffer/abufferStruct.hglsl");
addFunc("${SHADERS}/PowerScaling/powerScaling_fs.hglsl");
addFunc("${SHADERS}/PowerScaling/powerScaling_vs.hglsl");
_resolveShader = nullptr;
generateShaderSource();
updateShader();
// ============================
// GEOMETRY (quad)
// ============================
const GLfloat size = 1.0f;
const GLfloat vertex_data[] = { // square of two triangles (sigh)
// x y z w s t
-size, -size, 0.0f, 1.0f,
size, size, 0.0f, 1.0f,
-size, size, 0.0f, 1.0f,
-size, -size, 0.0f, 1.0f,
size, -size, 0.0f, 1.0f,
size, size, 0.0f, 1.0f,
};
GLuint vertexPositionBuffer;
glGenVertexArrays(1, &_screenQuad); // generate array
glBindVertexArray(_screenQuad); // 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);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*4, reinterpret_cast<void*>(0));
glEnableVertexAttribArray(0);
return true;
}
void ABuffer::resolve() {
if( ! _validShader) {
_validShader = true;
generateShaderSource();
updateShader();
}
if(_resolveShader) {
_resolveShader->activate();
int startAt = 0;
for(int i = 0; i < _volumes.size(); ++i) {
glActiveTexture(GL_TEXTURE0 + i);
_volumes.at(i).second->bind();
startAt = i + 1;
}
for(int i = 0; i < _transferFunctions.size(); ++i) {
glActiveTexture(GL_TEXTURE0 + startAt + i);
_transferFunctions.at(i).second->bind();
}
glBindVertexArray(_screenQuad);
glDrawArrays(GL_TRIANGLES, 0, 6);
_resolveShader->deactivate();
}
}
void ABuffer::addVolume(const std::string& tag,ghoul::opengl::Texture* volume) {
_volumes.push_back(std::make_pair(tag, volume));
}
void ABuffer::addTransferFunction(const std::string& tag,ghoul::opengl::Texture* transferFunction) {
_transferFunctions.push_back(std::make_pair(tag, transferFunction));
}
int ABuffer::addSamplerfile(const std::string& filename) {
if( ! FileSys.fileExists(filename))
return -1;
auto fileCallback = [this](const ghoul::filesystem::File& file) {
_validShader = false;
};
ghoul::filesystem::File* file = new ghoul::filesystem::File(filename);
file->setCallback(fileCallback);
_samplerFiles.push_back(file);
_samplers.push_back("");
// ID is one more than "actual" position since ID=0 is considered geometry
return _samplers.size();
}
bool ABuffer::updateShader() {
using ghoul::opengl::ShaderObject;
using ghoul::opengl::ProgramObject;
ShaderObject* vs
= new ShaderObject(ShaderObject::ShaderType::ShaderTypeVertex,
absPath("${SHADERS}/ABuffer/abufferResolveVertex.glsl"), "Vertex");
ShaderObject* fs
= new ShaderObject(ShaderObject::ShaderType::ShaderTypeFragment,_fragmentShaderPath, "Fragment");
ghoul::opengl::ProgramObject* resolveShader = new ProgramObject;
resolveShader->attachObject(vs);
resolveShader->attachObject(fs);
if (!resolveShader->compileShaderObjects()) {
LERROR("Could not compile shader");
return false;
}
if (!resolveShader->linkProgramObject()){
LERROR("Could not link shader");
return false;
}
int startAt = 0;
for(int i = 0; i < _volumes.size(); ++i) {
resolveShader->setUniform(_volumes.at(i).first, i);
startAt = i + 1;
}
for(int i = 0; i < _transferFunctions.size(); ++i) {
resolveShader->setUniform(_transferFunctions.at(i).first, startAt + i);
}
resolveShader->setUniform("SCREEN_WIDTH", static_cast<int>(_width));
resolveShader->setUniform("SCREEN_HEIGHT", static_cast<int>(_height));
if(_resolveShader)
delete _resolveShader;
_resolveShader = resolveShader;
LDEBUG("Successfully updated shader!");
return true;
}
void ABuffer::generateShaderSource() {
for(int i = 0; i < _samplerFiles.size(); ++i) {
std::string line, source = "";
std::ifstream samplerFile(_samplerFiles.at(i)->path());
if(samplerFile.is_open()) {
while(std::getline(samplerFile, line)) {
source += line + "\n";
}
}
samplerFile.close();
_samplers.at(i) = source;
}
std::string line, source = "";
std::ifstream fragmentShaderFile(_fragmentShaderFile->path());
if(fragmentShaderFile.is_open()) {
while(std::getline(fragmentShaderFile, line)) {
if(line == "#pragma openspace insert HEADERS") {
line = padGeneratedString(openspaceHeaders());
} else if(line == "#pragma openspace insert SAMPLERCALLS") {
line = padGeneratedString(openspaceSamplerCalls());
} else if(line == "#pragma openspace insert SAMPLERS") {
line = padGeneratedString(openspaceSamplers());
} else if(line == "#pragma openspace insert SETTINGS") {
line = padGeneratedString(settings());
}
source += line + "\n";
}
}
fragmentShaderFile.close();
std::ofstream fragmentShaderOut(_fragmentShaderPath);
fragmentShaderOut << source;
fragmentShaderOut.close();
}
std::string ABuffer::openspaceHeaders() {
std::string headers;
headers += "#define MAX_VOLUMES " + std::to_string(_samplers.size()) + "\n";
for (int i = 0; i < _volumes.size(); ++i) {
headers += "uniform sampler3D " + _volumes.at(i).first + ";\n";
}
for (int i = 0; i < _transferFunctions.size(); ++i) {
headers += "uniform sampler1D " + _transferFunctions.at(i).first + ";\n";
}
for (int i = 0; i < _samplers.size(); ++i) {
auto found = _samplers.at(i).find_first_of('{');
if(found!=std::string::npos) {
headers += _samplers.at(i).substr(0, found) + ";\n";
}
}
headers += "const vec3 volume_dim[] = {\n";
for (int i = 0; i < _volumes.size(); ++i) {
glm::size3_t size = _volumes.at(i).second->dimensions();
headers += " vec3(" + std::to_string(size[0]) + ".0," + std::to_string(size[1]) + ".0,"
+ std::to_string(size[2]) + ".0),\n";
}
headers += "};\n";
headers += "float volumeStepSize[] = {\n";
for (int i = 0; i < _volumes.size(); ++i) {
glm::size3_t size = _volumes.at(i).second->dimensions();
headers += " stepSize,\n";
}
headers += "};\n";
return headers;
}
std::string ABuffer::openspaceSamplerCalls() {
std::string samplercalls;
for (int i = 0; i < _samplers.size(); ++i) {
auto found1 = _samplers.at(i).find_first_not_of("void ");
auto found2 = _samplers.at(i).find_first_of("(",found1);
if(found1 != std::string::npos && found2 != std::string::npos) {
std::string functionName = _samplers.at(i).substr(found1, found2 - found1);
samplercalls += "if((currentVolumeBitmask & (1 << " + std::to_string(i) + ")) == 1) {\n";
samplercalls += functionName + "(final_color,volume_position[" + std::to_string(i) + "]);\n";
samplercalls += "volume_position[" + std::to_string(i) + "] += volume_direction[" + std::to_string(i) + "]*volumeStepSize[" + std::to_string(i) + "];;\n";
samplercalls += "}\n";
}
}
return samplercalls;
}
std::string ABuffer::openspaceSamplers() {
std::string samplers;
for (int i = 0; i < _samplers.size(); ++i) {
samplers += _samplers.at(i) + "\n";
}
return samplers;
}
} // openspace

View File

@@ -0,0 +1,124 @@
/*****************************************************************************************
* *
* 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 <openspace/abuffer/abufferSingleLinked.h>
#include <openspace/engine/openspaceengine.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/logging/logmanager.h>
#include <iostream>
#include <fstream>
#include <string>
#define MAX_LAYERS 10
namespace {
std::string _loggerCat = "ABufferSingleLinked";
}
namespace openspace {
ABufferSingleLinked::ABufferSingleLinked(): _data(0), _anchorPointerTexture(0),
_anchorPointerTextureInitializer(0), _atomicCounterBuffer(0), _fragmentBuffer(0),
_fragmentTexture(0)
{}
ABufferSingleLinked::~ABufferSingleLinked() {
if(_data != 0)
delete _data;
glDeleteTextures(1,&_anchorPointerTexture);
glDeleteTextures(1,&_fragmentTexture);
glDeleteBuffers(1,&_anchorPointerTextureInitializer);
glDeleteBuffers(1,&_atomicCounterBuffer);
glDeleteBuffers(1,&_anchorPointerTextureInitializer);
}
bool ABufferSingleLinked::initialize() {
// ============================
// BUFFERS
// ============================
glGenTextures(1, &_anchorPointerTexture);
glBindTexture(GL_TEXTURE_2D, _anchorPointerTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R32UI, _width, _height, 0, GL_RED_INTEGER, GL_UNSIGNED_INT, NULL);
glGenBuffers(1, &_anchorPointerTextureInitializer);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, _anchorPointerTextureInitializer);
glBufferData(GL_PIXEL_UNPACK_BUFFER, _totalPixels * sizeof(GLuint), NULL, GL_STATIC_DRAW);
_data = (GLuint*)glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY);
memset(_data, 0x00, _totalPixels * sizeof(GLuint));
glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
glGenBuffers(1, &_atomicCounterBuffer);
glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, _atomicCounterBuffer);
glBufferData(GL_ATOMIC_COUNTER_BUFFER, sizeof(GLuint), NULL, GL_DYNAMIC_COPY);
glGenBuffers(1, &_fragmentBuffer);
glBindBuffer(GL_TEXTURE_BUFFER, _fragmentBuffer);
glBufferData(GL_TEXTURE_BUFFER, MAX_LAYERS*_totalPixels*sizeof(GLfloat)*4, NULL, GL_DYNAMIC_COPY);
glGenTextures(1, &_fragmentTexture);
glBindTexture(GL_TEXTURE_BUFFER, _fragmentTexture);
glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32UI, _fragmentBuffer);
glBindTexture(GL_TEXTURE_BUFFER, 0);
glBindImageTexture(1, _fragmentTexture, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32UI);
return initializeABuffer();
}
void ABufferSingleLinked::clear() {
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, _anchorPointerTextureInitializer);
glBindTexture(GL_TEXTURE_2D, _anchorPointerTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R32UI, _width, _height, 0, GL_RED_INTEGER, GL_UNSIGNED_INT, NULL);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
static const GLuint zero = 1;
glBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, 0, _atomicCounterBuffer);
glBufferSubData(GL_ATOMIC_COUNTER_BUFFER, 0, sizeof(zero), &zero);
glBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, 0, 0);
}
void ABufferSingleLinked::preRender() {
// Bind head-pointer image for read-write
glBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, 0, _atomicCounterBuffer);
glBindImageTexture(0, _anchorPointerTexture, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R32UI);
glBindImageTexture(1, _fragmentTexture, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA32UI);
}
void ABufferSingleLinked::postRender() {
}
std::string ABufferSingleLinked::settings() {
return R"(#define SINGLE_LINKED)";
}
} // openspace

View File

@@ -124,9 +124,9 @@ bool OpenSpaceEngine::registerBasePathFromConfigurationFile(const std::string& f
bool OpenSpaceEngine::findConfiguration(std::string& filename)
{
if (!filename.empty())
if (!filename.empty()) {
return FileSys.fileExists(filename);
else {
} else {
std::string currentDirectory = FileSys.absolutePath(FileSys.currentDirectory());
size_t occurrences = std::count(currentDirectory.begin(), currentDirectory.end(),
ghoul::filesystem::FileSystem::PathSeparator);
@@ -273,12 +273,13 @@ bool OpenSpaceEngine::initialize()
// initialize the RenderEngine, needs ${SCENEPATH} to be set
_renderEngine->initialize();
sceneGraph->loadScene(sceneDescriptionPath, scenePath);
sceneGraph->initialize();
_renderEngine->setSceneGraph(sceneGraph);
#ifdef FLARE_ONLY
_flare = new Flare();
_flare->initialize();
#endif
// Initialize OpenSpace input devices
DeviceIdentifier::init();
@@ -331,16 +332,26 @@ void OpenSpaceEngine::preSynchronization()
_interactionHandler->update(dt);
_interactionHandler->lockControls();
}
#ifdef FLARE_ONLY
_flare->preSync();
#endif
}
void OpenSpaceEngine::postSynchronizationPreDraw()
{
_renderEngine->postSynchronizationPreDraw();
#ifdef FLARE_ONLY
_flare->postSyncPreDraw();
#endif
}
void OpenSpaceEngine::render()
{
#ifdef FLARE_ONLY
_flare->render();
#else
_renderEngine->render();
#endif
}
void OpenSpaceEngine::postDraw()
@@ -348,6 +359,9 @@ void OpenSpaceEngine::postDraw()
if (sgct::Engine::instance()->isMaster()) {
_interactionHandler->unlockControls();
}
#ifdef FLARE_ONLY
_flare->postDraw();
#endif
}
void OpenSpaceEngine::keyboardCallback(int key, int action)
@@ -355,6 +369,9 @@ void OpenSpaceEngine::keyboardCallback(int key, int action)
if (sgct::Engine::instance()->isMaster()) {
_interactionHandler->keyboardCallback(key, action);
}
#ifdef FLARE_ONLY
_flare->keyboard(key, action);
#endif
}
void OpenSpaceEngine::mouseButtonCallback(int key, int action)
@@ -362,6 +379,9 @@ void OpenSpaceEngine::mouseButtonCallback(int key, int action)
if (sgct::Engine::instance()->isMaster()) {
_interactionHandler->mouseButtonCallback(key, action);
}
#ifdef FLARE_ONLY
_flare->mouse(key, action);
#endif
}
void OpenSpaceEngine::mousePositionCallback(int x, int y)
@@ -376,6 +396,9 @@ void OpenSpaceEngine::mouseScrollWheelCallback(int pos)
void OpenSpaceEngine::encode()
{
#ifdef FLARE_ONLY
_flare->encode();
#else
std::vector<char> dataStream(1024);
size_t offset = 0;
@@ -384,16 +407,21 @@ void OpenSpaceEngine::encode()
_synchronizationBuffer.setVal(dataStream);
sgct::SharedData::instance()->writeVector(&_synchronizationBuffer);
#endif
}
void OpenSpaceEngine::decode()
{
#ifdef FLARE_ONLY
_flare->decode();
#else
sgct::SharedData::instance()->readVector(&_synchronizationBuffer);
std::vector<char> dataStream = std::move(_synchronizationBuffer.getVal());
size_t offset = 0;
// deserialize in the same order as done in serialization
_renderEngine->deserialize(dataStream, offset);
#endif
}
} // namespace openspace

View File

@@ -6,6 +6,7 @@
#include <ghoul/logging/logmanager.h>
#include <sgct.h>
#include <ghoul/opengl/ghoul_gl.h>
#include <ghoul/opengl/framebufferobject.h>
#include <fstream>
#include <openspace/flare/Raycaster.h>
#include <openspace/flare/BrickManager.h>
@@ -94,6 +95,7 @@ Raycaster * Raycaster::New(Config *_config) {
bool Raycaster::Render(float _timestep) {
proj_ = sgct::Engine::instance()->getActiveProjectionMatrix();
GLuint activeFBO = ghoul::opengl::FramebufferObject::getActiveObject();
// Clear cache for benchmarking
if (config_->ClearCache()) {
@@ -270,7 +272,7 @@ bool Raycaster::Render(float _timestep) {
// Render to framebuffer using quad
glBindFramebuffer(GL_FRAMEBUFFER, sgct::Engine::instance()->getActiveWindowPtr()->getFBOPtr()->getBufferID());
glBindFramebuffer(GL_FRAMEBUFFER, activeFBO);
glGetError();
quadShaderProgram_->activate();

View File

@@ -34,7 +34,9 @@ Flare::Flare()
, _lastMouseY(0)
, _oldTime(0.f)
, _currentTime(0.f)
{}
{
setBoundingSphere(PowerScaledScalar::CreatePSS(sqrt(3.0f)));
}
Flare::~Flare() {
// Clean up like a good citizen
@@ -66,7 +68,8 @@ void Flare::update() {
void Flare::render() {
// Sync timestep
_animator->SetCurrentTimestep(static_cast<unsigned int>(_timeStep.getVal()));
//unsigned int ts = static_cast<unsigned int>(_timeStep.getVal());
//LDEBUG("ts: " << ts);
// Reload config if flag is set
if (_reloadFlag.getVal()) _raycaster->Reload();
@@ -379,6 +382,7 @@ void Flare::preSync() {
_oldTime = _currentTime;
_currentTime = static_cast<float>(sgct::Engine::getTime());
_elapsedTime.setVal(_currentTime - _oldTime);
_timeStep.setVal(_animator->CurrentTimestep());
// Update automatic model transform
if (!_animationPaused.getVal()) {
@@ -398,6 +402,10 @@ void Flare::preSync() {
}
}
void Flare::postSyncPreDraw() {
_animator->SetCurrentTimestep(static_cast<unsigned int>(_timeStep.getVal()));
}
void Flare::postDraw() {
// Reset manual timestep
_manualTimestep.setVal(0);

View File

@@ -173,19 +173,21 @@ void InteractionHandler::distance(const PowerScaledScalar &distance) {
lockControls();
psc relative = camera_->position();
psc origin;
if(node_) {
origin = node_->getWorldPosition();
}
const psc origin = (node_) ? node_->getWorldPosition() : psc();
psc relative_origin_coordinate = relative - origin;
glm::vec3 dir(relative_origin_coordinate.direction());
dir = dir * distance[0];
relative_origin_coordinate = dir;
const glm::vec3 dir(relative_origin_coordinate.direction());
glm:: vec3 newdir = dir * distance[0];
relative_origin_coordinate = newdir;
relative_origin_coordinate[3] = distance[1];
relative = relative + relative_origin_coordinate;
camera_->setPosition(relative);
relative_origin_coordinate = relative - origin;
newdir = relative_origin_coordinate.direction();
// update only if on the same side of the origin
if(glm::angle(newdir, dir) < 90.0f)
camera_->setPosition(relative);
unlockControls();
}
@@ -303,62 +305,65 @@ void InteractionHandler::keyboardCallback(int key, int action) {
// TODO package in script
const double speed = 2.75;
const double dt = getDt();
if (key == 'S') {
glm::vec3 euler(speed * dt, 0.0, 0.0);
glm::quat rot = glm::quat(euler);
orbit(rot);
}
if (key == 'W') {
glm::vec3 euler(-speed * dt, 0.0, 0.0);
glm::quat rot = glm::quat(euler);
orbit(rot);
}
if (key == 'A') {
glm::vec3 euler(0.0, -speed * dt, 0.0);
glm::quat rot = glm::quat(euler);
orbit(rot);
}
if (key == 'D') {
glm::vec3 euler(0.0, speed * dt, 0.0);
glm::quat rot = glm::quat(euler);
orbit(rot);
}
if (key == 262) {
glm::vec3 euler(0.0, speed * dt, 0.0);
glm::quat rot = glm::quat(euler);
rotate(rot);
}
if (key == 263) {
glm::vec3 euler(0.0, -speed * dt, 0.0);
glm::quat rot = glm::quat(euler);
rotate(rot);
}
if (key == 264) {
glm::vec3 euler(speed * dt, 0.0, 0.0);
glm::quat rot = glm::quat(euler);
rotate(rot);
}
if (key == 265) {
glm::vec3 euler(-speed * dt, 0.0, 0.0);
glm::quat rot = glm::quat(euler);
rotate(rot);
}
if (key == 'R') {
PowerScaledScalar dist(-speed * dt, 0.0);
distance(dist);
}
if (key == 'F') {
PowerScaledScalar dist(speed * dt, 0.0);
distance(dist);
}
if (key == 'T') {
PowerScaledScalar dist(-speed * 100.0 * dt, 0.0);
distance(dist);
}
if (key == 'G') {
PowerScaledScalar dist(speed * 100.0 * dt, 0.0);
distance(dist);
}
if(action == SGCT_PRESS || action == SGCT_REPEAT) {
if (key == SGCT_KEY_S) {
glm::vec3 euler(speed * dt, 0.0, 0.0);
glm::quat rot = glm::quat(euler);
orbit(rot);
}
if (key == SGCT_KEY_W) {
glm::vec3 euler(-speed * dt, 0.0, 0.0);
glm::quat rot = glm::quat(euler);
orbit(rot);
}
if (key == SGCT_KEY_A) {
glm::vec3 euler(0.0, -speed * dt, 0.0);
glm::quat rot = glm::quat(euler);
orbit(rot);
}
if (key == SGCT_KEY_D) {
glm::vec3 euler(0.0, speed * dt, 0.0);
glm::quat rot = glm::quat(euler);
orbit(rot);
}
if (key == 262) {
glm::vec3 euler(0.0, speed * dt, 0.0);
glm::quat rot = glm::quat(euler);
rotate(rot);
}
if (key == 263) {
glm::vec3 euler(0.0, -speed * dt, 0.0);
glm::quat rot = glm::quat(euler);
rotate(rot);
}
if (key == 264) {
glm::vec3 euler(speed * dt, 0.0, 0.0);
glm::quat rot = glm::quat(euler);
rotate(rot);
}
if (key == 265) {
glm::vec3 euler(-speed * dt, 0.0, 0.0);
glm::quat rot = glm::quat(euler);
rotate(rot);
}
if (key == SGCT_KEY_R) {
PowerScaledScalar dist(-speed * dt, 0.0);
distance(dist);
}
if (key == SGCT_KEY_F) {
PowerScaledScalar dist(speed * dt, 0.0);
distance(dist);
}
if (key == SGCT_KEY_T) {
PowerScaledScalar dist(-speed * 100.0 * dt, 0.0);
distance(dist);
}
if (key == SGCT_KEY_G) {
PowerScaledScalar dist(speed * 100.0 * dt, 0.0);
distance(dist);
}
}
/*
if (key == '1') {
SceneGraphNode* node = getSceneGraphNode("sun");
@@ -412,6 +417,15 @@ void InteractionHandler::mouseScrollWheelCallback(int pos) {
//if(mouseControl_ != nullptr) {
// mouseControl_->mouseScrollCallback(pos);
//}
const double speed = 4.75;
const double dt = getDt();
if(pos < 0) {
PowerScaledScalar dist(speed * dt, 0.0);
distance(dist);
} else if(pos > 0) {
PowerScaledScalar dist(-speed * dt, 0.0);
distance(dist);
}
}

View File

@@ -159,11 +159,11 @@ void mainMousePosCallback(double x, double y)
OsEng.mousePositionCallback(static_cast<int>(x), static_cast<int>(y));
}
void mainMouseScrollCallback(double pos, double /*pos2*/)
void mainMouseScrollCallback(double posX, double posY)
{
// TODO use float instead
if (_sgctEngine->isMaster())
OsEng.mouseScrollWheelCallback(static_cast<int>(pos));
OsEng.mouseScrollWheelCallback(static_cast<int>(posY));
}
void mainEncodeFun()

View File

@@ -34,8 +34,7 @@ namespace {
namespace openspace {
RenderableFieldlines::RenderableFieldlines(const ghoul::Dictionary& dictionary) :
Renderable(dictionary), _VAO(0), _programUpdateOnSave(false) {
_shaderMutex = new std::mutex;
Renderable(dictionary), _VAO(0), _programUpdateOnSave(false),_update(false) {
if(dictionary.hasKey("Fieldlines")) {
ghoul::Dictionary fieldlines;
@@ -177,7 +176,7 @@ bool RenderableFieldlines::initialize() {
// ------ SETUP SHADERS -----------------
auto privateCallback = [this](const ghoul::filesystem::File& file) {
safeShaderCompilation();
_update = true;
};
if(_programUpdateOnSave) {
_vertexSourceFile->setCallback(privateCallback);
@@ -195,19 +194,40 @@ bool RenderableFieldlines::deinitialize() {
}
void RenderableFieldlines::render(const Camera* camera, const psc& thisPosition) {
if(_update) {
_update = false;
safeShaderCompilation();
}
glm::mat4 transform = camera->viewProjectionMatrix();
glm::mat4 camTransform = camera->viewRotationMatrix();
psc relative = thisPosition-camera->position();
transform = transform*camTransform;
transform = glm::translate(transform, relative.vec3());
//transform = glm::translate(transform, relative.vec3());
transform = glm::mat4(1.0);
transform = glm::rotate(transform, -90.0f, glm::vec3(1.0, 0.0, 0.0)); // Model has positive Z as up
transform = glm::scale(transform, glm::vec3(0.1)); // Scale to avoid depth buffer problems
transform = glm::scale(transform, glm::vec3(0.036*0.5*0.5));
//transform = glm::scale(transform, glm::vec3(0.1)); // Scale to avoid depth buffer problems
psc currentPosition = thisPosition;
psc campos = camera->position();
glm::mat4 camrot = camera->viewRotationMatrix();
PowerScaledScalar scaling = camera->scaling();
// Activate shader
_fieldlinesProgram->activate();
//_fieldlinesProgram->setUniform("modelViewProjection", transform);
_fieldlinesProgram->setUniform("modelViewProjection", camera->viewProjectionMatrix());
_fieldlinesProgram->setUniform("modelTransform", transform);
_fieldlinesProgram->setUniform("campos", campos.vec4());
_fieldlinesProgram->setUniform("objpos", currentPosition.vec4());
_fieldlinesProgram->setUniform("camrot", camrot);
_fieldlinesProgram->setUniform("scaling", scaling.vec2());
// ------ FIELDLINES -----------------
_shaderMutex->lock();
_fieldlinesProgram->activate();
_fieldlinesProgram->setUniform("modelViewProjection", transform);
glBindVertexArray(_VAO);
glMultiDrawArrays(GL_LINE_STRIP, &_lineStart[0], &_lineCount[0], _lineStart.size());
@@ -216,19 +236,17 @@ void RenderableFieldlines::render(const Camera* camera, const psc& thisPosition)
glMultiDrawArrays(GL_POINTS, &_lineStart[0], &_lineCount[0], _seedPoints.size());
glBindVertexArray(0);
// Deactivate shader
_fieldlinesProgram->deactivate();
_shaderMutex->unlock();
}
void RenderableFieldlines::update() {
}
void RenderableFieldlines::safeShaderCompilation() {
_shaderMutex->lock();
_fieldlinesProgram->rebuildFromFile();
_fieldlinesProgram->compileShaderObjects();
_fieldlinesProgram->linkProgramObject();
_shaderMutex->unlock();
}
std::vector<std::vector<glm::vec3> > RenderableFieldlines::getFieldlinesData(std::string filename, ghoul::Dictionary hintsDictionary) {

View File

@@ -77,7 +77,10 @@ RenderableVolume::RenderableVolume(const ghoul::Dictionary& dictionary) : Render
RenderableVolume::~RenderableVolume() {
}
ghoul::opengl::Texture* RenderableVolume::loadVolume(const std::string& filepath, const ghoul::Dictionary& hintsDictionary) {
ghoul::opengl::Texture* RenderableVolume::loadVolume(
const std::string& filepath,
const ghoul::Dictionary& hintsDictionary)
{
if( ! FileSys.fileExists(filepath)) {
LWARNING("Could not load volume, could not find '" << filepath << "'");
return nullptr;
@@ -89,63 +92,128 @@ ghoul::opengl::Texture* RenderableVolume::loadVolume(const std::string& filepath
return rawReader.read(filepath);
} else if(hasExtension(filepath, "cdf")) {
std::string modelString;
if (hintsDictionary.hasKey("Model") && hintsDictionary.getValue("Model", modelString)) {
KameleonWrapper::Model model;
if (modelString == "BATSRUS") {
model = KameleonWrapper::Model::BATSRUS;
} else if (modelString == "ENLIL") {
model = KameleonWrapper::Model::ENLIL;
} else {
LWARNING("Hints does not specify a valid 'Model'");
return nullptr;
}
glm::size3_t dimensions(1,1,1);
double tempValue;
if (hintsDictionary.hasKey("Dimensions.1") &&
hintsDictionary.getValue("Dimensions.1", tempValue)) {
int intVal = static_cast<int>(tempValue);
if(intVal > 0)
dimensions[0] = intVal;
}
if (hintsDictionary.hasKey("Dimensions.2") &&
hintsDictionary.getValue("Dimensions.2", tempValue)) {
int intVal = static_cast<int>(tempValue);
if(intVal > 0)
dimensions[1] = intVal;
}
if (hintsDictionary.hasKey("Dimensions.3") &&
hintsDictionary.getValue("Dimensions.3", tempValue)) {
int intVal = static_cast<int>(tempValue);
if(intVal > 0)
dimensions[2] = intVal;
}
glm::size3_t dimensions(1,1,1);
double tempValue;
if (hintsDictionary.hasKey("Dimensions.1") && hintsDictionary.getValue("Dimensions.1", tempValue)) {
int intVal = static_cast<int>(tempValue);
if(intVal > 0)
dimensions[0] = intVal;
}
if (hintsDictionary.hasKey("Dimensions.2") && hintsDictionary.getValue("Dimensions.2", tempValue)) {
int intVal = static_cast<int>(tempValue);
if(intVal > 0)
dimensions[1] = intVal;
}
if (hintsDictionary.hasKey("Dimensions.3") && hintsDictionary.getValue("Dimensions.3", tempValue)) {
int intVal = static_cast<int>(tempValue);
if(intVal > 0)
dimensions[2] = intVal;
}
std::string modelString = "";
if (hintsDictionary.hasKey("Model"))
hintsDictionary.getValue("Model", modelString);
KameleonWrapper kw(filepath, model);
if(modelString == "") {
LWARNING("Model not specified.");
return nullptr;
}
std::string variableString;
if (hintsDictionary.hasKey("Variable") && hintsDictionary.getValue("Variable", variableString)) {
float* data = kw.getUniformSampledValues(variableString, dimensions);
return new ghoul::opengl::Texture(data, dimensions, ghoul::opengl::Texture::Format::Red, GL_RED, GL_FLOAT);
std::string variableCacheString = "";
if (hintsDictionary.hasKey("Variable")) {
hintsDictionary.getValue("Variable", variableCacheString);
} else if(hintsDictionary.hasKey("Variables")) {
std::string xVariable, yVariable, zVariable;
bool xVar, yVar, zVar;
xVar = hintsDictionary.getValue("Variables.1", xVariable);
yVar = hintsDictionary.getValue("Variables.2", yVariable);
zVar = hintsDictionary.getValue("Variables.3", zVariable);
if (xVar && yVar && zVar) {
variableCacheString = xVariable + "." + yVariable + "." + zVariable;
}
}
} else if (hintsDictionary.hasKey("Variables")) {
std::string xVariable, yVariable, zVariable;
bool xVar, yVar, zVar;
xVar = hintsDictionary.getValue("Variables.1", xVariable);
yVar = hintsDictionary.getValue("Variables.2", yVariable);
zVar = hintsDictionary.getValue("Variables.3", zVariable);
bool cache = false;
hintsDictionary.hasKey("Cache");
if (hintsDictionary.hasKey("Cache"))
hintsDictionary.getValue("Cache", cache);
if (!xVar || !yVar || !zVar) {
LERROR("Error reading variables! Must be 3 and must exist in CDF data");
} else {
float* data = kw.getUniformSampledVectorValues(xVariable, yVariable, zVariable, dimensions);
return new ghoul::opengl::Texture(data, dimensions, ghoul::opengl::Texture::Format::RGBA, GL_RGBA, GL_FLOAT);
}
std::stringstream ss;
ss << "." << dimensions[0] << "x" << dimensions[1] << "x" << dimensions[2] << "." << modelString << "." << variableCacheString << ".cache";
std::string cachepath = filepath + ss.str();
if( cache && FileSys.fileExists(cachepath)) {
} else {
LWARNING("Hints does not specify a 'Variable' or 'Variables'");
}
FILE* file = fopen (cachepath.c_str(), "rb");
int length = dimensions[0] *dimensions[1] *dimensions[2];
float* data = new float[length];
for(int i = 0; i< length; i++){
float f;
fread(&f, sizeof(float), 1, file);
data[i] = f;
}
fclose(file);
ghoul::opengl::Texture* t = new ghoul::opengl::Texture(data, dimensions, ghoul::opengl::Texture::Format::Red, GL_RED, GL_FLOAT, ghoul::opengl::Texture::FilterMode::Linear, ghoul::opengl::Texture::WrappingMode::ClampToBorder);
t->setWrapping(ghoul::opengl::Texture::WrappingMode::ClampToBorder);
return t;
}
KameleonWrapper::Model model;
if (modelString == "BATSRUS") {
model = KameleonWrapper::Model::BATSRUS;
} else if (modelString == "ENLIL") {
model = KameleonWrapper::Model::ENLIL;
} else {
LWARNING("Hints does not specify a valid 'Model'");
return nullptr;
}
KameleonWrapper kw(filepath, model);
std::string variableString;
if (hintsDictionary.hasKey("Variable") && hintsDictionary.getValue("Variable", variableString)) {
float* data = kw.getUniformSampledValues(variableString, dimensions);
if(cache) {
FILE* file = fopen (cachepath.c_str(), "wb");
int length = dimensions[0] *dimensions[1] *dimensions[2];
fwrite(data, sizeof(float), length, file);
fclose(file);
}
ghoul::opengl::Texture* t = new ghoul::opengl::Texture(data, dimensions, ghoul::opengl::Texture::Format::Red, GL_RED, GL_FLOAT, ghoul::opengl::Texture::FilterMode::Linear, ghoul::opengl::Texture::WrappingMode::ClampToBorder);
t->setWrapping(ghoul::opengl::Texture::WrappingMode::ClampToBorder);
return t;
} else if (hintsDictionary.hasKey("Variables")) {
std::string xVariable, yVariable, zVariable;
bool xVar, yVar, zVar;
xVar = hintsDictionary.getValue("Variables.1", xVariable);
yVar = hintsDictionary.getValue("Variables.2", yVariable);
zVar = hintsDictionary.getValue("Variables.3", zVariable);
if (!xVar || !yVar || !zVar) {
LERROR("Error reading variables! Must be 3 and must exist in CDF data");
} else {
float* data = kw.getUniformSampledVectorValues(xVariable, yVariable, zVariable, dimensions);
if(cache) {
FILE* file = fopen (cachepath.c_str(), "wb");
int length = dimensions[0] *dimensions[1] *dimensions[2];
fwrite(data, sizeof(float), length, file);
fclose(file);
}
ghoul::opengl::Texture* t = new ghoul::opengl::Texture(data, dimensions, ghoul::opengl::Texture::Format::RGBA, GL_RGBA, GL_FLOAT);
t->setWrapping(ghoul::opengl::Texture::WrappingMode::ClampToBorder);
return t;
}
} else {
LWARNING("Hints does not specify a 'Variable' or 'Variables'");
}
LWARNING("Hints does not specify a 'Model'");
} else {
LWARNING("No valid file extension.");
}
@@ -222,7 +290,9 @@ ghoul::opengl::Texture* RenderableVolume::loadTransferFunction(const std::string
// check if not a txt based texture
if ( ! hasExtension(filepath, "txt")) {
return ghoul::opengl::loadTexture(f);
ghoul::opengl::Texture* t = ghoul::opengl::loadTexture(f);
t->setWrapping(ghoul::opengl::Texture::WrappingMode::ClampToBorder);
return t;
}
// it is a txt based texture
@@ -352,16 +422,18 @@ ghoul::opengl::Texture* RenderableVolume::loadTransferFunction(const std::string
//LDEBUG("["<< position <<"] " << value);
}
// LDEBUG(weight << ", (" <<
// transferFunction[4*i+0] << ", " <<
// transferFunction[4*i+1] << ", " <<
// transferFunction[4*i+2] << ", " <<
// transferFunction[4*i+3] << ")");
// LDEBUG(weight << ", (" <<
// transferFunction[4*i+0] << ", " <<
// transferFunction[4*i+1] << ", " <<
// transferFunction[4*i+2] << ", " <<
// transferFunction[4*i+3] << ")");
}
return new ghoul::opengl::Texture(transferFunction,
ghoul::opengl::Texture* t = new ghoul::opengl::Texture(transferFunction,
glm::size3_t(width,1,1),ghoul::opengl::Texture::Format::RGBA,
GL_RGBA, GL_FLOAT);;
GL_RGBA, GL_FLOAT, ghoul::opengl::Texture::FilterMode::Linear,
ghoul::opengl::Texture::WrappingMode::ClampToBorder);
return t;
}
} // namespace openspace

View File

@@ -33,6 +33,9 @@
#include <algorithm>
#include <openspace/engine/openspaceengine.h>
#include <sgct.h>
namespace {
std::string _loggerCat = "RenderableVolumeGL";
}
@@ -40,10 +43,9 @@ namespace {
namespace openspace {
RenderableVolumeGL::RenderableVolumeGL(const ghoul::Dictionary& dictionary):
RenderableVolume(dictionary), _screenQuad(0), _boxScaling(1.0, 1.0, 1.0),
_programUpdateOnSave(false) {
RenderableVolume(dictionary), _box(nullptr), _boxScaling(1.0, 1.0, 1.0),
_updateTransferfunction(false), _id(-1) {
_shaderMutex = new std::mutex;
_filename = "";
if(dictionary.hasKey("Volume")) {
@@ -57,36 +59,29 @@ RenderableVolumeGL::RenderableVolumeGL(const ghoul::Dictionary& dictionary):
if(dictionary.hasKey("Hints"))
dictionary.getValue("Hints", _hintsDictionary);
std::string vshaderpath = "";
std::string fshaderpath = "";
if (dictionary.hasKey("Shaders")) {
ghoul::Dictionary shaderDictionary;
if(dictionary.getValue("Shaders", shaderDictionary)) {
if (shaderDictionary.hasKey("VertexShader")) {
shaderDictionary.getValue("VertexShader", vshaderpath);
}
if (shaderDictionary.hasKey("FragmentShader")) {
shaderDictionary.getValue("FragmentShader", fshaderpath);
}
vshaderpath = findPath(vshaderpath);
fshaderpath = findPath(fshaderpath);
_vertexSourceFile = new ghoul::filesystem::File(vshaderpath, false);
_fragmentSourceFile = new ghoul::filesystem::File(fshaderpath, false);
_twopassProgram = new ghoul::opengl::ProgramObject("TwoPassProgram");
ghoul::opengl::ShaderObject* vertexShader = new ghoul::opengl::ShaderObject(ghoul::opengl::ShaderObject::ShaderTypeVertex,vshaderpath);
ghoul::opengl::ShaderObject* fragmentShader = new ghoul::opengl::ShaderObject(ghoul::opengl::ShaderObject::ShaderTypeFragment,fshaderpath);
_twopassProgram->attachObject(vertexShader);
_twopassProgram->attachObject(fragmentShader);
_transferFunction = nullptr;
_transferFunctionFile = nullptr;
if (dictionary.hasKey("TransferFunction")) {
std::string transferFunctionPath = "";
if(dictionary.getValue("TransferFunction", transferFunctionPath)) {
_transferFunctionPath = findPath(transferFunctionPath);
}
}
if(dictionary.hasKey("UpdateOnSave")) {
dictionary.getValue("UpdateOnSave", _programUpdateOnSave);
_samplerFilename = "";
if (dictionary.hasKey("Sampler")) {
if(dictionary.getValue("Sampler", _samplerFilename)) {
_samplerFilename = findPath(_samplerFilename);
}
}
if( _transferFunctionPath == "") {
LERROR("No transferFunction!");
} else {
_transferFunctionFile = new ghoul::filesystem::File(_transferFunctionPath, true);
}
if( _samplerFilename == "") {
LERROR("No samplerfile!");
}
double tempValue;
if(dictionary.hasKey("BoxScaling.1") && dictionary.getValue("BoxScaling.1", tempValue)) {
@@ -102,7 +97,6 @@ RenderableVolumeGL::RenderableVolumeGL(const ghoul::Dictionary& dictionary):
_boxScaling[2] = tempValue;
}
_colorBoxRenderer = new VolumeRaycasterBox();
setBoundingSphere(PowerScaledScalar::CreatePSS(glm::length(_boxScaling)));
}
@@ -110,8 +104,12 @@ RenderableVolumeGL::~RenderableVolumeGL() {
deinitialize();
if(_volume)
delete _volume;
if(_colorBoxRenderer)
delete _colorBoxRenderer;
if(_transferFunctionFile)
delete _transferFunctionFile;
if(_transferFunction)
delete _transferFunction;
if(_box)
delete _box;
}
bool RenderableVolumeGL::initialize() {
@@ -119,55 +117,84 @@ bool RenderableVolumeGL::initialize() {
// ------ VOLUME READING ----------------
_volume = loadVolume(_filename, _hintsDictionary);
_volume->uploadTexture();
// ------ SETUP GEOMETRY ----------------
const GLfloat size = 1.0f;
const GLfloat vertex_texcoord_data[] = { // square of two triangles (sigh)
// x y z s t
-size, -size, 0.0f, 0.0f, 0.0f,
size, size, 0.0f, 1.0f, 1.0f,
-size, size, 0.0f, 0.0f, 1.0f,
-size, -size, 0.0f, 0.0f, 0.0f,
size, -size, 0.0f, 1.0f, 0.0f,
size, size, 0.0f, 1.0f, 1.0f
_transferFunction = loadTransferFunction(_transferFunctionPath);
_transferFunction->uploadTexture();
// TODO: fix volume an transferfunction names
OsEng.renderEngine().abuffer()->addVolume("volume1", _volume);
OsEng.renderEngine().abuffer()->addTransferFunction("transferFunction1", _transferFunction);
_id = OsEng.renderEngine().abuffer()->addSamplerfile(_samplerFilename);
auto textureCallback = [this](const ghoul::filesystem::File& file) {
_updateTransferfunction = true;
};
GLuint vertexPositionBuffer;
glGenVertexArrays(1, &_screenQuad); // generate array
glBindVertexArray(_screenQuad); // bind array
glGenBuffers(1, &vertexPositionBuffer); // generate buffer
glBindBuffer(GL_ARRAY_BUFFER, vertexPositionBuffer); // bind buffer
glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_texcoord_data), vertex_texcoord_data, GL_STATIC_DRAW);
// Vertex positions
GLuint vertexLocation = 2;
glEnableVertexAttribArray(vertexLocation);
glVertexAttribPointer(vertexLocation, 3, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), reinterpret_cast<void*>(0));
// Texture coordinates
GLuint texcoordLocation = 0;
glEnableVertexAttribArray(texcoordLocation);
glVertexAttribPointer(texcoordLocation, 2, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (void*)(3*sizeof(GLfloat)));
glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind buffer
glBindVertexArray(0); //unbind array
_colorBoxRenderer->initialize();
// ------ SETUP SHADERS -----------------
auto privateCallback = [this](const ghoul::filesystem::File& file) {
safeShaderCompilation();
_transferFunctionFile->setCallback(textureCallback);
_box = new sgct_utils::SGCTBox(1.0f, sgct_utils::SGCTBox::Regular);
OsEng.configurationManager().getValue("RaycastProgram", _boxProgram);
_MVPLocation = _boxProgram->uniformLocation("modelViewProjection");
_modelTransformLocation = _boxProgram->uniformLocation("modelTransform");
_typeLocation = _boxProgram->uniformLocation("volumeType");
// ============================
// GEOMETRY (quad)
// ============================
const GLfloat size = 0.5f;
const GLfloat vertex_data[] = { // square of two triangles (sigh)
// x, y, z, s,
-size, -size, size, 0.0f,
size, size, size, 0.0f,
-size, size, size, 0.0f,
-size, -size, size, 0.0f,
size, -size, size, 0.0f,
size, size, size, 0.0f,
-size, -size, -size, 0.0f,
size, size, -size, 0.0f,
-size, size, -size, 0.0f,
-size, -size, -size, 0.0f,
size, -size, -size, 0.0f,
size, size, -size, 0.0f,
size, -size, -size, 0.0f,
size, size, size, 0.0f,
size, -size, size, 0.0f,
size, -size, -size, 0.0f,
size, size, -size, 0.0f,
size, size, size, 0.0f,
-size, -size, -size, 0.0f,
-size, size, size, 0.0f,
-size, -size, size, 0.0f,
-size, -size, -size, 0.0f,
-size, size, -size, 0.0f,
-size, size, size, 0.0f,
-size, size, -size, 0.0f,
size, size, size, 0.0f,
-size, size, size, 0.0f,
-size, size, -size, 0.0f,
size, size, -size, 0.0f,
size, size, size, 0.0f,
-size, -size, -size, 0.0f,
size, -size, size, 0.0f,
-size, -size, size, 0.0f,
-size, -size, -size, 0.0f,
size, -size, -size, 0.0f,
size, -size, size, 0.0f,
};
if(_programUpdateOnSave) {
_vertexSourceFile->setCallback(privateCallback);
_fragmentSourceFile->setCallback(privateCallback);
}
GLuint vertexPositionBuffer;
glGenVertexArrays(1, &_boxArray); // generate array
glBindVertexArray(_boxArray); // 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);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*4, reinterpret_cast<void*>(0));
//glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*7, reinterpret_cast<void*>(0));
glEnableVertexAttribArray(0);
//glEnableVertexAttribArray(1);
_twopassProgram->compileShaderObjects();
_twopassProgram->linkProgramObject();
_twopassProgram->setUniform("texBack", 0);
_twopassProgram->setUniform("texFront", 1);
_twopassProgram->setUniform("texVolume", 2);
return true;
}
@@ -177,52 +204,74 @@ bool RenderableVolumeGL::deinitialize() {
}
void RenderableVolumeGL::render(const Camera *camera, const psc &thisPosition) {
_stepSize = 0.01f;
if(_updateTransferfunction) {
_updateTransferfunction = false;
ghoul::opengl::Texture* transferFunction = loadTransferFunction(_transferFunctionPath);
if(transferFunction) {
const void* data = transferFunction->pixelData();
glBindBuffer(GL_COPY_READ_BUFFER, *transferFunction);
_transferFunction->bind();
glTexImage1D( GL_TEXTURE_1D, 0, _transferFunction->internalFormat(),
_transferFunction->width(),0, _transferFunction->format(),
_transferFunction->dataType(), data);
delete transferFunction;
LDEBUG("Updated transferfunction!");
glm::mat4 transform = camera->viewProjectionMatrix();
glm::mat4 camTransform = camera->viewRotationMatrix();
psc relative = thisPosition-camera->position();
}
}
transform = transform*camTransform;
transform = glm::translate(transform, relative.vec3());
//psc relative = thisPosition-camera->position();
// glm::mat4 transform = camera->viewRotationMatrix();
// transform = glm::translate(transform, relative.vec3());
// transform = glm::translate(transform, glm::vec3(-1.1,0.0,0.0));
// transform = glm::scale(transform, _boxScaling);
glm::mat4 transform = glm::mat4(1.0);
transform = glm::scale(transform, _boxScaling);
_colorBoxRenderer->render(transform);
// Draw screenquad
_shaderMutex->lock();
_twopassProgram->activate();
_twopassProgram->setUniform("stepSize", _stepSize);
// Set textures
glActiveTexture(GL_TEXTURE0);
_colorBoxRenderer->backFace()->bind();
glActiveTexture(GL_TEXTURE1);
_colorBoxRenderer->frontFace()->bind();
glActiveTexture(GL_TEXTURE2);
_volume->bind();
glBindVertexArray(_screenQuad);
glDrawArrays(GL_TRIANGLES, 0, 6);
glBindVertexArray(0);
_twopassProgram->deactivate();
_shaderMutex->unlock();
// fetch data
psc currentPosition = thisPosition;
psc campos = camera->position();
glm::mat4 camrot = camera->viewRotationMatrix();
PowerScaledScalar scaling = camera->scaling();
psc addon(-1.1,0.0,0.0,0.0);
currentPosition += addon;
// TODO: Use _id to identify this volume
_boxProgram->activate();
// _boxProgram->setUniform(_MVPLocation, camera->viewProjectionMatrix());
// _boxProgram->setUniform(_modelTransformLocation, transform);
_boxProgram->setUniform(_typeLocation, _id);
_boxProgram->setUniform("modelViewProjection", camera->viewProjectionMatrix());
_boxProgram->setUniform("modelTransform", transform);
_boxProgram->setUniform("campos", campos.vec4());
_boxProgram->setUniform("objpos", currentPosition.vec4());
_boxProgram->setUniform("camrot", camrot);
_boxProgram->setUniform("scaling", scaling.vec2());
// make sure GL_CULL_FACE is enabled (it should be)
glEnable(GL_CULL_FACE);
// Draw backface
glCullFace(GL_FRONT);
glBindVertexArray(_boxArray);
glDrawArrays(GL_TRIANGLES, 0, 6*6);
// _box->draw();
// Draw frontface (now the normal cull face is is set)
glCullFace(GL_BACK);
glDrawArrays(GL_TRIANGLES, 0, 6*6);
// _box->draw();
_boxProgram->deactivate();
}
void RenderableVolumeGL::update() {
}
void RenderableVolumeGL::safeShaderCompilation() {
_shaderMutex->lock();
_twopassProgram->rebuildFromFile();
_twopassProgram->compileShaderObjects();
_twopassProgram->linkProgramObject();
_twopassProgram->setUniform("texBack", 0);
_twopassProgram->setUniform("texFront", 1);
_twopassProgram->setUniform("texVolume", 2);
_shaderMutex->unlock();
}
} // namespace openspace

View File

@@ -34,6 +34,8 @@
#include <array>
#include <openspace/abuffer/abufferSingleLinked.h>
namespace {
const std::string _loggerCat = "RenderEngine";
}
@@ -42,6 +44,7 @@ namespace openspace {
RenderEngine::RenderEngine()
: _mainCamera(nullptr)
, _sceneGraph(nullptr)
, _abuffer(nullptr)
{
}
@@ -52,6 +55,7 @@ RenderEngine::~RenderEngine()
bool RenderEngine::initialize()
{
// LDEBUG("RenderEngine::initialize()");
// init camera and set temporary position and scaling
_mainCamera = new Camera();
_mainCamera->setScaling(glm::vec2(1.0, -8.0));
@@ -61,11 +65,14 @@ bool RenderEngine::initialize()
//if (sgct::Engine::instance()->isMaster())
OsEng.interactionHandler().setCamera(_mainCamera);
_abuffer = new ABufferSingleLinked();
return true;
}
bool RenderEngine::initializeGL()
{
// LDEBUG("RenderEngine::initializeGL()");
sgct::SGCTWindow* wPtr = sgct::Engine::instance()->getActiveWindowPtr();
// TODO: Fix the power scaled coordinates in such a way that these values can be
@@ -132,6 +139,8 @@ bool RenderEngine::initializeGL()
_mainCamera->setMaxFov(maxFov);
}
_abuffer->initialize();
// successful init
return true;
}
@@ -150,8 +159,10 @@ void RenderEngine::postSynchronizationPreDraw()
void RenderEngine::render()
{
// SGCT resets certain settings
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
//glEnable(GL_DEPTH_TEST);
//glEnable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
// setup the camera for the current frame
const glm::vec3 eyePosition
@@ -163,8 +174,12 @@ void RenderEngine::render()
sgct::Engine::instance()->getActiveModelViewProjectionMatrix() * view);
// render the scene starting from the root node
_abuffer->clear();
_abuffer->preRender();
_sceneGraph->render(_mainCamera);
_abuffer->postRender();
_abuffer->resolve();
/*
// Print some useful information on the master viewport
if (sgct::Engine::instance()->isMaster()) {
// Apple usually has retina screens
@@ -200,6 +215,7 @@ void RenderEngine::render()
sgct_text::FontManager::instance()->getFont("SGCTFont", FONT_SIZE),
FONT_SIZE, FONT_SIZE * 2, "Scaling: (%.10f, %.2f)", scaling[0], scaling[1]);
}
*/
}
SceneGraph* RenderEngine::sceneGraph()
@@ -388,4 +404,8 @@ Camera* RenderEngine::camera() const {
return _mainCamera;
}
ABuffer* RenderEngine::abuffer() const {
return _abuffer;
}
} // namespace openspace

View File

@@ -61,7 +61,9 @@ bool VolumeRaycasterBox::initialize() {
// ------ SETUP SHADER -----------------
OsEng.configurationManager().getValue("RaycastProgram", _boxProgram);
_MVPLocation = _boxProgram->uniformLocation("modelViewProjection");
_MVPLocation = _boxProgram->uniformLocation("modelViewProjection");
_modelTransformLocation = _boxProgram->uniformLocation("modelTransform");
_typeLocation = _boxProgram->uniformLocation("volumeType");
// ------ SETUP FBO ---------------------
_fbo = new FramebufferObject();
@@ -69,8 +71,6 @@ bool VolumeRaycasterBox::initialize() {
// changed from getActiveXResolution to getCurrentViewportPixelCoords because
// if there are more viewports in the same screen.
//size_t x = sgct::Engine::instance()->getActiveXResolution();
//size_t y = sgct::Engine::instance()->getActiveYResolution();
int x1, xSize, y1, ySize;
sgct::Engine::instance()->getActiveWindowPtr()->getCurrentViewportPixelCoords(x1, y1, xSize, ySize);
size_t x = xSize;
@@ -89,11 +89,13 @@ bool VolumeRaycasterBox::initialize() {
return true;
}
void VolumeRaycasterBox::render(const glm::mat4& MVP) {
void VolumeRaycasterBox::render(const glm::mat4& MVP,const glm::mat4& transform, int type) {
GLuint activeFBO = FramebufferObject::getActiveObject(); // Save SGCTs main FBO
_fbo->activate();
_boxProgram->activate();
_boxProgram->setUniform(_MVPLocation, MVP);
_boxProgram->setUniform(_MVPLocation, MVP);
_boxProgram->setUniform(_modelTransformLocation, transform);
_boxProgram->setUniform(_typeLocation, type);
sgct_core::Frustum::FrustumMode mode = sgct::Engine::instance()->
getActiveWindowPtr()->

View File

@@ -51,18 +51,18 @@ const std::string _loggerCat = "SceneGraph";
const std::string _rootNodeName = "Root";
const std::string _moduleExtension = ".mod";
void printTree(openspace::SceneGraphNode* node, std::string pre = "")
{
LDEBUGC("Tree", pre << node->nodeName());
const std::vector<openspace::SceneGraphNode*>& children = node->children();
for (openspace::SceneGraphNode* child : children)
printTree(child, pre + " ");
}
}
namespace openspace {
void printTree(SceneGraphNode* node, std::string pre = "")
{
LDEBUGC("Tree", pre << node->nodeName());
const std::vector<SceneGraphNode*>& children = node->children();
for (SceneGraphNode* child : children)
printTree(child, pre + " ");
}
SceneGraph::SceneGraph()
: _focus("Root")
, _position("Root")
@@ -82,69 +82,77 @@ bool SceneGraph::initialize()
using ghoul::opengl::ShaderObject;
using ghoul::opengl::ProgramObject;
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;
// pscstandard
{
std::string programObjectName = "pscstandard";
ProgramObject* po = new ProgramObject(programObjectName);
ShaderObject* vs = new ShaderObject( ShaderObject::ShaderType::ShaderTypeVertex,
absPath("${SHADERS}/pscstandard_vs.glsl"),
programObjectName + "Vertex");
ShaderObject* fs = new ShaderObject( ShaderObject::ShaderType::ShaderTypeFragment,
absPath("${SHADERS}/pscstandard_fs.glsl"),
programObjectName + "Fragment");
po->attachObject(vs);
po->attachObject(fs);
if ( ! po->compileShaderObjects()) return false;
if ( ! po->linkProgramObject()) return false;
OsEng.ref().configurationManager().setValue("pscShader", po);
}
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");
// RaycastProgram
{
std::string programObjectName = "RaycastProgram";
ProgramObject* po = new ProgramObject(programObjectName);
ShaderObject* vs = new ShaderObject( ShaderObject::ShaderType::ShaderTypeVertex,
absPath("${SHADERS}/exitpoints.vert"),
programObjectName + "Vertex");
ShaderObject* fs = new ShaderObject( ShaderObject::ShaderType::ShaderTypeFragment,
absPath("${SHADERS}/exitpoints.frag"),
programObjectName + "Fragment");
po->attachObject(vs);
po->attachObject(fs);
if ( ! po->compileShaderObjects()) return false;
if ( ! po->linkProgramObject()) return false;
OsEng.ref().configurationManager().setValue("RaycastProgram", po);
}
po = new ProgramObject;
po->attachObject(powerscale_vs);
po->attachObject(powerscale_fs);
// TwoPassProgram
{
std::string programObjectName = "TwoPassProgram";
ProgramObject* po = new ProgramObject(programObjectName);
ShaderObject* vs = new ShaderObject( ShaderObject::ShaderType::ShaderTypeVertex,
absPath("${SHADERS}/twopassraycaster.vert"),
programObjectName + "Vertex");
ShaderObject* fs = new ShaderObject( ShaderObject::ShaderType::ShaderTypeFragment,
absPath("${SHADERS}/twopassraycaster.frag"),
programObjectName + "Fragment");
po->attachObject(vs);
po->attachObject(fs);
if ( ! po->compileShaderObjects()) return false;
if ( ! po->linkProgramObject()) return false;
po->setUniform("texBack", 0);
po->setUniform("texFront", 1);
po->setUniform("texVolume", 2);
OsEng.ref().configurationManager().setValue("TwoPassProgram", po);
}
if (!po->compileShaderObjects())
return false;
if (!po->linkProgramObject())
return false;
OsEng.ref().configurationManager().setValue("pscShader", po);
ProgramObject* _fboProgram = new ProgramObject("RaycastProgram");
ShaderObject* vertexShader = new ShaderObject(ShaderObject::ShaderTypeVertex,
absPath("${SHADERS}/exitpoints.vert"));
ShaderObject* fragmentShader = new ShaderObject(
ShaderObject::ShaderTypeFragment, absPath("${SHADERS}/exitpoints.frag"));
_fboProgram->attachObject(vertexShader);
_fboProgram->attachObject(fragmentShader);
_fboProgram->compileShaderObjects();
_fboProgram->linkProgramObject();
ProgramObject* _twopassProgram = new ProgramObject("TwoPassProgram");
vertexShader = new ShaderObject(ShaderObject::ShaderTypeVertex,
absPath("${SHADERS}/twopassraycaster.vert"));
fragmentShader = new ShaderObject(ShaderObject::ShaderTypeFragment,
absPath("${SHADERS}/twopassraycaster.frag"));
_twopassProgram->attachObject(vertexShader);
_twopassProgram->attachObject(fragmentShader);
_twopassProgram->compileShaderObjects();
_twopassProgram->linkProgramObject();
_twopassProgram->setUniform("texBack", 0);
_twopassProgram->setUniform("texFront", 1);
_twopassProgram->setUniform("texVolume", 2);
ProgramObject* quad = new ProgramObject("Quad");
ShaderObject* quadv = new ShaderObject(ShaderObject::ShaderTypeVertex,
absPath("${SHADERS}/quadVert.glsl"));
ShaderObject* quadf = new ShaderObject(ShaderObject::ShaderTypeFragment,
absPath("${SHADERS}/quadFrag.glsl"));
quad->attachObject(quadv);
quad->attachObject(quadf);
quad->compileShaderObjects();
quad->linkProgramObject();
quad->setUniform("quadTex", 0);
OsEng.ref().configurationManager().setValue("RaycastProgram", _fboProgram);
OsEng.ref().configurationManager().setValue("TwoPassProgram", _twopassProgram);
OsEng.ref().configurationManager().setValue("Quad", quad);
// Quad
{
std::string programObjectName = "Quad";
ProgramObject* po = new ProgramObject(programObjectName);
ShaderObject* vs = new ShaderObject( ShaderObject::ShaderType::ShaderTypeVertex,
absPath("${SHADERS}/quadVert.glsl"),
programObjectName + "Vertex");
ShaderObject* fs = new ShaderObject( ShaderObject::ShaderType::ShaderTypeFragment,
absPath("${SHADERS}/quadFrag.glsl"),
programObjectName + "Fragment");
po->attachObject(vs);
po->attachObject(fs);
if ( ! po->compileShaderObjects()) return false;
if ( ! po->linkProgramObject()) return false;
po->setUniform("quadTex", 0);
OsEng.ref().configurationManager().setValue("Quad", po);
}
// Initialize all nodes
for (auto node : _nodes) {

View File

@@ -181,6 +181,7 @@ void SceneGraphNode::evaluate(const Camera* camera, const psc& parentPosition)
if (!sphereInsideFrustum(thisPosition, _boundingSphere, camera)) {
// the node is completely outside of the camera view, stop evaluating this
// node
//LFATAL(_nodeName << " is outside of frustum");
return;
}
}
@@ -198,7 +199,7 @@ void SceneGraphNode::evaluate(const Camera* camera, const psc& parentPosition)
// evaluate all the children, tail-recursive function(?)
for (auto& child : _children) {
child->evaluate(camera, psc());
child->evaluate(camera, thisPosition);
}
}
@@ -290,13 +291,22 @@ PowerScaledScalar SceneGraphNode::calculateBoundingSphere()
}
}
_boundingSphere += maxChild;
} else { // leaf
}
// if has a renderable, use that boundingsphere
if (_renderable)
_boundingSphere += _renderable->getBoundingSphere();
// if has a renderable, use that boundingsphere
if (_renderable ) {
PowerScaledScalar renderableBS = _renderable->getBoundingSphere();
if(renderableBS > _boundingSphere)
_boundingSphere = renderableBS;
}
LWARNING(_nodeName << ": " << _boundingSphere);
return _boundingSphere;
}
PowerScaledScalar SceneGraphNode::boundingSphere() const{
return _boundingSphere;
}

View File

@@ -86,16 +86,27 @@ float* KameleonWrapper::getUniformSampledValues(const std::string& var, glm::siz
int size = outDimensions.x*outDimensions.y*outDimensions.z;
float* data = new float[size];
double* doubleData = new double[size];
float varMin = _model->getVariableAttribute(var, "actual_min").getAttributeFloat();
float varMax = _model->getVariableAttribute(var, "actual_max").getAttributeFloat();
float stepX = (_xMax-_xMin)/(static_cast<float>(outDimensions.x));
float stepY = (_yMax-_yMin)/(static_cast<float>(outDimensions.y));
float stepZ = (_zMax-_zMin)/(static_cast<float>(outDimensions.z));
double varMin = _model->getVariableAttribute(var, "actual_min").getAttributeFloat();
double varMax = _model->getVariableAttribute(var, "actual_max").getAttributeFloat();
double stepX = (_xMax-_xMin)/(static_cast<double>(outDimensions.x));
double stepY = (_yMax-_yMin)/(static_cast<double>(outDimensions.y));
double stepZ = (_zMax-_zMin)/(static_cast<double>(outDimensions.z));
LDEBUG(var << "Min: " << varMin);
LDEBUG(var << "Max: " << varMax);
// HISTOGRAM
const int bins = 200;
const float truncLim = 0.9;
std::vector<int> histogram (bins,0);
auto mapToHistogram = [varMin, varMax, bins](double val) {
double zeroToOne = (val-varMin)/(varMax-varMin);
zeroToOne *= static_cast<double>(bins);
return static_cast<int>(zeroToOne);
};
for (int x = 0; x < outDimensions.x; ++x) {
progressBar(x, outDimensions.x);
@@ -106,35 +117,37 @@ float* KameleonWrapper::getUniformSampledValues(const std::string& var, glm::siz
int index = x + y*outDimensions.x + z*outDimensions.x*outDimensions.y;
if(_type == Model::BATSRUS) {
float xPos = _xMin + stepX*x;
float yPos = _yMin + stepY*y;
float zPos = _zMin + stepZ*z;
double xPos = _xMin + stepX*x;
double yPos = _yMin + stepY*y;
double zPos = _zMin + stepZ*z;
// get interpolated data value for (xPos, yPos, zPos)
float value = _interpolator->interpolate(var, xPos, yPos, zPos);
double value = _interpolator->interpolate(var, xPos, yPos, zPos);
// scale to [0,1]
data[index] = (value-varMin)/(varMax-varMin);
//doubleData[index] = (value-varMin)/(varMax-varMin);
doubleData[index] = value;
histogram[mapToHistogram(value)]++;
} else if (_type == Model::ENLIL) {
// Put r in the [0..sqrt(3)] range
float rNorm = sqrt(3.0)*(float)x/(float)(outDimensions.x-1);
double rNorm = sqrt(3.0)*(double)x/(double)(outDimensions.x-1);
// Put theta in the [0..PI] range
float thetaNorm = M_PI*(float)y/(float)(outDimensions.y-1);
double thetaNorm = M_PI*(double)y/(double)(outDimensions.y-1);
// Put phi in the [0..2PI] range
float phiNorm = 2.0*M_PI*(float)z/(float)(outDimensions.z-1);
double phiNorm = 2.0*M_PI*(double)z/(double)(outDimensions.z-1);
// Go to physical coordinates before sampling
float rPh = _xMin + rNorm*(_xMax-_xMin);
float thetaPh = thetaNorm;
double rPh = _xMin + rNorm*(_xMax-_xMin);
double thetaPh = thetaNorm;
// phi range needs to be mapped to the slightly different model
// range to avoid gaps in the data Subtract a small term to
// avoid rounding errors when comparing to phiMax.
float phiPh = _zMin + phiNorm/(2.0*M_PI)*(_zMax-_zMin-0.000001);
double phiPh = _zMin + phiNorm/(2.0*M_PI)*(_zMax-_zMin-0.000001);
float varValue = 0.f;
double varValue = 0.f;
// See if sample point is inside domain
if (rPh < _xMin || rPh > _xMax || thetaPh < _yMin ||
thetaPh > _yMax || phiPh < _zMin || phiPh > _zMax) {
@@ -155,7 +168,7 @@ float* KameleonWrapper::getUniformSampledValues(const std::string& var, glm::siz
varValue = _interpolator->interpolate(var, rPh, thetaPh, phiPh);
}
data[index] = (varValue-varMin)/(varMax-varMin);
doubleData[index] = (varValue-varMin)/(varMax-varMin);
}
}
}
@@ -163,6 +176,30 @@ float* KameleonWrapper::getUniformSampledValues(const std::string& var, glm::siz
std::cout << std::endl;
LINFO("Done!");
int sum = 0;
int stop;
const int sumuntil = size * truncLim;
for(int i = 0; i < bins-1; ++i) {
sum += histogram[i];
if(sum + histogram[i+1] > sumuntil) {
stop = i;
LDEBUG("====================");
break;
}
LDEBUG(histogram[i]);
}
double dist = varMax - varMin;
dist = (dist / static_cast<double>(bins)) * static_cast<double>(stop);
varMax = varMin + dist;
for(int i = 0; i < size; ++i) {
double normalizedVal = (doubleData[i]-varMin)/(varMax-varMin);
data[i] = static_cast<float>(glm::clamp(normalizedVal, 0.0, 1.0));
}
delete[] doubleData;
return data;
}