Removed Flare

This commit is contained in:
Jonas Strandstedt
2014-10-23 15:35:55 +02:00
parent 5e410c6816
commit 3ee8f85c14
30 changed files with 1 additions and 5429 deletions
@@ -34,18 +34,7 @@
#include <openspace/interaction/interactionhandler.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/engine/configurationmanager.h>
#include <ghoul/opencl/clcontext.h>
#include <ghoul/opencl/clcommandqueue.h>
#include <ghoul/opencl/clprogram.h>
#include <ghoul/opencl/clkernel.h>
#include <ghoul/cmdparser/commandlineparser.h>
// #define FLARE_ONLY
#include <openspace/flare/flare.h>
// #define OPENSPACE_VIDEO_EXPORT
namespace openspace {
@@ -69,7 +58,6 @@ public:
static bool findConfiguration(std::string& filename);
ConfigurationManager& configurationManager();
ghoul::opencl::CLContext& clContext();
InteractionHandler& interactionHandler();
RenderEngine& renderEngine();
scripting::ScriptEngine& scriptEngine();
@@ -105,14 +93,6 @@ private:
RenderEngine _renderEngine;
scripting::ScriptEngine _scriptEngine;
ghoul::cmdparser::CommandlineParser _commandlineParser;
#ifdef OPENSPACE_VIDEO_EXPORT
bool _doVideoExport;
#endif
#ifdef FLARE_ONLY
Flare* _flare;
#endif
// ScriptEngine* _scriptEngine;
ghoul::opencl::CLContext _context;
SyncBuffer* _syncBuffer;
-63
View File
@@ -1,63 +0,0 @@
#ifndef ANIMATOR_H
#define ANIMATOR_H
/*
* Author: Victor Sand (victor.sand@gmail.com)
* Encapsulates animation logic
*
*/
namespace osp {
class Config;
class Animator {
public:
static Animator * New(Config *_config);
// Signals the animator to update its state if needed
void Update(float _elapsedTime);
// Pauses if unpaused, unpauses if paused
void TogglePause();
// If FPS mode is on, don't wait. Update every timestep.
void ToggleFPSMode();
void SetPaused(bool _paused);
void SetFPSMode(bool _fpsMode);
void ManualTimestep(int _manualTimestep);
unsigned int CurrentTimestep() const { return currentTimestep_; }
unsigned int NextTimestep() const {
return currentTimestep_ < numTimesteps_-1 ? currentTimestep_+1 : 0;
}
void SetCurrentTimestep(unsigned int _timestep);
void SetNumTimesteps(unsigned int _numTimesteps);
void IncTimestep();
void DecTimestep();
bool UpdateConfig();
private:
Animator();
Animator(Config *_config);
Animator(const Animator&) { }
Config *config_;
// Number of timesteps before looping occurs
unsigned int numTimesteps_;
// Current timestep, the output of the Animator
unsigned int currentTimestep_;
bool fpsMode_;
bool paused_;
// Keeps track of elapsed time between timestep updates
float elapsedTime_;
// Time before timestep gets updates
float refreshInterval_;
};
}
#endif
-154
View File
@@ -1,154 +0,0 @@
/*
* Author: Victor Sand (victor.sand@gmail.com)
*
*/
#ifndef BRICKMANAGER_H
#define BRICKMANAGER_H
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <fstream>
//#include <boost/timer/timer.hpp>
#include <stdio.h>
#include <ghoul/opengl/texture.h>
// Make sure we get 64 bits for offset
#define _FILE_OFFSET_BITS 64
// For easy switching between offset types
#define off off64_t
namespace osp {
class Config;
class BrickManager {
public:
static BrickManager * New(Config *_config);
~BrickManager();
Config *config_;
enum BUFFER_INDEX { EVEN = 0, ODD };
// Read header data from file, should normally only be called once
// unless header data changes
bool ReadHeader();
bool InitAtlas();
// Build brick list from request list
// Resets values in _brickRequest to 0
bool BuildBrickList(BUFFER_INDEX _bufIdx, std::vector<int> &_brickRequest);
// Upload bricks from memory buffer to PBO using the brick list
bool DiskToPBO(BUFFER_INDEX _pboIndex);
// Init transfer from PBO to texture atlas
bool PBOToAtlas(BUFFER_INDEX _pboIndex);
std::vector<int> BrickList(BUFFER_INDEX _bufIdx) {
return brickLists_[_bufIdx];
}
ghoul::opengl::Texture * TextureAtlas() { return textureAtlas_; }
// Header accessors
unsigned int GridType() const { return gridType_; }
unsigned int NumOrigTimesteps() const { return numOrigTimesteps_; }
unsigned int NumTimesteps() const { return numTimesteps_; }
unsigned int XBrickDim() const { return xBrickDim_; }
unsigned int YBrickDim() const { return yBrickDim_; }
unsigned int ZBrickDim() const { return zBrickDim_; }
unsigned int XNumBricks() const { return xNumBricks_; }
unsigned int YNumBricks() const { return yNumBricks_; }
unsigned int ZNumBricks() const { return zNumBricks_; }
unsigned int PaddingWidth() const { return paddingWidth_; }
unsigned int DataSize() const { return dataSize_; }
private:
BrickManager();
BrickManager(Config *_config);
BrickManager(const BrickManager&);
// Header data
unsigned int gridType_;
unsigned int numOrigTimesteps_;
unsigned int numTimesteps_;
unsigned int xBrickDim_;
unsigned int yBrickDim_;
unsigned int zBrickDim_;
unsigned int xNumBricks_;
unsigned int yNumBricks_;
unsigned int zNumBricks_;
unsigned int dataSize_;
unsigned int numBricks_;
unsigned int brickDim_;
unsigned int paddedBrickDim_;
unsigned int atlasDim_;
const unsigned int paddingWidth_ = 1;
unsigned int numBrickVals_;
unsigned int numBricksFrame_;
unsigned int numBricksTree_;
unsigned int brickSize_;
unsigned int volumeSize_;
unsigned int numValsTot_;
// Texture coordinates to be assigned
int xCoord_;
int yCoord_;
int zCoord_;
// Texture where the actual atlas is kept
ghoul::opengl::Texture *textureAtlas_;
std::vector<std::vector<int> > brickLists_;
// C-style I/O
std::FILE *file_;
#ifdef WIN32
long long dataPos_;
#else
off_t dataPos_;
#endif
bool hasReadHeader_;
bool atlasInitialized_;
// PBOs
unsigned int pboHandle_[2];
// Caching, one for each PBO
std::vector<std::vector<int> > bricksInPBO_;
std::vector<std::vector<bool> > usedCoords_;
// Increment the coordinate to be assigned (handle looping)
void IncCoord();
// Linear version of the current x, y, z coordinate to be assigned
unsigned int LinearCoord(int _x, int _y, int _z);
// 3D coordinates from linear index
void CoordsFromLin(int _idx, int &_x, int &_y, int &_z);
// Fill a brick in the volume using a pointer to flattened brick data
bool FillVolume(float *_in,
float *_out,
unsigned int _x,
unsigned int _y,
unsigned int _z);
// Timer and timer constants
//boost::timer::cpu_timer timer_;
const double BYTES_PER_GB = 1073741824.0;
};
}
#endif
-139
View File
@@ -1,139 +0,0 @@
/*
* Author: Victor Sand (victor.sand@gmail.com)
*
*/
#ifndef CL_MANAGER_H_
#define CL_MANAGER_H_
#include <ghoul/opencl/ghoul_cl.h>
#include <ghoul/opencl/clcontext.h>
#include <ghoul/opencl/clcommandqueue.h>
#include <ghoul/opencl/clprogram.h>
#include <ghoul/opencl/clkernel.h>
#include <ghoul/opencl/clutil.h>
#include <ghoul/opencl/clworksize.h>
#include <map>
#include <string>
#include <openspace/flare/KernelConstants.h>
namespace osp {
class TransferFunction;
class CLProgram;
class TSP;
class CLManager {
public:
static CLManager * New();
~CLManager();
// Different queue indices for working with asynchronous uploads/executions
enum QueueIndex { EXECUTE, TRANSFER, NUM_QUEUE_INDICES };
enum TextureType { TEXTURE_1D, TEXTURE_2D, TEXTURE_3D };
enum Permissions { READ_ONLY, WRITE_ONLY, READ_WRITE };
enum AllocMode { USE_HOST_PTR, ALLOC_HOST_PTR, COPY_HOST_PTR };
// These four functions should be run in this order
bool InitPlatform();
bool InitDevices();
bool CreateContext();
bool CreateCommandQueue();
// Name a program and create it from source text file
bool CreateProgram(std::string _programName, std::string _fileName);
// Build program after creation
bool BuildProgram(std::string _programName);
// Create kernel after building program
bool CreateKernel(std::string _programName);
// Add an OpenGL texture to a program
bool AddTexture(std::string _programName, unsigned int _argNr,
ghoul::opengl::Texture *_texture, TextureType _textureType,
Permissions _permissions);
bool AddTexture(std::string _programName, unsigned int _argNr,
ghoul::opengl::Texture *_texture, TextureType _textureType,
Permissions _permissions, cl_mem& _clTextureMem);
bool AddTexture(std::string _programName, unsigned int _argNr,
cl_mem _texture, Permissions _permissions);
bool AddBuffer(std::string _programName, unsigned int _argNr,
void *_hostPtr, unsigned int _sizeInBytes,
AllocMode _allocMode, Permissions _permissions);
bool ReadBuffer(std::string _programName, unsigned int _argNr,
void *_hostPtr, unsigned int _sizeInBytes,
bool _blocking);
// Free resources
bool ReleaseBuffer(std::string _programName, unsigned int _argNr);
// Set the value of an integer argument
bool SetInt(std::string _programName, unsigned int _argNr, int _val);
// Aquire any shared textures, set up kernel arguments etc
bool PrepareProgram(std::string _programName);
// Launch program kernel (returns immediately)
bool LaunchProgram(std::string _programName,
unsigned int _gx, unsigned int _gy,
unsigned int _lx, unsigned int _ly);
// Wait for kernel to finish, releaste any shared resources
bool FinishProgram(std::string _programName);
// Finish all commands in a command queue
// Can be used e.g. to sync a DMA transfer operation
bool FinishQueue(QueueIndex _queueIndex);
friend class CLProgram;
private:
CLManager();
CLManager(const CLManager&);
// Read kernel source from file, return char array
// Store number of chars in _numChar argument
char * ReadSource(std::string _fileName, int &_numChars) const;
// Check state in a cl_int, print error if state is not CL_SUCCESS
bool CheckSuccess(cl_int _error, std::string _location) const;
// Translate cl_int enum to readable string
std::string ErrorString(cl_int _error) const;
// Convert CLManager::Permissions to cl_mem_flags
cl_mem_flags ConvertPermissions(Permissions _permissions);
// Conver CLManager::AllocMode to cl_mem_flags
cl_mem_flags ConvertAllocMode(AllocMode _allocMode);
static const unsigned int MAX_PLATFORMS = 32;
static const unsigned int MAX_DEVICES = 32;
static const unsigned int MAX_NAME_LENGTH = 128;
// Used for storing and reading error state during function calls
cl_int error_;
cl_uint numPlatforms_;
cl_platform_id platforms_[MAX_PLATFORMS];
cl_uint numDevices_;
cl_device_id devices_[MAX_DEVICES];
// Maximum allocatable size for each device
cl_ulong maxMemAllocSize_[MAX_DEVICES];
char deviceName_[MAX_NAME_LENGTH];
char driverVersion_[MAX_NAME_LENGTH];
char platformVersion_[MAX_NAME_LENGTH];
//cl_context context_;
ghoul::opencl::CLCommandQueue commandQueues_[NUM_QUEUE_INDICES];
// Programs are mapped using strings
std::map<std::string, CLProgram*> clPrograms_;
ghoul::opencl::CLContext _context;
};
}
#endif
-93
View File
@@ -1,93 +0,0 @@
/*
* Victor Sand (victor.sand@gmail.com)
*
*/
#ifndef CL_PROGRAM_H_
#define CL_PROGRAM_H_
#include <ghoul/opencl/ghoul_cl.h>
#include <map>
#include <string>
#include <openspace/flare/KernelConstants.h>
#include <ghoul/opengl/texture.h>
namespace osp {
class CLManager;
class TransferFunction;
class Texture;
class CLProgram {
public:
static CLProgram * New(const std::string &_programName,
CLManager *_clManager);
~CLProgram();
struct MemArg {
size_t size_;
cl_mem mem_;
};
cl_program Program() { return program_; }
cl_kernel Kernel() { return kernel_; }
cl_int Error() { return error_; }
bool CreateProgram(std::string _fileName);
bool BuildProgram();
bool CreateKernel();
bool AddTexture(unsigned int _argNr, ghoul::opengl::Texture *_texture,
GLuint _textureType,
cl_mem_flags _permissions);
bool AddTexture(unsigned int _argNr, ghoul::opengl::Texture *_texture,
GLuint _textureType,
cl_mem_flags _permissions, cl_mem& _clTextureMem);
bool AddTexture(unsigned int _argNr, cl_mem _texture,
cl_mem_flags _permissions);
bool AddBuffer(unsigned int _argNr,
void *_hostPtr,
unsigned int _sizeInBytes,
cl_mem_flags _allocMode,
cl_mem_flags _permissions);
bool ReadBuffer(unsigned int _argNr,
void *_hostPtr,
unsigned int _sizeInBytes,
cl_bool _blocking);
bool ReleaseBuffer(unsigned int _argNr);
bool SetInt(unsigned int _argNr, int _val);
bool PrepareProgram();
bool LaunchProgram(unsigned int _gx, unsigned int _gy,
unsigned int _lx, unsigned int _ly);
bool FinishProgram();
private:
CLProgram(const std::string &_programName, CLManager *_clManager);
CLProgram();
CLProgram(const CLProgram&);
char * ReadSource(const std::string &_fileName, int &_numChars) const;
std::string programName_;
CLManager *clManager_;
cl_program program_;
cl_kernel kernel_;
cl_int error_;
// Stores device OGL textures together with their kernel arg nummer
std::map<cl_uint, cl_mem> OGLTextures_;
// Stores non-texture memory buffer arguments
std::map<cl_uint, MemArg> memArgs_;
};
}
#endif
-109
View File
@@ -1,109 +0,0 @@
/*
* Author: Victor Sand (victor.sand@gmail.com)
*
* Simple functionality to read, save and access constants.
* Reads the specified file as soon as the object is created.
*
*/
#ifndef CONFIG_H_
#define CONFIG_H_
#include <string>
namespace osp {
class Config {
public:
static Config * New(const std::string &_configFilename);
~Config();
// Reads the config file, can be called by external modules
bool Read();
int WinWidth() const { return winWidth_; }
int WinHeight() const { return winHeight_; }
bool ClearCache() const { return clearCache_; }
int TextureDivisionFactor() const { return textureDivisionFactor_; }
unsigned int LocalWorkSizeX() const { return localWorkSizeX_; }
unsigned int LocalWorkSizeY() const { return localWorkSizeY_; }
std::string TSPFilename() const { return TSPFilename_; }
std::string TFFilename() const { return TFFilename_; }
std::string RaycasterKernelFilename()const{return raycasterKernelFilename_;}
std::string TSPTraversalKernelFilename() const
{ return TSPTraversalKernelFilename_; }
std::string CubeShaderVertFilename() const { return cubeShaderVertFilename_;}
std::string CubeShaderFragFilename() const { return cubeShaderFragFilename_;}
std::string QuadShaderVertFilename() const { return quadShaderVertFilename_;}
std::string QuadShaderFragFilename() const { return quadShaderFragFilename_;}
float SpatialErrorTolerance() const { return spatialErrorTolerance_; }
float TemporalErrorTolerance() const { return temporalErrorTolerance_; }
float TSPTraversalStepsize() const { return TSPTraversalStepsize_; }
float RaycasterStepsize() const { return raycasterStepsize_; }
float RaycasterIntensity() const { return raycasterIntensity_; }
float AnimatorRefreshInterval() const { return animatorRefreshInterval_; }
float MousePitchFactor() const { return mousePitchFactor_; }
float MouseRollFactor() const { return mouseRollFactor_; }
float ZoomFactor() const { return zoomFactor_; }
float StartPitch() const { return startPitch_; }
float StartRoll() const { return startRoll_; }
float StartYaw() const { return startYaw_; }
float TranslateX() const { return translateX_; }
float TranslateY() const { return translateY_; }
float TranslateZ() const { return translateZ_; }
int CalculateError() const { return calculateError_; }
float PitchSpeed() const { return pitchSpeed_; }
float RollSpeed() const { return rollSpeed_; }
float YawSpeed() const { return yawSpeed_; }
bool TakeScreenshot() const { return takeScreenshot_; }
private:
Config();
Config(const std::string &_configFilename);
Config(const Config&);
std::string configFilename_;
int winWidth_;
int winHeight_;
bool clearCache_;
int textureDivisionFactor_;
unsigned int localWorkSizeX_;
unsigned int localWorkSizeY_;
std::string TSPFilename_;
std::string TFFilename_;
std::string raycasterKernelFilename_;
std::string TSPTraversalKernelFilename_;
std::string cubeShaderVertFilename_;
std::string cubeShaderFragFilename_;
std::string quadShaderVertFilename_;
std::string quadShaderFragFilename_;
float spatialErrorTolerance_;
float temporalErrorTolerance_;
float TSPTraversalStepsize_;
float raycasterStepsize_;
float raycasterIntensity_;
float animatorRefreshInterval_;
float mousePitchFactor_;
float mouseRollFactor_;
float zoomFactor_;
float startPitch_;
float startRoll_;
float startYaw_;
float translateX_;
float translateY_;
float translateZ_;
int calculateError_;
float pitchSpeed_;
float rollSpeed_;
float yawSpeed_;
bool takeScreenshot_;
};
}
#endif
-37
View File
@@ -1,37 +0,0 @@
#ifndef KERNELCONSTANTS_H_
#define KERNELCONSTANTS_H_
/*
Author: Victor Sand (victor.sand@gmail.com)
Simple structs to gather constants used in kernel
*/
namespace osp {
struct KernelConstants {
int gridType_;
float stepsize_;
float intensity_;
int numTimesteps_;
int numValuesPerNode_;
int numOTNodes_;
int numBoxesPerAxis_;
float temporalTolerance_;
float spatialTolerance_;
int rootLevel_;
int paddedBrickDim_;
};
struct TraversalConstants {
int gridType_;
float stepsize_;
int numTimesteps_;
int numValuesPerNode_;
int numOTNodes_;
float temporalTolerance_;
float spatialTolerance_;
};
}
#endif
-65
View File
@@ -1,65 +0,0 @@
#ifndef MAPPINGKEY_H
#define MAPPINGKEY_H
/*
Author: Victor Sand (victor.sand@gmail.com)
Mapping key used in transfer function. A key includes an intensity
for which the key is active, and RGBA values for that specific intensity.
*/
#include <iostream>
#include <openspace/flare/Utils.h>
namespace osp {
class MappingKey {
public:
MappingKey();
MappingKey(const MappingKey &_mappingKey);
MappingKey(float _intensity, unsigned int _r, unsigned int _g,
unsigned int _b, unsigned int _a);
~MappingKey();
float Intensity() const { return intensity_; }
unsigned int R() const { return r_; }
unsigned int G() const { return g_; }
unsigned int B() const { return b_; }
unsigned int A() const { return a_; }
unsigned int Channel(unsigned int _channel) const {
switch (_channel) {
case 0:
return r_;
case 1:
return g_;
case 2:
return b_;
case 3:
return a_;
default:
ERROR("Invalid channel, returning 0");
return 0;
}
}
void SetValues(float _intensity, unsigned int _r, unsigned int _g,
unsigned int _b, unsigned int _a);
// Comparsion by intensity for sorting purposes
bool operator<(const MappingKey &_mappingKey) const;
MappingKey & operator=(const MappingKey &_mappingKey);
private:
float intensity_;
unsigned int r_;
unsigned int g_;
unsigned int b_;
unsigned int a_;
};
}
std::ostream& operator<<(std::ostream &os,
const osp::MappingKey &_mappingKey);
#endif
-196
View File
@@ -1,196 +0,0 @@
#ifndef RAYCASTER_H_
#define RAYCASTER_H_
/*
Author: Victor Sand (victor.sand@gmail.com)
Mammoth workhorse class that ties all parts of the raycaster application
together. Manages state, render calls and a lot of initializations.
TODO: Iteratively break away parts from it into other classes.
*/
#include <openspace/flare/Renderer.h>
#include <map>
#include <string>
#include <vector>
#include <ghoul/glm.h>
#include <ghoul/opencl/ghoul_cl.h>
#include <openspace/flare/KernelConstants.h>
//#include <boost/timer/timer.hpp>
#include <openspace/flare/TSP.h>
#include <ghoul/opengl/programobject.h>
#include <ghoul/opengl/texture.h>
namespace osp {
class TransferFunction;
class Animator;
class BrickManager;
class CLManager;
class Config;
class Raycaster : public Renderer {
public:
static Raycaster * New(Config *_config);
virtual ~Raycaster();
virtual bool Render(float _timestep);
// Called by the SGCT window manager
bool Reload();
// Init pipeline for double buffered setup
bool InitPipeline();
// Reload GLSL shaders
bool ReloadShaders();
// Reload transfer function file
bool ReloadTransferFunctions();
// Initialize the color cube used for raycasting.
// TODO Make cube class.
bool InitCube();
// Init the quad used for output texture rendering
bool InitQuad();
// Run all of CLHandlers initialization functions
bool InitCL();
// Set up buffers for the different rendering stages
bool InitFramebuffers();
// Set up two pixel buffers for texture streaming
bool InitPixelBuffers();
// Update matrices with current view parameters
bool UpdateMatrices();
// Bind transformation matrices to a ShaderProgram
bool BindTransformationMatrices(ghoul::opengl::ProgramObject *_program);
// Read kernel config from file and voxel data,
// update the constants that get sent to the kernel every frame
bool UpdateKernelConfig();
// For keyboard handling, retrieve the last known state of a key
bool KeyLastState(int _key) const;
// Add a transfer function to the transfer function list
// TODO Actually support and make use of multiple TFs
void AddTransferFunction(TransferFunction *_transferFunction);
ghoul::opengl::Texture * CubeFrontTexture() const { return cubeFrontTex_; }
ghoul::opengl::Texture * CubeBackTexture() const { return cubeBackTex_; }
ghoul::opengl::Texture * QuadTexture() const { return quadTex_; }
void SetKernelConfigFilename(const std::string &_filename);
void SetCubeFrontTexture(ghoul::opengl::Texture *_cubeFrontTexture);
void SetCubeBackTexture(ghoul::opengl::Texture *_cubeBackTexture);
void SetQuadTexture(ghoul::opengl::Texture *_quadTexture);
void SetCubeShaderProgram(ghoul::opengl::ProgramObject *_cubeShaderProgram);
void SetQuadShaderProgram(ghoul::opengl::ProgramObject *_quadShaderProgram);
void SetAnimator(Animator *_animator);
void SetCLManager(CLManager *_clManager);
void SetBrickManager(BrickManager *_brickManager);
void SetTSP(TSP *_tsp);
// SGCT
void SetModelParams(float _pitch, float _yaw, float _roll);
void SetViewParams(float _translateX, float _translateY, float _translateZ);
private:
Raycaster();
Raycaster(Config *_config);
Config *config_;
// VAO handles
unsigned int cubeVAO_;
unsigned int quadVAO_;
// Buffer object handles
unsigned int cubeFrontFBO_;
unsigned int cubeBackFBO_;
unsigned int renderbufferObject_;
unsigned int cubePosbufferObject_;
unsigned int quadPosbufferObject_;
unsigned int cubePositionAttrib_;
unsigned int quadPositionAttrib_;
// Shaders
ghoul::opengl::ProgramObject *cubeShaderProgram_;
ghoul::opengl::ProgramObject *quadShaderProgram_;
// Textures
ghoul::opengl::Texture *cubeFrontTex_;
ghoul::opengl::Texture *cubeBackTex_;
ghoul::opengl::Texture *quadTex_;
ghoul::opengl::Texture *volumeTex_;
// Model params
float pitch_;
float yaw_;
float roll_;
// View
float translateX_;
float translateY_;
float translateZ_;
// Tranformation matrices
glm::mat4 model_;
glm::mat4 view_;
glm::mat4 proj_;
// State
bool cubeInitialized_;
bool quadInitialized_;
bool framebuffersInitialized_;
bool pingPong_; // texture streaming
// Animator to control update rate and looping
Animator * animator_;
// Used to see if it is time to update frames
unsigned int lastTimestep_;
// Used for ping pong memory buffering
unsigned int pingPongIndex_;
// Kernel constants
KernelConstants kernelConstants_;
TraversalConstants traversalConstants_;
std::string kernelConfigFilename_;
// Transfer functions
std::vector<TransferFunction*> transferFunctions_;
// Brick manager with access to brick data
BrickManager *brickManager_;
bool LaunchTSPTraversal(unsigned int _timestep);
// Brick request list
std::vector<int> brickRequest_;
// TSP tree structure (not actual data)
TSP *tsp_;
// Entry point for all things OpenCL
CLManager *clManager_;
// Helper function for updating and binding kernel constants
bool UpdateKernelConstants();
// For the corresponding CL kernel
static const unsigned int cubeFrontArg_ = 0;
static const unsigned int cubeBackArg_ = 1;
static const unsigned int quadArg_ = 2;
static const unsigned int textureAtlasArg_ = 3;
static const unsigned int constantsArg_ = 4;
static const unsigned int transferFunctionArg_ = 5;
static const unsigned int tspArg_ = 6;
static const unsigned int brickListArg_ = 7;
static const unsigned int timestepArg_ = 8;
static const unsigned int tspCubeFrontArg_ = 0;
static const unsigned int tspCubeBackArg_ = 1;
static const unsigned int tspConstantsArg_ = 2;
static const unsigned int tspTSPArg_ = 3;
static const unsigned int tspBrickListArg_ = 4;
static const unsigned int tspTimestepArg_ = 5;
// Timer and timer constants
//boost::timer::cpu_timer timer_;
cl_mem cubeFrontCLmem;
cl_mem cubeBackCLmem;
};
}
#endif
-45
View File
@@ -1,45 +0,0 @@
#ifndef RENDERER_H
#define RENDERER_H
/*
Author: Victor Sand (victor.sand@gmail.com)
Renderer abstract class, Render() functions needs to be
implemented by subclasses.
TODO No real use right now but to handle key and mouse state
TODO Write better and manageable key state functionality
*/
#include <map>
namespace osp {
class Renderer {
public:
virtual bool Render(float _timestep) = 0;
virtual ~Renderer();
void SetKeyPressed(int _key, bool _pressed);
bool KeyPressed(int _key) const;
void SetWinWidth(unsigned int _winWidth);
void SetWinHeight(unsigned int _winHeight);
void SetMousePosition(float _mouseX, float _mouseY);
void SetMousePressed(bool _leftPressed, bool _rightPressed);
float FPS() const;
protected:
Renderer();
// Window
unsigned int winWidth_;
unsigned int winHeight_;
// Mouse
bool leftMouseDown_;
bool rightMouseDown_;
float currentMouseX_;
float currentMouseY_;
float lastMouseX_;
float lastMouseY_;
// Keyboard
std::map<int, bool> keysPressed_; // Is key pressed or not?
};
}
#endif
-154
View File
@@ -1,154 +0,0 @@
/*
* Author: Victor Sand (victor.sand@gmail.com)
*
* Construct a traversable TSP structure with structure and error info
* from a .tsp file
*
*/
#ifndef TSP_H_
#define TSP_H_
// Make sure to use 64 bits for file offset
#define _FILE_OFFSET_BITS 64
// For easy switching between offset types
// (off_t, off64_t etc)
#define off off64_t
#include <vector>
#include <list>
#include <string>
#include <iostream>
namespace osp {
class Config;
class TransferFunction;
class TSP {
public:
enum NodeData {
BRICK_INDEX = 0,
CHILD_INDEX,
SPATIAL_ERR,
TEMPORAL_ERR,
NUM_DATA
};
static TSP * New(Config * _config);
~TSP();
// Struct for convenience
// Note: UNUSED in this implementation
struct Color {
Color() {
r = g = b = a = 0.f;
}
Color(float _r, float _g, float _b, float _a) {
r = _r;
g = _g;
b = _b;
a = _a;
}
float r;
float g;
float b;
float a;
};
// Tries to read cached file
bool ReadCache();
// Write structure to cache
bool WriteCache();
bool ReadHeader();
// Functions to build TSP tree and calculate errors
bool Construct();
bool CalculateSpatialError();
bool CalculateTemporalError();
int * Data() { return &data_[0]; }
size_t Size() { return data_.size(); }
// TODO support dimensions of differens sizes
unsigned int BrickDim() const { return xBrickDim_; }
unsigned int PaddedBrickDim() const { return paddedBrickDim_; }
unsigned int NumBricksPerAxis() const { return xNumBricks_; }
unsigned int NumOrigTimesteps() const { return numOrigTimesteps_; }
unsigned int NumTimesteps() const { return numTimesteps_; }
unsigned int NumTotalNodes() const { return numTotalNodes_; }
unsigned int NumValuesPerNode() const { return NUM_DATA; }
unsigned int NumBSTNodes() const { return numBSTNodes_; }
unsigned int NumOTNodes() const { return numOTNodes_; }
unsigned int NumOTLevels() const { return numOTLevels_; }
private:
TSP();
TSP(Config *_config);
TSP(const TSP&);
Config *config_;
// Holds the actual structure
std::vector<int> data_;
// Data from file
unsigned int gridType_;
unsigned int numOrigTimesteps_;
unsigned int numTimesteps_;
unsigned int xBrickDim_;
unsigned int yBrickDim_;
unsigned int zBrickDim_;
unsigned int xNumBricks_;
unsigned int yNumBricks_;
unsigned int zNumBricks_;
//unsigned int dataSize_;
// Additional metadata
unsigned int paddedBrickDim_;
unsigned int numTotalNodes_;
unsigned int numBSTLevels_;
unsigned int numBSTNodes_;
unsigned int numOTLevels_;
unsigned int numOTNodes_;
const unsigned int paddingWidth_ = 1;
// Error stats
float minSpatialError_;
float maxSpatialError_;
float medianSpatialError_;
float minTemporalError_;
float maxTemporalError_;
float medianTemporalError_;
// Returns a list of the octree leaf nodes that a given input
// brick covers. If the input is already a leaf, the list will
// only contain that one index.
std::list<unsigned int> CoveredLeafBricks(unsigned int _brickIndex);
// Returns a list of the BST leaf nodes that a given input brick
// covers (at the same spatial subdivision level).
std::list<unsigned int> CoveredBSTLeafBricks(unsigned int _brickIndex);
// Return a list of eight children brick incices given a brick index
std::list<unsigned int> ChildBricks(unsigned int _brickIndex);
//std::ios::pos_type dataPos_;
// Position of first data entry (after header)
off_t dataPos_;
// Calculate weighted square distance between two RGBA colors
// c2 should be an averaged or zero color
float SquaredDist(Color _c1, Color _c2);
};
}
#endif
-24
View File
@@ -1,24 +0,0 @@
#ifndef TIMER_H_
#define TIMER_H_
/*
* Author: Victor Sand (victor.sand@gmail.com)
*
*/
namespace osp {
class Timer {
public:
Timer();
void Start();
void Stop();
void Print();
private:
float elapsedTime_;
};
}
#endif;
@@ -1,87 +0,0 @@
#ifndef TRANSFERFUNCTION_H
#define TRANSFERFUNCTION_H
/*
Author: Victor Sand (victor.sand@gmail.com)
Transfer function class that consists of a number of MappingKeys. When
the mapping keys are added, the transfer function can be constructed by
interpolating between the MappingKey values.
TODO Use Texture1D for implementation when OpenCL 1.2 is supported
*/
#include <openspace/flare/MappingKey.h>
#include <set>
#include <string>
#include <iostream>
#include <ghoul/opengl/texture.h>
namespace osp {
class TransferFunction {
public:
static TransferFunction * New();
~TransferFunction();
struct Color {
float r;
float g;
float b;
float a;
};
enum Interpolation {
LINEAR = 0,
};
// Host side sample
bool Sample(float &_r, float &_g, float &_b, float &_a, float _i);
// Take the saved values and construct a texture
bool ConstructTexture();
// Read TF from the in file
bool ReadFile();
std::string ToString() const;
// Mutators
void SetInFilename(const std::string &_inFilename);
// Accessors
unsigned int Width() const { return width_; }
ghoul::opengl::Texture * Texture() { return texture_; }
// TODO temp
float * FloatData() { return floatData_; }
// Operators
TransferFunction& operator=(const TransferFunction &_tf);
private:
TransferFunction();
TransferFunction(const TransferFunction &_tf);
float *floatData_;
ghoul::opengl::Texture *texture_;
unsigned int width_;
float lower_;
float upper_;
bool generatedTexture_;
std::string inFilename_;
std::set<MappingKey> mappingKeys_;
Interpolation interpolation_;
// Linearly interpolate between two values. Distance
// is assumed to be normalized.
inline float Lerp(float _v0, float _v1, float _d) {
return _v0*(1.0 - _d) + _v1*_d;
}
};
}
std::ostream & operator<<(std::ostream &os, const osp::TransferFunction &_tf);
#endif
-25
View File
@@ -1,25 +0,0 @@
/*
Auhtor: Victor Sand (victor.sand@gmail.com)
Global helper functions and utilities
*/
#ifndef UTILS_H_
#define UTILS_H_
#include <iostream>
namespace osp {
#define INFO(x) std::cout << x << std::endl;
#define DEBUG(x) std::cout << "DEBUG: " << x << std::endl
#define ERROR(x) std::cout << "ERROR: " << x << std::endl
#define WARNING(x) std::cout << "WARNING: " << x << std::endl
// Print the last GL error if there is one, function returns the code for
// the error so that it can be compared to GL_NO_ERROR, for example
unsigned int CheckGLError(std::string _location);
}
#endif
-94
View File
@@ -1,94 +0,0 @@
/*****************************************************************************************
* *
* 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. *
****************************************************************************************/
// Source is still in here to cannibalize later (ab)
//#ifndef __FLARE_H__
//#define __FLARE_H__
//
//#include <GL/glew.h>
//#include <ghoul/logging/logmanager.h>
//#define SGCT_WINDOWS_INCLUDE
//#include <sgct.h>
//#include <openspace/flare/Animator.h>
//#include <openspace/flare/Raycaster.h>
//#include <openspace/flare/Config.h>
//#include <openspace/rendering/renderable.h>
//
//namespace openspace {
//
//class Flare: public Renderable {
//public:
// Flare();
// ~Flare();
//
// bool initialize();
// bool deinitialize();
//
// virtual void render(const Camera *camera, const psc& thisPosition, RuntimeData* runtimeData);
// virtual void update();
//
// void render();
// void initNavigation();
//
// void keyboard(int key, int action);
// void mouse(int button, int action);
// void preSync();
// void postSyncPreDraw();
// void postDraw();
// void encode();
// void decode();
//
//private:
// void init();
//
// osp::Config* _config;
// osp::Raycaster* _raycaster;
// osp::Animator* _animator;
//
// sgct::SharedInt _timeStep;
// sgct::SharedBool _animationPaused;
// sgct::SharedBool _fpsMode;
// sgct::SharedFloat _elapsedTime;
// sgct::SharedInt _manualTimestep;
// sgct::SharedFloat _pitch;
// sgct::SharedFloat _yaw;
// sgct::SharedFloat _roll;
// sgct::SharedFloat _translateX;
// sgct::SharedFloat _translateY;
// sgct::SharedFloat _translateZ;
// sgct::SharedBool _reloadFlag;
//
// float _oldTime;
// float _currentTime;
// bool _leftMouseButton;
// double _currentMouseX;
// double _currentMouseY;
// double _lastMouseX;
// double _lastMouseY;
//};
//
//} // namespace openspace
//
//#endif // __FLARE_H__
+1
View File
@@ -26,6 +26,7 @@
#include <openspace/engine/openspaceengine.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/opengl/texture.h>
#include <ghoul/logging/logmanager.h>
#include <sgct.h>
-33
View File
@@ -243,13 +243,6 @@ bool OpenSpaceEngine::initialize() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
GLFWwindow* win = sgct::Engine::instance()->getActiveWindowPtr()->getWindowHandle();
glfwSwapBuffers(win);
//int samples = sqrt(sgct::Engine::instance()->getActiveWindowPtr()->getNumberOfAASamples());
//LDEBUG("samples: " << samples);
// Register the filepaths from static function enables easy testing
// registerFilePaths();
_context.createContextFromGLContext();
// Detect and log OpenCL and OpenGL versions and available devices
ghoul::systemcapabilities::SystemCapabilities::initialize();
@@ -377,10 +370,6 @@ ConfigurationManager& OpenSpaceEngine::configurationManager() {
return _configurationManager;
}
ghoul::opencl::CLContext& OpenSpaceEngine::clContext() {
return _context;
}
InteractionHandler& OpenSpaceEngine::interactionHandler() {
return _interactionHandler;
}
@@ -486,34 +475,12 @@ void OpenSpaceEngine::mouseScrollWheelCallback(int pos) {
void OpenSpaceEngine::encode()
{
//#ifdef FLARE_ONLY
// _flare->encode();
//#else
// std::vector<char> dataStream(1024);
//
// size_t offset = 0;
// // serialization
// _renderEngine->serialize(dataStream, offset);
//
// _synchronizationBuffer.setVal(dataStream);
// sgct::SharedData::instance()->writeVector(&_synchronizationBuffer);
//#endif
_renderEngine.serialize(_syncBuffer);
_syncBuffer->write();
}
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
_syncBuffer->read();
_renderEngine.deserialize(_syncBuffer);
}
-101
View File
@@ -1,101 +0,0 @@
#include <openspace/flare/Animator.h>
#include <openspace/flare/Utils.h>
#include <openspace/flare/Config.h>
using namespace osp;
Animator * Animator::New(Config *_config) {
Animator *animator = new Animator(_config);
animator->UpdateConfig();
return animator;
}
Animator::Animator(Config *_config)
: config_(_config),
numTimesteps_(0),
currentTimestep_(0),
fpsMode_(true),
paused_(false),
elapsedTime_(0.f),
refreshInterval_(0.f) {
}
void Animator::SetCurrentTimestep(unsigned int _timestep) {
currentTimestep_ = _timestep;
}
bool Animator::UpdateConfig() {
refreshInterval_ = config_->AnimatorRefreshInterval();
return true;
}
void Animator::Update(float _elapsedTime) {
if (paused_) return;
if (fpsMode_) {
IncTimestep();
return;
}
// Add time to the time that might have been left from last update
elapsedTime_ += _elapsedTime;
// Update as many times as needed
while (elapsedTime_ > refreshInterval_) {
elapsedTime_ -= refreshInterval_;
IncTimestep();
}
}
void Animator::SetPaused(bool _paused) {
paused_ = _paused;
}
void Animator::SetFPSMode(bool _fpsMode) {
fpsMode_ = _fpsMode;
}
void Animator::ToggleFPSMode() {
fpsMode_ = !fpsMode_;
if (fpsMode_) {
INFO("Rendering as fast as possible");
} else {
INFO("Rendering uses refresh interval parameter");
}
}
void Animator::TogglePause() {
paused_ = !paused_;
}
void Animator::SetNumTimesteps(unsigned int _numTimesteps) {
numTimesteps_ = _numTimesteps;
}
void Animator::ManualTimestep(int _manualTimestep) {
if (_manualTimestep == 0) {
return;
} else if (_manualTimestep < 0) {
DecTimestep();
} else {
IncTimestep();
}
}
void Animator::IncTimestep() {
currentTimestep_++;
if (currentTimestep_ == numTimesteps_) {
currentTimestep_ = 0;
}
}
void Animator::DecTimestep() {
if (currentTimestep_ == 0) {
currentTimestep_ = numTimesteps_-1;
} else {
currentTimestep_--;
}
INFO(currentTimestep_);
}
-494
View File
@@ -1,494 +0,0 @@
/*
* Author: Victor Sand (victor.sand@gmail.com)
*
*/
#include <ghoul/opengl/ghoul_gl.h>
#include <openspace/flare/BrickManager.h>
#include <openspace/flare/Config.h>
#include <openspace/flare/Utils.h>
#include <cmath>
#include <limits>
//#include <boost/timer/timer.hpp>
using namespace osp;
BrickManager * BrickManager::New(Config *_config) {
return new BrickManager(_config);
}
BrickManager::BrickManager(Config *_config)
: config_(_config), xCoord_(0), yCoord_(0), zCoord_(0), textureAtlas_(NULL), file_(NULL),
hasReadHeader_(false), atlasInitialized_(false) {
// TODO move
glGenBuffers(1, &pboHandle_[EVEN]);
glGenBuffers(2, &pboHandle_[ODD]);
}
BrickManager::~BrickManager() {
//if (in_.is_open()) {
// in_.close();
//}
}
bool BrickManager::ReadHeader() {
INFO("\nReading header for Brick Manager");
if (!config_) {
ERROR("No config set");
return false;
}
std::string inFilename = config_->TSPFilename();
file_ = fopen(inFilename.c_str(), "r");
if (!file_) {
ERROR("Failed to open file: " << inFilename);
return false;
}
// DEBUG(inFilename);
// Read unsigned ints in header
size_t s = sizeof(unsigned int);
fread(reinterpret_cast<void*>(&gridType_), s, 1, file_);
fread(reinterpret_cast<void*>(&numOrigTimesteps_), s, 1, file_);
fread(reinterpret_cast<void*>(&numTimesteps_), s, 1, file_);
fread(reinterpret_cast<void*>(&xBrickDim_), s, 1, file_);
fread(reinterpret_cast<void*>(&yBrickDim_), s, 1, file_);
fread(reinterpret_cast<void*>(&zBrickDim_), s, 1, file_);
fread(reinterpret_cast<void*>(&xNumBricks_), s, 1, file_);
fread(reinterpret_cast<void*>(&yNumBricks_), s, 1, file_);
fread(reinterpret_cast<void*>(&zNumBricks_), s, 1, file_);
//fread(reinterpret_cast<void*>(&s_), s, 1, file_);
dataSize_ = 1399743856;
INFO("Grid type: " << gridType_);
INFO("Original num timesteps: " << numOrigTimesteps_);
INFO("Num timesteps: " << numTimesteps_);
INFO("Brick dims: " << xBrickDim_ << " " << yBrickDim_ <<" "<< zBrickDim_);
INFO("Num bricks: " << xNumBricks_ <<" "<< yNumBricks_ <<" "<< zNumBricks_);
INFO("Data size: " << dataSize_);
INFO("");
// Keep track of position for data in file
#ifdef WIN32
dataPos_ = _ftelli64(file_);
#else
dataPos_ = ftello(file_);
#endif
brickDim_ = xBrickDim_;
numBricks_ = xNumBricks_;
paddedBrickDim_ = brickDim_ + paddingWidth_*2;
atlasDim_ = paddedBrickDim_*numBricks_;
INFO("Padded brick dim: " << paddedBrickDim_);
INFO("Atlas dim: " << atlasDim_);
numBrickVals_ = paddedBrickDim_*paddedBrickDim_*paddedBrickDim_;
// Number of bricks per frame
numBricksFrame_ = numBricks_*numBricks_*numBricks_;
// Calculate number of bricks in tree
unsigned int numOTLevels = (unsigned int)(log((int)numBricks_)/log(2)+1);
unsigned int numOTNodes = (unsigned int)((pow(8, numOTLevels) - 1) / 7);
unsigned int numBSTNodes = (unsigned int)numTimesteps_*2 - 1;
numBricksTree_ = numOTNodes * numBSTNodes;
INFO("Num OT levels: " << numOTLevels);
INFO("Num OT nodes: " << numOTNodes);
INFO("Num BST nodes: " << numBSTNodes);
INFO("Num bricks in tree: " << numBricksTree_);
INFO("Num values per brick: " << numBrickVals_);
brickSize_ = sizeof(float)*numBrickVals_;
volumeSize_ = brickSize_*numBricksFrame_;
numValsTot_ = numBrickVals_*numBricksFrame_;
#ifdef WIN32
_fseeki64(file_, 0, SEEK_END);
long long fileSize = _ftelli64(file_);
long long calcFileSize = static_cast<long long>(numBricksTree_)*
static_cast<long long>(brickSize_)+dataPos_;
#else
fseeko(file_, 0, SEEK_END);
off_t fileSize = ftello(file_);
off_t calcFileSize = static_cast<off_t>(numBricksTree_) *
static_cast<off_t>(brickSize_) + dataPos_;
#endif
if (fileSize != calcFileSize) {
ERROR("Sizes don't match");
INFO("calculated file size: " << calcFileSize);
INFO("file size: " << fileSize);
return false;
}
hasReadHeader_ = true;
// Hold two brick lists
brickLists_.resize(2);
// Make sure the brick list can hold the maximum number of bricks
// Each entry holds tree coordinates
brickLists_[EVEN].resize(numBricksTree_*3, -1);
brickLists_[ODD].resize(numBricksTree_*3, -1);
// Allocate space for keeping tracks of bricks in PBO
bricksInPBO_.resize(2);
bricksInPBO_[EVEN].resize(numBricksTree_, -1);
bricksInPBO_[ODD].resize(numBricksTree_, -1);
// Allocate space for keeping track of the used coordinates in atlas
usedCoords_.resize(2);
usedCoords_[EVEN].resize(numBricksFrame_, false);
usedCoords_[ODD].resize(numBricksFrame_, false);
return true;
}
bool BrickManager::InitAtlas() {
if (atlasInitialized_) {
WARNING("InitAtlas() - already initialized");
}
if (!hasReadHeader_) {
ERROR("InitAtlas() - Has not read header");
return false;
}
// Prepare the 3D texture
std::vector<unsigned int> dims;
dims.push_back(atlasDim_);
dims.push_back(atlasDim_);
dims.push_back(atlasDim_);
textureAtlas_ = new ghoul::opengl::Texture(glm::size3_t(atlasDim_, atlasDim_, atlasDim_), ghoul::opengl::Texture::Format::RGBA, GL_RGBA, GL_FLOAT);
textureAtlas_->uploadTexture();
//textureAtlas_ = Texture3D::New(dims);
//if (!textureAtlas_->Init()) return false;
atlasInitialized_ = true;
return true;
}
void BrickManager::IncCoord() {
// Update atlas coordinate
xCoord_++;
if (xCoord_ == xNumBricks_) {
xCoord_ = 0;
yCoord_++;
if (yCoord_ == yNumBricks_) {
yCoord_ = 0;
zCoord_++;
if (zCoord_ == zNumBricks_) {
zCoord_ = 0;
}
}
}
}
unsigned int BrickManager::LinearCoord(int _x, int _y, int _z) {
return _x + _y*xNumBricks_ + _z*xNumBricks_*yNumBricks_;
}
void BrickManager::CoordsFromLin(int _idx, int &_x, int &_y, int &_z) {
_x = _idx % xNumBricks_;
_idx /= xNumBricks_;
_y = _idx % yNumBricks_;
_idx /= yNumBricks_;
_z = _idx;
}
bool BrickManager::BuildBrickList(BUFFER_INDEX _bufIdx,
std::vector<int> &_brickRequest) {
// Keep track of number bricks used and number of bricks cached
// (for benchmarking)
int numBricks = 0;
int numCached = 0;
// For every non-zero entry in the request list, assign a texture atlas
// coordinate. For zero entries, signal "no brick" using -1.
for (unsigned int i=0; i<_brickRequest.size(); ++i) {
if (_brickRequest[i] > 0) {
numBricks++;
//INFO("Checking brick " << i);
// If the brick is already in the atlas, keep the coordinate
if (bricksInPBO_[_bufIdx][i] != -1) {
numCached++;
// Get the corresponding coordinates from index
int x, y, z;
CoordsFromLin(bricksInPBO_[_bufIdx][i], x, y, z);
brickLists_[_bufIdx][3*i + 0] = x;
brickLists_[_bufIdx][3*i + 1] = y;
brickLists_[_bufIdx][3*i + 2] = z;
// Mark coordinate as used
usedCoords_[_bufIdx][bricksInPBO_[_bufIdx][i]] = true;
} else {
// If coord is already usedi by another brick,
// skip it and try the next one
while (usedCoords_[_bufIdx][LinearCoord(xCoord_, yCoord_, zCoord_)]) {
IncCoord();
}
brickLists_[_bufIdx][3*i + 0] = xCoord_;
brickLists_[_bufIdx][3*i + 1] = yCoord_;
brickLists_[_bufIdx][3*i + 2] = zCoord_;
usedCoords_[_bufIdx][LinearCoord(xCoord_, yCoord_, zCoord_)] = true;
IncCoord();
}
} else {
// -1 is for "not used"
brickLists_[_bufIdx][3*i + 0] = -1;
brickLists_[_bufIdx][3*i + 1] = -1;
brickLists_[_bufIdx][3*i + 2] = -1;
}
// Reset brick list during iteration
_brickRequest[i] = 0;
}
// Brick list is build, reset coordinate list
for (auto it=usedCoords_[_bufIdx].begin();
it!=usedCoords_[_bufIdx].end(); ++it) {
*it = false;
}
//INFO("bricks NOT used: " << (float)(numBricksFrame_-numBricks) / (float)(numBricksFrame_));
//INFO("bricks cached: " << (float)numCached / (float)(numBricksFrame_));
return true;
}
bool BrickManager::FillVolume(float *_in, float *_out,
unsigned int _x,
unsigned int _y,
unsigned int _z) {
//timer_.start();
unsigned int xMin = _x*paddedBrickDim_;
unsigned int yMin = _y*paddedBrickDim_;
unsigned int zMin = _z*paddedBrickDim_;
unsigned int xMax = xMin+paddedBrickDim_;
unsigned int yMax = yMin+paddedBrickDim_;
unsigned int zMax = zMin+paddedBrickDim_;
// Loop over the brick using three loops
unsigned int from = 0;
for (unsigned int zValCoord=zMin; zValCoord<zMax; ++zValCoord) {
for (unsigned int yValCoord=yMin; yValCoord<yMax; ++yValCoord) {
for (unsigned int xValCoord=xMin; xValCoord<xMax; ++xValCoord) {
unsigned int idx =
xValCoord +
yValCoord*atlasDim_ +
zValCoord*atlasDim_*atlasDim_;
_out[idx] = _in[from];
from++;
}
}
}
//timer_.stop();
//double time = timer_.elapsed().wall / 1.0e9;
//INFO("FillVolume: " << time << " s");
return true;
}
// TODO find buffer size
bool BrickManager::DiskToPBO(BUFFER_INDEX _pboIndex) {
// Map PBO
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pboHandle_[_pboIndex]);
glBufferData(GL_PIXEL_UNPACK_BUFFER, volumeSize_, 0, GL_STREAM_DRAW);
float *mappedBuffer = reinterpret_cast<float*>(
glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY));
if (!mappedBuffer) {
ERROR("Failed to map PBO");
return false;
}
// Loop over brick request list
unsigned int brickIndex = 0;
while (brickIndex < brickLists_[_pboIndex].size()/3) {
// Find first active brick index in list
while (brickIndex<brickLists_[_pboIndex].size()/3 &&
brickLists_[_pboIndex][3*brickIndex]== -1) {
// If not used, remove from PBO cache list
bricksInPBO_[_pboIndex][brickIndex] = -1;
brickIndex++;
}
// If we are at the end of the list, exit
if (brickIndex == brickLists_[_pboIndex].size()/3) {
break;
}
// Find a sequence of consecutive bricks in list
unsigned int sequence = 0;
// Count number of bricks already in PBO
unsigned int inPBO = 0;
unsigned int brickIndexProbe = brickIndex;
while (brickIndexProbe < brickLists_[_pboIndex].size()/3 &&
brickLists_[_pboIndex][3*brickIndexProbe] != -1) {
sequence++;
if (bricksInPBO_[_pboIndex][brickIndexProbe++] != -1) {
inPBO++;
}
brickIndexProbe++;
}
//INFO("Reading " << sequence << " bricks");
// Read the sequence into a buffer
float *seqBuffer = new float[sequence*numBrickVals_];
size_t bufSize = sequence*numBrickVals_*sizeof(float);
/*
std::ios::pos_type offset = dataPos_ +
static_cast<std::ios::pos_type>(brickIndex) *
static_cast<std::ios::pos_type>(brickSize_);
*/
off_t offset = dataPos_ +
static_cast<off_t>(brickIndex) *
static_cast<off_t>(brickSize_);
// Skip reading if all bricks in sequence is already in PBO
if (inPBO != sequence) {
//timer_.start();
/*
std::streamoff off = static_cast<std::streamoff>(offset);
in_.seekg(off);
if (in_.tellg() == -1) {
ERROR("Failed to get input stream position");
INFO("offset: " << offset);
INFO("streamoff max: " << std::numeric_limits<std::streamoff>::max());
INFO("size_t max: " << std::numeric_limits<size_t>::max());
return false;
}
INFO("in.tellg(): " << in_.tellg());
in_.read(reinterpret_cast<char*>(seqBuffer), brickSize_*sequence);
*/
#ifdef WIN32
_fseeki64(file_, offset, SEEK_SET);
#else
fseeko(file_, offset, SEEK_SET);
#endif
fread(reinterpret_cast<void*>(seqBuffer), bufSize, 1, file_);
if (ferror(file_) != 0) {
ERROR("File reading error");
perror(" ");
return false;
}
//timer_.stop();
//double time = timer_.elapsed().wall / 1.0e9;
//double mb = (brickSize_*sequence) / 1048576.0;
//INFO("Disk read "<<mb<<" MB in "<<time<<" s, "<< mb/time<<" MB/s");
// For each brick in the buffer, put it the correct buffer spot
for (unsigned int i=0; i<sequence; ++i) {
// Only upload if needed
// Pointless if implementation only skips reading when ALL bricks in
// sequence are in PBO, but could be useful if other solutions that
// considers part of the buffer are implemented
if (bricksInPBO_[_pboIndex][brickIndex+i] == -1) {
unsigned int x=static_cast<unsigned int>(
brickLists_[_pboIndex][3*(brickIndex+i)+0]);
unsigned int y=static_cast<unsigned int>(
brickLists_[_pboIndex][3*(brickIndex+i)+1]);
unsigned int z=static_cast<unsigned int>(
brickLists_[_pboIndex][3*(brickIndex+i)+2]);
// Put each brick in the correct buffer place.
// This needs to be done because the values are in brick order, and
// the volume needs to be filled with one big float array.
FillVolume(&seqBuffer[numBrickVals_*i], mappedBuffer, x, y, z);
// Update the atlas list since the brick will be uploaded
//INFO(brickIndex+i);
bricksInPBO_[_pboIndex][brickIndex+i] = LinearCoord(x, y, z);
}
}
delete[] seqBuffer;
} // if in pbo
// Update the brick index
brickIndex += sequence;
}
glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
return true;
}
bool BrickManager::PBOToAtlas(BUFFER_INDEX _pboIndex) {
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pboHandle_[_pboIndex]);
glm::size3_t dim = textureAtlas_->dimensions();
glGetError();
glBindTexture(GL_TEXTURE_3D, *textureAtlas_);
glTexSubImage3D(GL_TEXTURE_3D,
0,
0,
0,
0,
dim[0],
dim[1],
dim[2],
GL_RED,
GL_FLOAT,
NULL);
glBindTexture(GL_TEXTURE_3D, 0);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
return (CheckGLError("Texture3D::UpdateSubRegion") == GL_NO_ERROR);
/*
if (!textureAtlas_->UpdateSubRegion(0, 0, 0,
textureAtlas_->Dim(0),
textureAtlas_->Dim(1),
textureAtlas_->Dim(2),
0)) return false;
*/
//return true;
}
-493
View File
@@ -1,493 +0,0 @@
/*
* Author: Victor Sand (victor.sand@gmail.com)
*
*/
//#include <ghoul/opencl/ghoul_cl.hpp>
#include <openspace/engine/openspaceengine.h>
#include <openspace/flare/CLManager.h>
#include <openspace/flare/CLProgram.h>
#include <openspace/flare/TransferFunction.h>
#include <openspace/flare/TSP.h>
#include <openspace/flare/Utils.h>
#include <sstream>
#include <ghoul/logging/logmanager.h>
#include <ghoul/filesystem/filesystem.h>
namespace {
std::string _loggerCat = "CLManager";
}
using namespace osp;
CLManager::CLManager() {
}
CLManager * CLManager::New() {
return new CLManager();
}
CLManager::~CLManager() {
for (auto it=clPrograms_.begin(); it!=clPrograms_.end(); ++it) {
delete it->second;
}
for (unsigned int i=0; i<NUM_QUEUE_INDICES; ++i) {
clReleaseCommandQueue(commandQueues_[i]);
}
//clReleaseContext(context_);
}
bool CLManager::InitPlatform() {
error_ = clGetPlatformIDs(MAX_PLATFORMS, platforms_, &numPlatforms_);
if (error_ == CL_SUCCESS) {
INFO("Number of CL platforms: " << numPlatforms_);
} else {
CheckSuccess(error_, "InitPlatform()");
return false;
}
// TODO support more platforms?
if (numPlatforms_ > 1) {
WARNING("More than one platform found, this is unsupported");
}
error_ = clGetPlatformInfo(platforms_[0], CL_PLATFORM_VERSION,
sizeof(platformVersion_), platformVersion_, NULL);
if (CheckSuccess(error_, "InitPlatform() printing platform version")) {
INFO("Platform version: " << platformVersion_);
} else {
return false;
}
return true;
}
bool CLManager::InitDevices() {
if (numPlatforms_ < 1) {
ERROR("Number of platforms is < 1");
return false;
}
// Find devices
error_ = clGetDeviceIDs(platforms_[0], CL_DEVICE_TYPE_ALL,
sizeof(devices_), devices_, &numDevices_);
if (CheckSuccess(error_, "InitDevices() getting IDs")) {
INFO("Number of CL devices: " << numDevices_);
} else {
return false;
}
// Loop over found devices and print info
for (unsigned int i=0; i<numDevices_; i++) {
error_ = clGetDeviceInfo(devices_[i], CL_DEVICE_NAME,
sizeof(deviceName_), deviceName_, NULL);
if (CheckSuccess(error_, "InitDevices() printing info")) {
INFO("Device " << i << " name: " << deviceName_);
} else {
return false;
}
error_ = clGetDeviceInfo(devices_[i], CL_DRIVER_VERSION,
sizeof(driverVersion_), driverVersion_, NULL);
if (CheckSuccess(error_, "InitDevices() printing driver versio")) {
INFO("Driver version " << driverVersion_);
} else {
return false;
}
}
// Get maximum allocatable size for each device
for (unsigned int i=0; i<numDevices_; i++) {
error_ = clGetDeviceInfo(devices_[i], CL_DEVICE_MAX_MEM_ALLOC_SIZE,
sizeof(maxMemAllocSize_[i]),
&(maxMemAllocSize_[i]), NULL);
if (!CheckSuccess(error_, "InitDevices() finding maxMemAllocSize")) {
return false;
}
}
return true;
}
bool CLManager::CreateContext() {
if (numPlatforms_ < 1) {
ERROR("Number of platforms < 1, can't create context");
return false;
}
if (numDevices_ < 1) {
ERROR("Number of devices < 1, can't create context");
return false;
}
_context = OsEng.clContext();
/*
bool success = _context.createContextFromGLContext();
if(!success)
LDEBUG("Could not create GL context");
*/
devices_[0] = _context.device();
return _context.isValidContext();
}
bool CLManager::CreateCommandQueue() {
for (unsigned int i=0; i<NUM_QUEUE_INDICES; ++i) {
commandQueues_[i] = _context.createCommandQueue();
if (!CheckSuccess(error_, "CreateCommandQueue()")) {
return false;
}
}
return true;
}
bool CLManager::CreateProgram(std::string _programName,
std::string _fileName) {
// Make sure program doesn't already exist. If it does, delete it.
if (clPrograms_.find(_programName) != clPrograms_.end()) {
delete clPrograms_[_programName];
clPrograms_.erase(_programName);
}
// Create new program and save pointer in map
CLProgram *program = CLProgram::New(_programName, this);
clPrograms_[_programName] = program;
// Create program
return program->CreateProgram(_fileName);
}
bool CLManager::BuildProgram(std::string _programName) {
if (clPrograms_.find(_programName) == clPrograms_.end()) {
ERROR("Program " << _programName << " not found");
return false;
}
return clPrograms_[_programName]->BuildProgram();
}
bool CLManager::CreateKernel(std::string _programName) {
if (clPrograms_.find(_programName) == clPrograms_.end()) {
ERROR("Program " << _programName << " not found");
return false;
}
return clPrograms_[_programName]->CreateKernel();
}
bool CLManager::AddTexture(std::string _programName, unsigned int _argNr,
ghoul::opengl::Texture *_texture, TextureType _textureType,
Permissions _permissions) {
cl_mem_flags flag = ConvertPermissions(_permissions);
GLuint GLTextureType;
switch (_textureType) {
case TEXTURE_1D:
ERROR("Texture 1D unimplemented");
return false;
break;
case TEXTURE_2D:
GLTextureType = GL_TEXTURE_2D;
break;
case TEXTURE_3D:
GLTextureType = GL_TEXTURE_3D;
break;
default:
ERROR("Unknown texture type");
return false;
}
if (clPrograms_.find(_programName) == clPrograms_.end()) {
ERROR("Program " << _programName << " not found");
return false;
}
return clPrograms_[_programName]->AddTexture(_argNr, _texture,
GLTextureType, flag);
}
bool CLManager::AddTexture(std::string _programName, unsigned int _argNr,
ghoul::opengl::Texture *_texture, TextureType _textureType,
Permissions _permissions, cl_mem& _clTextureMem) {
cl_mem_flags flag = ConvertPermissions(_permissions);
GLuint GLTextureType;
switch (_textureType) {
case TEXTURE_1D:
ERROR("Texture 1D unimplemented");
return false;
break;
case TEXTURE_2D:
GLTextureType = GL_TEXTURE_2D;
break;
case TEXTURE_3D:
GLTextureType = GL_TEXTURE_3D;
break;
default:
ERROR("Unknown texture type");
return false;
}
if (clPrograms_.find(_programName) == clPrograms_.end()) {
ERROR("Program " << _programName << " not found");
return false;
}
return clPrograms_[_programName]->AddTexture(_argNr, _texture,
GLTextureType, flag, _clTextureMem);
}
bool osp::CLManager::AddTexture(std::string _programName,
unsigned int _argNr,
cl_mem _texture,
Permissions _permissions)
{
cl_mem_flags flag = ConvertPermissions(_permissions);
if (clPrograms_.find(_programName) == clPrograms_.end()) {
ERROR("Program " << _programName << " not found");
return false;
}
return clPrograms_[_programName]->AddTexture(_argNr, _texture, flag);
}
bool CLManager::AddBuffer(std::string _programName, unsigned int _argNr,
void *_hostPtr, unsigned int _sizeInBytes,
AllocMode _allocMode, Permissions _permissions) {
if (clPrograms_.find(_programName) == clPrograms_.end()) {
ERROR("Program " << _programName << " not found");
return false;
}
cl_mem_flags allocMode = ConvertAllocMode(_allocMode);
cl_mem_flags permissions = ConvertPermissions(_permissions);
return clPrograms_[_programName]->
AddBuffer(_argNr, _hostPtr, _sizeInBytes, allocMode, permissions);
}
bool CLManager::ReadBuffer(std::string _programName, unsigned int _argNr,
void *_hostPtr, unsigned int _sizeInBytes,
bool _blocking) {
if (clPrograms_.find(_programName) == clPrograms_.end()) {
ERROR("Program " << _programName << " not found");
return false;
}
cl_bool blocking = _blocking ? CL_TRUE : CL_FALSE;
return clPrograms_[_programName]->
ReadBuffer(_argNr, _hostPtr, _sizeInBytes, blocking);
}
bool CLManager::ReleaseBuffer(std::string _programName, unsigned int _argNr) {
if (clPrograms_.find(_programName) == clPrograms_.end()) {
ERROR("Program " << _programName << " not found");
return false;
}
return clPrograms_[_programName]->ReleaseBuffer(_argNr);
}
bool CLManager::PrepareProgram(std::string _programName) {
if (clPrograms_.find(_programName) == clPrograms_.end()) {
ERROR("Program " << _programName << " not found");
return false;
}
if (!clPrograms_[_programName]->PrepareProgram()) {
ERROR("Error when preparing program " << _programName);
return false;
}
return true;
}
bool CLManager::SetInt(std::string _programName, unsigned int _argNr,
int _val) {
if (clPrograms_.find(_programName) == clPrograms_.end()) {
ERROR("Program " << _programName << " not found");
return false;
}
if (!clPrograms_[_programName]->SetInt(_argNr, _val)) {
ERROR(_programName << " SetInt()");
return false;
}
return true;
}
bool CLManager::LaunchProgram(std::string _programName,
unsigned int _gx, unsigned int _gy,
unsigned int _lx, unsigned int _ly) {
if (clPrograms_.find(_programName) == clPrograms_.end()) {
ERROR("Program " << _programName << " not found");
return false;
}
if (!clPrograms_[_programName]->LaunchProgram(_gx, _gy, _lx, _ly)) {
ERROR("Error when launching program " << _programName);
return false;
}
return true;
}
bool CLManager::FinishProgram(std::string _programName) {
if (clPrograms_.find(_programName) == clPrograms_.end()) {
ERROR("Program " << _programName << " not found");
return false;
}
if (!clPrograms_[_programName]->FinishProgram()) {
ERROR("Error when finishing program " << _programName);
return false;
}
return true;
}
bool CLManager::FinishQueue(QueueIndex _queueIndex) {
clFinish(commandQueues_[_queueIndex]);
return true;
}
bool CLManager::CheckSuccess(cl_int _error, std::string _location) const {
if (_error == CL_SUCCESS) {
return true;
} else {
ERROR(_location);
ERROR(ErrorString(_error));
return false;
}
}
cl_mem_flags CLManager::ConvertPermissions(Permissions _p) {
switch (_p) {
case READ_WRITE:
return CL_MEM_READ_WRITE;
case READ_ONLY:
return CL_MEM_READ_ONLY;
case WRITE_ONLY:
return CL_MEM_WRITE_ONLY;
default:
ERROR("Unknown permission type, using READ_WRITE");
return CL_MEM_READ_WRITE;
}
}
cl_mem_flags CLManager::ConvertAllocMode(AllocMode _am) {
switch (_am) {
case USE_HOST_PTR:
return CL_MEM_USE_HOST_PTR;
case ALLOC_HOST_PTR:
return CL_MEM_ALLOC_HOST_PTR;
case COPY_HOST_PTR:
return CL_MEM_COPY_HOST_PTR;
default:
ERROR("Unknown alloc mode, using COPY_HOST_PTR");
return CL_MEM_COPY_HOST_PTR;
}
}
std::string CLManager::ErrorString(cl_int _error) const {
switch (_error) {
case CL_SUCCESS:
return "CL_SUCCESS";
case CL_DEVICE_NOT_FOUND:
return "CL_DEVICE_NOT_FOUND";
case CL_DEVICE_NOT_AVAILABLE:
return "CL_DEVICE_NOT_AVAILABLE";
case CL_COMPILER_NOT_AVAILABLE:
return "CL_COMPILER_NOT_AVAILABLE";
case CL_MEM_OBJECT_ALLOCATION_FAILURE:
return "CL_MEM_OBJECT_ALLOCATION_FAILURE";
case CL_OUT_OF_RESOURCES:
return "CL_OUT_OF_RESOURCES";
case CL_OUT_OF_HOST_MEMORY:
return "CL_OUT_OF_HOST_MEMORY";
case CL_PROFILING_INFO_NOT_AVAILABLE:
return "CL_PROFILING_INFO_NOT_AVAILABLE";
case CL_MEM_COPY_OVERLAP:
return "CL_MEM_COPY_OVERLAP";
case CL_IMAGE_FORMAT_MISMATCH:
return "CL_IMAGE_FORMAT_MISMATCH";
case CL_IMAGE_FORMAT_NOT_SUPPORTED:
return "CL_IMAGE_FORMAT_NOT_SUPPORTED";
case CL_BUILD_PROGRAM_FAILURE:
return "CL_BUILD_PROGRAM_FAILURE";
case CL_MAP_FAILURE:
return "CL_MAP_FAILURE";
case CL_INVALID_VALUE:
return "CL_INVALID_VALUE";
case CL_INVALID_DEVICE_TYPE:
return "CL_INVALID_DEVICE_TYPE";
case CL_INVALID_PLATFORM:
return "CL_INVALID_PLATFORM";
case CL_INVALID_DEVICE:
return "CL_INVALID_DEVICE";
case CL_INVALID_CONTEXT:
return "CL_INVALID_CONTEXT";
case CL_INVALID_QUEUE_PROPERTIES:
return "CL_INVALID_QUEUE_PROPERTIES";
case CL_INVALID_COMMAND_QUEUE:
return "CL_INVALID_COMMAND_QUEUE";
case CL_INVALID_HOST_PTR:
return "CL_INVALID_HOST_PTR";
case CL_INVALID_MEM_OBJECT:
return "CL_INVALID_MEM_OBJECT";
case CL_INVALID_IMAGE_FORMAT_DESCRIPTOR:
return "CL_INVALID_IMAGE_FORMAT_DESCRIPTOR";
case CL_INVALID_IMAGE_SIZE:
return "CL_INVALID_IMAGE_SIZE";
case CL_INVALID_SAMPLER:
return "CL_INVALID_SAMPLER";
case CL_INVALID_BINARY:
return "CL_INVALID_BINARY";
case CL_INVALID_BUILD_OPTIONS:
return "CL_INVALID_BUILD_OPTIONS";
case CL_INVALID_PROGRAM:
return "CL_INVALID_PROGRAM";
case CL_INVALID_PROGRAM_EXECUTABLE:
return "CL_INVALID_PROGRAM_EXECUTABLE";
case CL_INVALID_KERNEL_NAME:
return "CL_INVALID_KERNEL_NAME";
case CL_INVALID_KERNEL_DEFINITION:
return "CL_INVALID_KERNEL_DEFINITION";
case CL_INVALID_KERNEL:
return "CL_INVALID_KERNEL";
case CL_INVALID_ARG_INDEX:
return "CL_INVALID_ARG_INDEX";
case CL_INVALID_ARG_VALUE:
return "CL_INVALID_ARG_VALUE";
case CL_INVALID_ARG_SIZE:
return "CL_INVALID_ARG_SIZE";
case CL_INVALID_KERNEL_ARGS:
return "CL_INVALID_KERNEL_ARGS";
case CL_INVALID_WORK_DIMENSION:
return "CL_INVALID_WORK_DIMENSION";
case CL_INVALID_WORK_GROUP_SIZE:
return "CL_INVALID_WORK_GROUP_SIZE";
case CL_INVALID_WORK_ITEM_SIZE:
return "CL_INVALID_WORK_ITEM_SIZE";
case CL_INVALID_GLOBAL_OFFSET:
return "CL_INVALID_GLOBAL_OFFSET";
case CL_INVALID_EVENT_WAIT_LIST:
return "CL_INVALID_EVENT_WAIT_LIST";
case CL_INVALID_EVENT:
return "CL_INVALID_EVENT";
case CL_INVALID_OPERATION:
return "CL_INVALID_OPERATION";
case CL_INVALID_GL_OBJECT:
return "CL_INVALID_GL_OBJECT";
case CL_INVALID_BUFFER_SIZE:
return "CL_INVALID_BUFFER_SIZE";
case CL_INVALID_MIP_LEVEL:
return "CL_INVALID_MIP_LEVEL";
case CL_INVALID_GLOBAL_WORK_SIZE:
return "CL_INVALID_GLOBAL_WORK_SIZE";
default:
std::stringstream ss;
std::string code;
ss << "Unknown OpenCL error code - " << _error;
return ss.str();
}
}
-374
View File
@@ -1,374 +0,0 @@
/*
* Author: Victor Sand (victor.sand@gmail.com)
*
*/
//#include <ghoul/opengl/ghoul_gl.h>
#include <openspace/flare/CLProgram.h>
#include <openspace/flare/CLManager.h>
#include <openspace/flare/TransferFunction.h>
#include <openspace/flare/Utils.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/opencl/ghoul_cl.hpp>
namespace {
std::string _loggerCat = "CLProgram";
}
using namespace osp;
CLProgram::CLProgram(const std::string &_programName, CLManager *_clManager)
: programName_(_programName), clManager_(_clManager) {
}
CLProgram * CLProgram::New(const std::string &_programName,
CLManager *_clManager) {
return new CLProgram(_programName, _clManager);
}
CLProgram::~CLProgram() {
clReleaseKernel(kernel_);
clReleaseProgram(program_);
}
bool CLProgram::CreateProgram(std::string _fileName) {
int numChars;
char *source = ReadSource(_fileName, numChars);
program_ = clCreateProgramWithSource(clManager_->_context, 1,
(const char**)&source,
NULL, &error_);
free(source);
return (error_ == CL_SUCCESS);
}
bool CLProgram::BuildProgram() {
std::string options = "-cl-opt-disable";
error_ = clBuildProgram(program_, (cl_uint)0,
NULL, options.c_str(), NULL, NULL);
if (error_ != CL_SUCCESS) {
LDEBUG("Could not build program " << getErrorString(error_));
// Print build log
char * log;
size_t logSize = 0;
clGetProgramBuildInfo(program_, clManager_->devices_[0],
CL_PROGRAM_BUILD_LOG, 0, NULL, &logSize);
if (logSize > 0) {
INFO("Build log:");
log = new char[logSize+1];
clGetProgramBuildInfo(program_, clManager_->devices_[0],
CL_PROGRAM_BUILD_LOG, logSize, log, NULL);
log[logSize] = '\0';
INFO(log);
delete[] log;
}
return false;
}
return true;
}
bool CLProgram::CreateKernel() {
kernel_ = clCreateKernel(program_, programName_.c_str(), &error_);
return (error_ == CL_SUCCESS);
}
bool CLProgram::AddTexture(unsigned int _argNr, ghoul::opengl::Texture *_texture,
GLuint _textureType,
cl_mem_flags _permissions) {
// Remove anything already associated with argument index
if (OGLTextures_.find((cl_uint)_argNr) != OGLTextures_.end()) {
OGLTextures_.erase((cl_uint)_argNr);
}
cl_mem texture;
switch (_textureType) {
case GL_TEXTURE_1D:
LERROR("Texture 1D unimplemented");
return false;
break;
case GL_TEXTURE_2D:
#ifdef CL_VERSION_1_2
texture = clCreateFromGLTexture(clManager_->_context, _permissions,
GL_TEXTURE_2D, 0,
*_texture, &error_);
#else
texture = clCreateFromGLTexture2D(clManager_->_context, _permissions,
GL_TEXTURE_2D, 0,
*_texture, &error_);
#endif
break;
case GL_TEXTURE_3D:
#ifdef CL_VERSION_1_2
texture = clCreateFromGLTexture(clManager_->_context, _permissions,
GL_TEXTURE_3D, 0,
*_texture, &error_);
#else
texture = clCreateFromGLTexture3D(clManager_->_context, _permissions,
GL_TEXTURE_3D, 0,
*_texture, &error_);
#endif
break;
default:
LERROR("Unknown GL texture type");
return false;
}
if (!clManager_->CheckSuccess(error_, "AddTexture")) return false;
OGLTextures_.insert(std::make_pair((cl_uint)_argNr, texture));
return true;
}
bool CLProgram::AddTexture(unsigned int _argNr, ghoul::opengl::Texture *_texture,
GLuint _textureType,
cl_mem_flags _permissions,
cl_mem& _clTextureMem) {
// Remove anything already associated with argument index
if (OGLTextures_.find((cl_uint)_argNr) != OGLTextures_.end()) {
OGLTextures_.erase((cl_uint)_argNr);
}
switch (_textureType) {
case GL_TEXTURE_1D:
LERROR("Texture 1D unimplemented");
return false;
break;
case GL_TEXTURE_2D:
#ifdef CL_VERSION_1_2
_clTextureMem = clCreateFromGLTexture(clManager_->_context, _permissions,
GL_TEXTURE_2D, 0,
*_texture, &error_);
#else
_clTextureMem = clCreateFromGLTexture2D(clManager_->_context, _permissions,
GL_TEXTURE_2D, 0,
*_texture, &error_);
#endif
break;
case GL_TEXTURE_3D:
#ifdef CL_VERSION_1_2
_clTextureMem = clCreateFromGLTexture(clManager_->_context, _permissions,
GL_TEXTURE_3D, 0,
*_texture, &error_);
#else
_clTextureMem = clCreateFromGLTexture2D(clManager_->_context, _permissions,
GL_TEXTURE_3D, 0,
*_texture, &error_);
#endif
break;
default:
LERROR("Unknown GL texture type");
return false;
}
if (!clManager_->CheckSuccess(error_, "AddTexture")) return false;
OGLTextures_.insert(std::make_pair((cl_uint)_argNr, _clTextureMem));
return true;
}
bool osp::CLProgram::AddTexture(unsigned int _argNr,
cl_mem _texture,
cl_mem_flags _permissions)
{
// Remove anything already associated with argument index
if (OGLTextures_.find((cl_uint)_argNr) != OGLTextures_.end()) {
OGLTextures_.erase((cl_uint)_argNr);
}
OGLTextures_.insert(std::make_pair((cl_uint)_argNr, _texture));
return true;
}
bool CLProgram::AddBuffer(unsigned int _argNr,
void *_hostPtr,
unsigned int _sizeInBytes,
cl_mem_flags _allocMode,
cl_mem_flags _permissions) {
if (!_hostPtr) {
LERROR("AddBuffer(): Host pointer is NULL");
return false;
}
if (memArgs_.find((cl_uint)_argNr) != memArgs_.end()) {
memArgs_.erase((cl_uint)_argNr);
}
MemArg ma;
ma.size_ = sizeof(cl_mem);
ma.mem_ = clCreateBuffer(clManager_->_context,
_allocMode | _permissions,
(size_t)_sizeInBytes,
_hostPtr,
&error_);
if (!clManager_->CheckSuccess(error_, "AddBuffer")) {
return false;
}
memArgs_.insert(std::make_pair((cl_uint)_argNr, ma));
return true;
}
bool CLProgram::ReadBuffer(unsigned int _argNr,
void *_hostPtr,
unsigned int _sizeInBytes,
cl_bool _blocking) {
if (memArgs_.find((cl_uint)_argNr) == memArgs_.end()) {
LERROR("ReadBuffer(): Could not find mem arg " << _argNr);
return false;
}
error_ = clEnqueueReadBuffer(clManager_->commandQueues_[CLManager::EXECUTE],
memArgs_[(cl_uint)_argNr].mem_,
_blocking,
0,
_sizeInBytes,
_hostPtr,
0,
NULL,
NULL);
return clManager_->CheckSuccess(error_, "ReadBuffer");
}
bool CLProgram::ReleaseBuffer(unsigned int _argNr) {
if (memArgs_.find((cl_uint)_argNr) == memArgs_.end()) {
LERROR("ReleaseBuffer(): Could not find mem arg " << _argNr);
return false;
}
//LDEBUG("Releasing memory");
error_ = clReleaseMemObject(memArgs_[(cl_uint)_argNr].mem_);
return clManager_->CheckSuccess(error_, "ReleaseBuffer");
}
bool CLProgram::PrepareProgram() {
//ghoulFinishGL();
//#ifdef __APPLE__
//glFlushRenderAPPLE();
// glFinish();
//glFlush();
//#else
glFinish();
// Let OpenCL take control of the shared GL textures
for (auto it = OGLTextures_.begin(); it != OGLTextures_.end(); ++it) {
ghoul::opencl::CLCommandQueue q = clManager_->commandQueues_[CLManager::EXECUTE];
cl_command_queue clq = q;
error_ = clEnqueueAcquireGLObjects(clq, 1, &(it->second), 0, NULL, NULL);
if (!clManager_->CheckSuccess(error_, "PrepareProgram")) {
LDEBUG("error: " << getErrorString(error_));
LERROR("Failed to enqueue GL object aqcuisition");
LERROR("Failing object: " << it->first);
return false;
}
}
//#endif
// Set up kernel arguments of non-shared items
for (auto it=memArgs_.begin(); it!=memArgs_.end(); ++it) {
error_ = clSetKernelArg(kernel_,
it->first,
(it->second).size_,
&((it->second).mem_));
if (!clManager_->CheckSuccess(error_, "PrepareProgram")) {
LERROR("Failed to set kernel argument " << it->first);
return false;
}
}
// Set up kernel arguments for textures
for (auto it=OGLTextures_.begin(); it!=OGLTextures_.end(); ++it) {
error_ = clSetKernelArg(kernel_,
it->first,
sizeof(cl_mem),
&(it->second));
if (!clManager_->CheckSuccess(error_, "PrepareProgram")) {
LERROR("Failed to set texture kernel arg " << it->first);
return false;
}
}
return true;
}
bool CLProgram::SetInt(unsigned int _argNr, int _val) {
error_ = clSetKernelArg(kernel_, _argNr, sizeof(int), &_val);
if (!clManager_->CheckSuccess(error_, "SetInt")) {
LERROR("Failed to set integer value");
return false;
}
return true;
}
bool CLProgram::LaunchProgram(unsigned int _gx, unsigned int _gy,
unsigned int _lx, unsigned int _ly) {
size_t globalSize[] = { _gx, _gy };
size_t localSize[] = { _lx, _ly };
error_ = clEnqueueNDRangeKernel(
clManager_->commandQueues_[CLManager::EXECUTE], kernel_, 2, NULL,
globalSize, localSize, 0, NULL, NULL);
return clManager_->CheckSuccess(error_, "LaunchProgram()");
}
bool CLProgram::FinishProgram() {
//#ifndef __APPLE__
// Make sure kernel is done
// Release shared OGL objects
for (auto it=OGLTextures_.begin(); it!=OGLTextures_.end(); ++it) {
error_ = clEnqueueReleaseGLObjects(
clManager_->commandQueues_[CLManager::EXECUTE], 1,
&(it->second), 0, NULL, NULL);
if (!clManager_->CheckSuccess(error_, "FinishProgram, release GL objs")) {
LERROR("Failed to release GL object");
LERROR("Failed object: " << it->first);
return false;
}
}
error_ = clFinish(clManager_->commandQueues_[CLManager::EXECUTE]);
if (!clManager_->CheckSuccess(error_, "FinishProgram, clFinish")) {
LERROR("Failed to finish program");
return false;
}
//#else
//error_ = clFinish(clManager_->commandQueues_[CLManager::EXECUTE]);
//if (!clManager_->CheckSuccess(error_, "FinishProgram, clFinish")) {
// ERROR("Failed to finish program");
// return false;
//}
//#endif
return true;
}
char * CLProgram::ReadSource(const std::string &_filename,
int &_numChars) const {
FILE *in;
char *content = NULL;
in = fopen(_filename.c_str(), "r");
int count = 0;
if (in != NULL) {
fseek(in, 0, SEEK_END);
count = ftell(in);
rewind(in);
content = (char *)malloc(sizeof(char)*(count+1));
count = fread(content, sizeof(char), count, in);
content[count] = '\0';
fclose(in);
} else {
LERROR("Could not read source from file " << _filename);
}
_numChars = count;
return content;
}
-216
View File
@@ -1,216 +0,0 @@
/*
* Author: Victor Sand (victor.sand@gmail.com)
*
*/
#include <openspace/flare/Config.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <openspace/flare/Utils.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/logging/logmanager.h>
namespace {
const std::string _loggerCat = "Flare.Config";
}
using namespace osp;
Config::Config() : configFilename_("OopsNotSet") {}
Config::Config(const std::string &_configFilename)
: configFilename_(_configFilename),
winWidth_(512),
winHeight_(512),
clearCache_(false),
localWorkSizeX_(16),
localWorkSizeY_(16),
TSPFilename_("notSet"),
TFFilename_("notSet"),
raycasterKernelFilename_("notSet"),
TSPTraversalKernelFilename_("notSet"),
cubeShaderVertFilename_("notSet"),
cubeShaderFragFilename_("notSet"),
quadShaderVertFilename_("notSet"),
quadShaderFragFilename_("notSet"),
spatialErrorTolerance_(0.f),
temporalErrorTolerance_(0.f),
TSPTraversalStepsize_(0.1f),
raycasterStepsize_(0.1f),
raycasterIntensity_(1.f),
animatorRefreshInterval_(1.f),
mousePitchFactor_(1.f),
mouseRollFactor_(1.f),
zoomFactor_(1.f),
startPitch_(0.f),
startRoll_(0.f),
startYaw_(0.f),
translateX_(0.f),
translateY_(0.f),
translateZ_(0.f),
calculateError_(1),
pitchSpeed_(0.f),
rollSpeed_(0.f),
yawSpeed_(0.f),
takeScreenshot_(false)
{}
Config::~Config() {}
Config * Config::New(const std::string &_configFilename) {
Config *config = new Config(_configFilename);
if (!config->Read()) {
LERROR("Could not read config. Returning NULL.");
delete config;
return NULL;
}
return config;
}
bool Config::Read() {
LINFO("\nReading config from " << configFilename_);
std::ifstream in;
in.open(configFilename_.c_str(), std::ifstream::in);
if (!in.is_open()) {
LERROR("Could not open " << configFilename_);
return false;
}
std::string line;
while (std::getline(in, line)) {
// Ignore empty lines and comments
if (!line.empty() && line.at(0) != '#') {
// Read variable name
std::stringstream ss;
ss.str(line);
std::string variable;
ss >> variable;
// Save value
if (variable == "tsp_filename") {
ss >> TSPFilename_;
TSPFilename_ = absPath(TSPFilename_);
LINFO("TSP file name: " << TSPFilename_);
} else if (variable == "transferfunction_filename") {
ss >> TFFilename_;
TFFilename_ = absPath(TFFilename_);
LINFO("Transfer function file name " << TFFilename_);
} else if (variable == "spatial_error_tolerance") {
ss >> spatialErrorTolerance_;
LINFO("Spatial error tolerance: " << spatialErrorTolerance_);
} else if (variable == "temporal_error_tolerance") {
ss >> temporalErrorTolerance_;
LINFO("Temporal error tolerance: " << temporalErrorTolerance_);
} else if (variable == "tsp_traversal_stepsize") {
ss >> TSPTraversalStepsize_;
LINFO("TSP traversal step size: " << TSPTraversalStepsize_);
} else if (variable == "raycaster_stepsize") {
ss >> raycasterStepsize_;
LINFO("Ray caster step size: " << raycasterStepsize_);
} else if (variable == "raycaster_intensity") {
ss >> raycasterIntensity_;
LINFO("Ray caster intensity: " << raycasterIntensity_);
} else if (variable == "animator_refresh_interval") {
ss >> animatorRefreshInterval_;
LINFO("Animator refresh interval: " << animatorRefreshInterval_);
} else if (variable == "win_width") {
ss >> winWidth_;
LINFO("Win width: " << winWidth_);
} else if (variable == "win_height") {
ss >> winHeight_;
LINFO("Win height: " << winHeight_);
} else if (variable == "raycaster_kernel_filename") {
ss >> raycasterKernelFilename_;
raycasterKernelFilename_ = absPath(raycasterKernelFilename_);
LINFO("Raycaster kernel file name: " << raycasterKernelFilename_);
} else if (variable == "tsp_traversal_kernel_filename" ) {
ss >> TSPTraversalKernelFilename_;
TSPTraversalKernelFilename_ = absPath(TSPTraversalKernelFilename_);
LINFO("TSP traversal kernel file name: " <<TSPTraversalKernelFilename_);
} else if (variable == "cube_shader_vert_filename") {
ss >> cubeShaderVertFilename_;
cubeShaderVertFilename_ = absPath(cubeShaderVertFilename_);
LINFO("Cube vertex shader file name: " << cubeShaderVertFilename_);
} else if (variable == "cube_shader_frag_filename") {
ss >> cubeShaderFragFilename_;
cubeShaderFragFilename_ = absPath(cubeShaderFragFilename_);
LINFO("Cube fragment shader file name: " << cubeShaderFragFilename_);
} else if (variable == "quad_shader_vert_filename") {
ss >> quadShaderVertFilename_;
quadShaderVertFilename_ = absPath(quadShaderVertFilename_);
LINFO("Quad vertex shader file name: " << quadShaderVertFilename_);
} else if (variable == "quad_shader_frag_filename") {
ss >> quadShaderFragFilename_;
quadShaderFragFilename_ = absPath(quadShaderFragFilename_);
LINFO("Cube vertex shader file name: " << quadShaderFragFilename_);
} else if (variable == "mouse_pitch_factor") {
ss >> mousePitchFactor_;
LINFO("Mouse pitch factor " << mousePitchFactor_);
} else if (variable == "mouse_roll_factor") {
ss >> mouseRollFactor_;
LINFO("Mouse roll factor " << mouseRollFactor_);
} else if (variable == "zoom_factor") {
ss >> zoomFactor_;
LINFO("Zoom factor " << zoomFactor_);
} else if (variable == "start_pitch") {
ss >> startPitch_;
LINFO("Start pitch: " << startPitch_);
} else if (variable == "start_roll") {
ss >> startRoll_;
LINFO("Start roll: " << startRoll_);
} else if (variable == "start_yaw") {
ss >> startYaw_;
LINFO("Start yaw: " << startYaw_);
} else if (variable == "translate_x") {
ss >> translateX_;
LINFO("Translate X: " << translateX_);
} else if (variable == "translate_y") {
ss >> translateY_;
LINFO("Translate Y: " << translateY_);
} else if (variable == "translate_z") {
ss >> translateZ_;
LINFO("Translate Z: " << translateZ_);
} else if (variable == "local_worksize_x") {
ss >> localWorkSizeX_;
LINFO("Local worksize X: " << localWorkSizeX_);
} else if (variable == "local_worksize_y") {
ss >> localWorkSizeY_;
LINFO("Local worksize Y: " << localWorkSizeY_);
} else if (variable == "texture_division_factor") {
ss >> textureDivisionFactor_;
LINFO("Texture division factor: " << textureDivisionFactor_);
} else if (variable == "clear_cache") {
ss >> clearCache_;
LINFO("Clearing cache: " << clearCache_);
} else if (variable == "calculate_error") {
ss >> calculateError_;
LINFO("Calculate error: " << calculateError_);
} else if (variable == "pitch_speed") {
ss >> pitchSpeed_;
LINFO("Pitch speed: " << pitchSpeed_);
} else if (variable == "roll_speed") {
ss >> rollSpeed_;
LINFO("Roll speed: " << rollSpeed_);
} else if (variable == "yaw_speed") {
ss >> yawSpeed_;
LINFO("Yaw speed: " << yawSpeed_);
} else if (variable == "take_screenshot") {
ss >> takeScreenshot_;
LINFO("Take screenshot: " << takeScreenshot_);
} else {
LERROR("Variable name " << variable << " unknown");
}
}
}
LINFO("");
return true;
}
-55
View File
@@ -1,55 +0,0 @@
#include <openspace/flare/MappingKey.h>
#include <iostream>
#include <iomanip>
using namespace osp;
MappingKey::MappingKey()
: intensity_(0.f),
r_(0),
g_(0),
b_(0),
a_(0) {}
MappingKey::MappingKey(const MappingKey &_mk)
: intensity_(_mk.intensity_),
r_(_mk.r_),
g_(_mk.g_),
b_(_mk.b_),
a_(_mk.a_) {}
MappingKey::MappingKey(float _intensity, unsigned int _r, unsigned int _g,
unsigned int _b, unsigned int _a)
: intensity_(_intensity),
r_(_r),
g_(_g),
b_(_b),
a_(_a) {}
MappingKey::~MappingKey() {}
void MappingKey::SetValues(float _intensity, unsigned int _r, unsigned int _g,
unsigned int _b, unsigned int _a) {
intensity_ = _intensity;
r_ = _r;
g_ = _g;
b_ = _b;
a_ = _a;
}
std::ostream& operator<<(std::ostream &os,
const MappingKey &_mk) {
os << _mk.Intensity() << " ["
<< _mk.R() << " " << _mk.G() << " " << _mk.B() << " " << _mk.A() << "]";
return os;
}
bool MappingKey::operator<(const MappingKey &_mappingKey) const {
return intensity_ < _mappingKey.intensity_;
}
MappingKey & MappingKey::operator=(const MappingKey &_mk) {
if (this == &_mk) return *this;
SetValues(_mk.intensity_, _mk.r_, _mk.g_, _mk.b_, _mk.a_);
return *this;
}
-846
View File
@@ -1,846 +0,0 @@
/*
* Author: Victor Sand (victor.sand@gmail.com)
*
*/
#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>
#include <openspace/flare/Utils.h>
#include <glm/gtc/matrix_transform.hpp>
#include <openspace/flare/TransferFunction.h>
#include <openspace/flare/Animator.h>
#include <vector>
#include <openspace/flare/CLManager.h>
#include <openspace/flare/KernelConstants.h>
#include <openspace/flare/Config.h>
#include <stdint.h>
//#include <unistd.h> // sync()
using namespace osp;
uint32_t ZOrder(uint16_t xPos, uint16_t yPos, uint16_t zPos) {
uint32_t x = static_cast<uint32_t>(xPos);
uint32_t y = static_cast<uint32_t>(yPos);
uint32_t z = static_cast<uint32_t>(zPos);
x = (x | (x << 16)) & 0x030000FF;
x = (x | (x << 8)) & 0x0300F00F;
x = (x | (x << 4)) & 0x030C30C3;
x = (x | (x << 2)) & 0x09249249;
y = (y | (y << 16)) & 0x030000FF;
y = (y | (y << 8)) & 0x0300F00F;
y = (y | (y << 4)) & 0x030C30C3;
y = (y | (y << 2)) & 0x09249249;
z = (z | (z << 16)) & 0x030000FF;
z = (z | (z << 8)) & 0x0300F00F;
z = (z | (z << 4)) & 0x030C30C3;
z = (z | (z << 2)) & 0x09249249;
const uint32_t result = x | (y << 1) | (z << 2);
return result;
}
//const double BYTES_PER_GB = 1073741824.0;
Raycaster::Raycaster(Config *_config)
: Renderer(),
config_(_config),
cubeFrontFBO_(0),
cubeBackFBO_(0),
renderbufferObject_(0),
cubePosbufferObject_(0),
quadPosbufferObject_(0),
cubePositionAttrib_(0),
quadPositionAttrib_(0),
cubeShaderProgram_(NULL),
quadShaderProgram_(NULL),
cubeFrontTex_(NULL),
cubeBackTex_(NULL),
quadTex_(NULL),
pitch_(0.f),
yaw_(0.f),
roll_(0.f),
translateX_(_config->TranslateX()),
translateY_(_config->TranslateY()),
translateZ_(_config->TranslateZ()),
model_(glm::mat4()),
view_(glm::mat4()),
proj_(glm::mat4()),
cubeInitialized_(false),
quadInitialized_(false),
framebuffersInitialized_(false),
pingPong_(0),
animator_(NULL),
lastTimestep_(1),
pingPongIndex_(true),
brickManager_(NULL),
clManager_(NULL),
cubeFrontCLmem(0),
cubeBackCLmem(0) {
}
Raycaster::~Raycaster() {
// TODO relase GL textures
}
Raycaster * Raycaster::New(Config *_config) {
Raycaster *raycaster = new Raycaster(_config);
return raycaster;
}
bool Raycaster::Render(float _timestep) {
proj_ = sgct::Engine::instance()->getActiveProjectionMatrix();
GLuint activeFBO = ghoul::opengl::FramebufferObject::getActiveObject();
// Clear cache for benchmarking
if (config_->ClearCache()) {
//sync();
std::ofstream ofs("/proc/sys/vm/drop_caches");
ofs << "3" << std::endl;
ofs.close();
}
//timer_.start();
if (animator_ == NULL) {
WARNING("Animator not set");
}
// Reset any errors
glGetError();
// TODO move init checks and only run them once
if (!cubeInitialized_) {
ERROR("Rendering failed, cube not initialized");
return false;
}
if (!quadInitialized_) {
ERROR("Rendering failed, quad not initialized");
return false;
}
if (!framebuffersInitialized_) {
ERROR("Rendering failed, framebuffers not initialized");
return false;
}
if (!cubeFrontTex_ || !cubeBackTex_ || !quadTex_) {
ERROR("Rendering failed, one or more texures are not set");
return false;
}
if (!cubeShaderProgram_ || !quadShaderProgram_) {
ERROR("Rendering failed, one or more shaders are not set");
return false;
}
if (!UpdateMatrices()) return false;
if (!BindTransformationMatrices(cubeShaderProgram_)) return false;
// For some reason, setting 0 all across leaves the background white.
//glClearColor(0.f, 0.f, 0.f, 0.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Render cube
cubeShaderProgram_->activate();
//glUseProgram(cubeShaderProgram_->Handle());
cubePositionAttrib_ = cubeShaderProgram_->attributeLocation("position");
if (cubePositionAttrib_ == -1) {
ERROR("Cube position attribute lookup failed");
return false;
}
glFrontFace(GL_CW);
glEnable(GL_CULL_FACE);
// Front
glBindFramebuffer(GL_FRAMEBUFFER, cubeFrontFBO_);
glCullFace(GL_BACK);
glBindVertexArray(cubeVAO_);
glBindBuffer(GL_ARRAY_BUFFER, cubePosbufferObject_);
glEnableVertexAttribArray(cubePositionAttrib_);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDrawArrays(GL_TRIANGLES, 0, 144);
glDisableVertexAttribArray(cubePositionAttrib_);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindVertexArray(0);
if (CheckGLError("Cube front rendering") != GL_NO_ERROR) {
return false;
}
// Back
glBindFramebuffer(GL_FRAMEBUFFER, cubeBackFBO_);
glCullFace(GL_FRONT);
glBindVertexArray(cubeVAO_);
glBindBuffer(GL_ARRAY_BUFFER, cubePosbufferObject_);
glEnableVertexAttribArray(cubePositionAttrib_);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDrawArrays(GL_TRIANGLES, 0, 144);
glDisableVertexAttribArray(cubePositionAttrib_);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindVertexArray(0);
if (CheckGLError("Cube back rendering") != GL_NO_ERROR) {
return false;
}
glUseProgram(0);
unsigned int currentTimestep;
unsigned int nextTimestep;
if (animator_ != NULL) {
currentTimestep = animator_->CurrentTimestep();
nextTimestep = animator_->NextTimestep();
} else {
WARNING("Animator not set");
currentTimestep = 0;
nextTimestep = 1;
}
// Choose buffers
BrickManager::BUFFER_INDEX currentBuf, nextBuf;
if (currentTimestep % 2 == 0) {
currentBuf = BrickManager::EVEN;
nextBuf = BrickManager::ODD;
} else {
currentBuf = BrickManager::ODD;
nextBuf = BrickManager::EVEN;
}
// When starting a rendering iteration, the PBO corresponding to the
// current timestep is loaded with the data.
// Launch traversal of the next timestep
if (!LaunchTSPTraversal(nextTimestep)) return false;
// While traversal of next step is working, upload current data to atlas
if (!brickManager_->PBOToAtlas(currentBuf)) return false;
// Make sure the traversal kernel is done
if (!clManager_->FinishProgram("TSPTraversal")) return false;
// Read buffer and release the memory
if (!clManager_->ReadBuffer("TSPTraversal", tspBrickListArg_,
reinterpret_cast<void*>(&brickRequest_[0]),
brickRequest_.size()*sizeof(int),
true)) return false;
if (!clManager_->ReleaseBuffer("TSPTraversal",tspBrickListArg_))return false;
// When traversal of next timestep is done, launch raycasting kernel
if (!clManager_->SetInt("RaycasterTSP", timestepArg_, currentTimestep))
return false;
// Add brick list
if (!clManager_->
AddBuffer("RaycasterTSP", brickListArg_,
reinterpret_cast<void*>(&(brickManager_->BrickList(currentBuf)[0])),
brickManager_->BrickList(currentBuf).size()*sizeof(int),
CLManager::COPY_HOST_PTR,
CLManager::READ_ONLY)) return false;
if (!clManager_->PrepareProgram("RaycasterTSP")) return false;
if (!clManager_->LaunchProgram("RaycasterTSP",
winWidth_,
winHeight_,
config_->LocalWorkSizeX(),
config_->LocalWorkSizeY()))
return false;
// While the raycaster kernel is working, build next brick list and start
// upload to the next PBO
if (!brickManager_->BuildBrickList(nextBuf, brickRequest_)) return false;
if (!brickManager_->DiskToPBO(nextBuf)) return false;
// Finish raycaster and render current frame
if (!clManager_->ReleaseBuffer("RaycasterTSP", brickListArg_)) return false;
if (!clManager_->FinishProgram("RaycasterTSP")) return false;
// Render to framebuffer using quad
glBindFramebuffer(GL_FRAMEBUFFER, activeFBO);
glGetError();
quadShaderProgram_->activate();
glActiveTexture(GL_TEXTURE0);
int location = quadShaderProgram_->uniformLocation("quadTex");
//int location = glGetUniformLocation(_shaderProgram->Handle(),_uniformName.c_str());
if (location == -1) {
ERROR("Uniform " << "quadTex" << " could not be found");
glUseProgram(0);
return false;
}
glUniform1i(location, 0);
glBindTexture(GL_TEXTURE_2D, *quadTex_);
glUseProgram(0);
//if (!quadTex_->Bind(quadShaderProgram_, "quadTex", 0)) return false;
glDisable(GL_CULL_FACE);
quadShaderProgram_->activate();
//glUseProgram(quadShaderProgram_->Handle());
//quadPositionAttrib_ = quadShaderProgram_->GetAttribLocation("position");
quadPositionAttrib_ = quadShaderProgram_->attributeLocation("position");
if (quadPositionAttrib_ == -1) {
ERROR("Quad position attribute lookup failed");
return false;
}
glCullFace(GL_BACK);
glBindVertexArray(quadVAO_);
glBindBuffer(GL_ARRAY_BUFFER, quadPosbufferObject_);
glEnableVertexAttribArray(quadPositionAttrib_);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableVertexAttribArray(quadPositionAttrib_);
glBindVertexArray(0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
if (CheckGLError("Quad rendering") != GL_NO_ERROR) {
return false;
}
glUseProgram(0);
//timer_.stop();
//double time = timer_.elapsed().wall / 1.0e9;
//INFO("total time: " << time << "s");
// Window manager takes care of swapping buffers
return true;
}
bool Raycaster::LaunchTSPTraversal(unsigned int _timestep) {
if (!clManager_->SetInt("TSPTraversal", tspTimestepArg_, _timestep)) {
ERROR("RunTSPTraversal() - Failed to set timestep");
return false;
}
if (!clManager_->AddBuffer("TSPTraversal", tspBrickListArg_,
reinterpret_cast<void*>(&brickRequest_[0]),
brickRequest_.size()*sizeof(int),
CLManager::COPY_HOST_PTR,
CLManager::READ_WRITE)) return false;
if (!clManager_->PrepareProgram("TSPTraversal")) return false;
if (!clManager_->LaunchProgram("TSPTraversal",
winWidth_,
winHeight_,
config_->LocalWorkSizeX(),
config_->LocalWorkSizeY())) return false;
return true;
}
bool Raycaster::InitPipeline() {
INFO("Initializing pipeline");
if (!tsp_) {
ERROR("InitPipeline(): No TSP set");
return false;
}
if (!brickManager_) {
ERROR("InitPipeline(): No BrickManager set");
return false;
}
// Allocate space for the brick request list
// Use 0 as default value
brickRequest_.resize(tsp_->NumTotalNodes(), 0);
glFinish();
// Run TSP traversal for timestep 0
if (!LaunchTSPTraversal(0)) {
ERROR("InitPipeline() - failed to launch TSP traversal");
return false;
}
// Finish TSP traversal and read results into brick request
if (!clManager_->FinishProgram("TSPTraversal")) return false;
if (!clManager_->ReadBuffer("TSPTraversal", tspBrickListArg_,
reinterpret_cast<void*>(&brickRequest_[0]),
brickRequest_.size()*sizeof(int),
true)) return false;
// Free device memory
if (!clManager_->ReleaseBuffer("TSPTraversal",tspBrickListArg_))return false;
// Upload data for timestep 0 to PBO
if (!brickManager_->BuildBrickList(BrickManager::EVEN,
brickRequest_)) return false;
if (!brickManager_->DiskToPBO(BrickManager::EVEN)) return false;
//if (!brickManager_->PBOToAtlas(BrickManager::EVEN)) return false;
return true;
}
void Raycaster::SetAnimator(Animator *_animator) {
animator_ = _animator;
}
void Raycaster::SetBrickManager(BrickManager *_brickManager) {
brickManager_ = _brickManager;
}
bool Raycaster::InitCube() {
glGetError();
float v[] = {
// front
1.f, 0.f, 0.f, 1.f,
0.f, 1.f, 0.f, 1.f,
0.f, 0.f, 0.f, 1.f,
1.f, 0.f, 0.f, 1.f,
1.f, 1.f, 0.f, 1.f,
0.f, 1.f, 0.f, 1.f,
// right
1.f, 0.f, 0.f, 1.f,
1.f, 0.f, 1.f, 1.f,
1.f, 1.f, 0.f, 1.f,
1.f, 0.f, 1.f, 1.f,
1.f, 1.f, 1.f, 1.f,
1.f, 1.f, 0.f, 1.f,
// back
1.f, 1.f, 1.f, 1.f,
0.f, 0.f, 1.f, 1.f,
0.f, 1.f, 1.f, 1.f,
1.f, 1.f, 1.f, 1.f,
1.f, 0.f, 1.f, 1.f,
0.f, 0.f, 1.f, 1.f,
// left
0.f, 0.f, 1.f, 1.f,
0.f, 0.f, 0.f, 1.f,
0.f, 1.f, 1.f, 1.f,
0.f, 0.f, 0.f, 1.f,
0.f, 1.f, 0.f, 1.f,
0.f, 1.f, 1.f, 1.f,
// top
0.f, 1.f, 0.f, 1.f,
1.f, 1.f, 0.f, 1.f,
0.f, 1.f, 1.f, 1.f,
0.f, 1.f, 1.f, 1.f,
1.f, 1.f, 0.f, 1.f,
1.f, 1.f, 1.f, 1.f,
// bottom
0.f, 0.f, 0.f, 1.f,
0.f, 0.f, 1.f, 1.f,
1.f, 0.f, 1.f, 1.f,
0.f, 0.f, 0.f, 1.f,
1.f, 0.f, 1.f, 1.f,
1.f, 0.f, 0.f, 1.f
};
glGenVertexArrays(1, &cubeVAO_);
glBindVertexArray(cubeVAO_);
glGenBuffers(1, &cubePosbufferObject_);
glBindBuffer(GL_ARRAY_BUFFER, cubePosbufferObject_);
glBufferData(GL_ARRAY_BUFFER, sizeof(float)*144, v, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
if (CheckGLError("InitCube()") != GL_NO_ERROR) {
return false;
}
cubeInitialized_ = true;
return true;
}
bool Raycaster::InitQuad() {
glGetError();
float v[] = {
-1.f, -1.f, 0.f, 1.f,
1.f, -1.f, 0.f, 1.f,
-1.f, 1.f, 0.f, 1.f,
1.f, -1.f, 0.f, 1.f,
1.f, 1.f, 0.f, 1.f,
-1.f, 1.0, 0.f, 1.f,
};
glGenVertexArrays(1, &quadVAO_);
glBindVertexArray(quadVAO_);
glGenBuffers(1, &quadPosbufferObject_);
glBindBuffer(GL_ARRAY_BUFFER, quadPosbufferObject_);
glBufferData(GL_ARRAY_BUFFER, sizeof(float)*24, v, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
if (CheckGLError("InitQuad()") != GL_NO_ERROR) {
return false;
}
quadInitialized_ = true;
return true;
}
bool Raycaster::InitFramebuffers() {
glGetError();
if (winWidth_ == 0 || winHeight_ == 0) {
ERROR("Raycaster window dimension(s) are zero");
return false;
}
if (cubeFrontTex_ == NULL || cubeBackTex_ == NULL) {
ERROR("Can't init framebuffers, textures are not set");
return false;
}
// Renderbuffer for depth component
INFO("Initializing renderbuffer for depth");
glGenRenderbuffers(1, &renderbufferObject_);
glBindRenderbuffer(GL_RENDERBUFFER, renderbufferObject_);
glRenderbufferStorage(GL_RENDERBUFFER,
GL_DEPTH_COMPONENT,
winWidth_,
winHeight_);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
CheckGLError("Init renderbuffer");
// Front cube
INFO("Initializing front cube framebuffer");
glGenFramebuffers(1, &cubeFrontFBO_);
glBindFramebuffer(GL_FRAMEBUFFER, cubeFrontFBO_);
glFramebufferTexture2D(GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D,
*cubeFrontTex_,
0);
glFramebufferRenderbuffer(GL_FRAMEBUFFER,
GL_DEPTH_ATTACHMENT,
GL_RENDERBUFFER,
renderbufferObject_);
GLenum status;
status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
ERROR("Front cube framebuffer not complete");
CheckGLError("Front cube framebuffer");
return false;
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// Back cube
INFO("Initializing back cube framebuffer");
glGenFramebuffers(1, &cubeBackFBO_);
glBindFramebuffer(GL_FRAMEBUFFER, cubeBackFBO_);
glFramebufferTexture2D(GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D,
*cubeBackTex_,
0);
glFramebufferRenderbuffer(GL_FRAMEBUFFER,
GL_DEPTH_ATTACHMENT,
GL_RENDERBUFFER,
renderbufferObject_);
status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
ERROR("Back cube framebuffer not complete");
CheckGLError("Back cube framebuffer");
return false;
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
if (CheckGLError("InitFramebuffers()") != GL_NO_ERROR) {
return false;
}
INFO("Initializing framebuffers... complete");
framebuffersInitialized_ = true;
return true;
}
bool Raycaster::ReloadTransferFunctions() {
INFO("Reloading transfer functions");
if (!transferFunctions_[0]->ReadFile()) return false;
if (!transferFunctions_[0]->ConstructTexture()) return false;
if (!clManager_->AddTexture("RaycasterTSP", transferFunctionArg_,
transferFunctions_[0]->Texture(),
CLManager::TEXTURE_2D,
CLManager::READ_ONLY)) return false;
return true;
}
bool Raycaster::UpdateMatrices() {
model_ = glm::mat4(1.f);
model_ = glm::translate(model_, glm::vec3(0.5f, 0.5f, 0.5f));
model_ = glm::rotate(model_, roll_, glm::vec3(1.f, 0.f, 0.f));
model_ = glm::rotate(model_, -pitch_, glm::vec3(0.f, 1.f, 0.0));
model_ = glm::rotate(model_, yaw_, glm::vec3(0.f, 0.f, 1.f));
model_ = glm::translate(model_, glm::vec3(-0.5f, -0.5f, -0.5f));
/*
view_ = glm::rotate(glm::mat4(1.f), 180.f, glm::vec3(1.f, 0.f, 0.f));
view_ = glm::translate(view_, glm::vec3(-0.5f, -0.5f, zoom_));
*/
glm::mat4 sgctView = sgct::Engine::instance()->getActiveViewMatrix();
view_ = glm::translate(sgctView, glm::vec3(translateX_,
translateY_,
translateZ_));
return true;
}
bool Raycaster::BindTransformationMatrices(ghoul::opengl::ProgramObject * _program)
{
if (!_program->setUniform("modelMatrix", model_)) return false;
if (!_program->setUniform("viewMatrix", view_)) return false;
if (!_program->setUniform("projectionMatrix", proj_)) return false;
/*
if (!_program->BindMatrix4f("modelMatrix", &model_[0][0])) return false;
if (!_program->BindMatrix4f("viewMatrix", &view_[0][0])) return false;
if (!_program->BindMatrix4f("projectionMatrix", &proj_[0][0])) return false;
*/
return true;
}
void Raycaster::SetCubeFrontTexture(ghoul::opengl::Texture *_cubeFrontTexture) {
cubeFrontTex_ = _cubeFrontTexture;
}
void Raycaster::SetCubeBackTexture(ghoul::opengl::Texture *_cubeBackTexture) {
cubeBackTex_ = _cubeBackTexture;
}
void Raycaster::SetQuadTexture(ghoul::opengl::Texture *_quadTexture) {
quadTex_ = _quadTexture;
}
void Raycaster::SetCLManager(CLManager *_clManager) {
clManager_ = _clManager;
}
void Raycaster::SetTSP(TSP *_tsp) {
tsp_ = _tsp;
}
void Raycaster::SetCubeShaderProgram(ghoul::opengl::ProgramObject *_cubeShaderProgram) {
cubeShaderProgram_ = _cubeShaderProgram;
}
void Raycaster::SetQuadShaderProgram(ghoul::opengl::ProgramObject *_quadShaderProgram) {
quadShaderProgram_ = _quadShaderProgram;
}
bool Raycaster::ReloadShaders() {
glGetError();
INFO("Reloading shaders");
if (!cubeShaderProgram_->rebuildFromFile()) return false;
if (!quadShaderProgram_->rebuildFromFile()) return false;
CheckGLError("ReloadShaders()");
return true;
}
bool Raycaster::Reload() {
if (!config_->Read()) return false;
INFO("Config file read");
if (!UpdateKernelConstants()) return false;
INFO("Kernel constants updated");
if (!ReloadShaders()) return false;
INFO("Shaders reloaded");
if (!ReloadTransferFunctions()) return false;
INFO("Transfer functions reloaded");
if (!animator_->UpdateConfig()) return false;
INFO("Animator updated");
return true;
}
bool Raycaster::InitCL() {
INFO("Initializing OpenCL");
if (!clManager_) {
ERROR("InitCL() - No CL manager has been set");
return false;
}
// Init common OpenCL resources
if (!clManager_->InitPlatform()) return false;
if (!clManager_->InitDevices()) return false;
if (!clManager_->CreateContext()) return false;
if (!clManager_->CreateCommandQueue()) return false;
// TSP traversal part of raycaster
if (!clManager_->CreateProgram("TSPTraversal",
config_->TSPTraversalKernelFilename())) {
return false;
}
if (!clManager_->BuildProgram("TSPTraversal")) return false;
if (!clManager_->CreateKernel("TSPTraversal")) return false;
//cl_mem cubeFrontCLmem;
if (!clManager_->AddTexture("TSPTraversal", tspCubeFrontArg_,
cubeFrontTex_, CLManager::TEXTURE_2D,
CLManager::READ_ONLY, cubeFrontCLmem)) {
return false;
}
//cl_mem cubeBackCLmem;
if (!clManager_->AddTexture("TSPTraversal", tspCubeBackArg_,
cubeBackTex_, CLManager::TEXTURE_2D,
CLManager::READ_ONLY, cubeBackCLmem)) {
return false;
}
/*
if (!clManager_->AddTexture("TSPTraversal", quadArg_, quadTex_,
CLManager::TEXTURE_2D,
CLManager::WRITE_ONLY)) return false;
*/
if (!clManager_->AddBuffer("TSPTraversal", tspTSPArg_,
reinterpret_cast<void*>(tsp_->Data()),
tsp_->Size()*sizeof(int),
CLManager::COPY_HOST_PTR,
CLManager::READ_ONLY)) return false;
LDEBUGC("RAYCASTER", config_->RaycasterKernelFilename());
// Raycaster part
if (!clManager_->CreateProgram("RaycasterTSP",
config_->RaycasterKernelFilename())) {
return false;
}
if (!clManager_->BuildProgram("RaycasterTSP")) return false;
if (!clManager_->CreateKernel("RaycasterTSP")) return false;
if (!clManager_->AddTexture("RaycasterTSP", cubeFrontArg_, cubeFrontCLmem,
CLManager::READ_ONLY)) return false;
if (!clManager_->AddTexture("RaycasterTSP", cubeBackArg_, cubeBackCLmem,
CLManager::READ_ONLY)) return false;
if (!clManager_->AddTexture("RaycasterTSP", quadArg_, quadTex_,
CLManager::TEXTURE_2D,
CLManager::WRITE_ONLY)) return false;
if (!clManager_->AddTexture("RaycasterTSP", textureAtlasArg_,
brickManager_->TextureAtlas(),
CLManager::TEXTURE_3D,
CLManager::READ_ONLY)) return false;
if (!clManager_->AddTexture("RaycasterTSP", transferFunctionArg_,
transferFunctions_[0]->Texture(),
CLManager::TEXTURE_2D,
CLManager::READ_ONLY)) return false;
// Add transfer function
//float* tfData = transferFunctions_[0]->FloatData();
//unsigned int tfSize = sizeof(float)*transferFunctions_[0]->Width()*4;
//if (!clManager_->AddBuffer("RaycasterTSP", transferFunctionArg_,
// reinterpret_cast<void*>(tfData),
// tfSize,
// CLManager::COPY_HOST_PTR,
// CLManager::READ_ONLY)) return false;
if (!clManager_->AddBuffer("RaycasterTSP", tspArg_,
reinterpret_cast<void*>(tsp_->Data()),
tsp_->Size()*sizeof(int),
CLManager::COPY_HOST_PTR,
CLManager::READ_ONLY)) return false;
// Update and add kernel constants
if (!UpdateKernelConstants()) return false;
return true;
}
bool Raycaster::UpdateKernelConstants() {
INFO("Updating kernel constants");
if (!tsp_) {
ERROR("TSP not set, cannot update kernel constants");
return false;
}
if (!config_) {
ERROR("Config not set, cannot update kernel constants");
return false;
}
kernelConstants_.gridType_ = static_cast<int>(brickManager_->GridType());
kernelConstants_.stepsize_ = config_->RaycasterStepsize();
kernelConstants_.intensity_ = config_->RaycasterIntensity();
kernelConstants_.numTimesteps_ = static_cast<int>(tsp_->NumTimesteps());
kernelConstants_.numValuesPerNode_ =
static_cast<int>(tsp_->NumValuesPerNode());
kernelConstants_.numOTNodes_ = static_cast<int>(tsp_->NumOTNodes());
kernelConstants_.numBoxesPerAxis_ =
static_cast<int>(tsp_->NumBricksPerAxis());
kernelConstants_.temporalTolerance_ = config_->TemporalErrorTolerance();
kernelConstants_.spatialTolerance_ = config_->SpatialErrorTolerance();
kernelConstants_.rootLevel_ = static_cast<int>(tsp_->NumOTLevels()) - 1;
kernelConstants_.paddedBrickDim_ = static_cast<int>(tsp_->PaddedBrickDim());
traversalConstants_.gridType_ = static_cast<int>(brickManager_->GridType());
traversalConstants_.stepsize_ = config_->TSPTraversalStepsize();
traversalConstants_.numTimesteps_ = static_cast<int>(tsp_->NumTimesteps());
traversalConstants_.numValuesPerNode_ =
static_cast<int>(tsp_->NumValuesPerNode());
traversalConstants_.numOTNodes_ = static_cast<int>(tsp_->NumOTNodes());
traversalConstants_.temporalTolerance_ = config_->TemporalErrorTolerance();
traversalConstants_.spatialTolerance_ = config_->SpatialErrorTolerance();
std::string _loggerCat = "KOLLA KONSTANTER";
LDEBUG("traversalConstants_.gridType_: " << traversalConstants_.gridType_);
LDEBUG("traversalConstants_.numOTNodes_: " << traversalConstants_.numOTNodes_);
LDEBUG("traversalConstants_.numTimesteps_: " << traversalConstants_.numTimesteps_);
LDEBUG("traversalConstants_.numValuesPerNode_: " << traversalConstants_.numValuesPerNode_);
LDEBUG("traversalConstants_.spatialTolerance_: " << traversalConstants_.spatialTolerance_);
LDEBUG("traversalConstants_.stepsize_: " << traversalConstants_.stepsize_);
LDEBUG("traversalConstants_.temporalTolerance_: " << traversalConstants_.temporalTolerance_);
if (!clManager_->AddBuffer("RaycasterTSP", constantsArg_,
reinterpret_cast<void*>(&kernelConstants_),
sizeof(KernelConstants),
CLManager::COPY_HOST_PTR,
CLManager::READ_ONLY)) return false;
if (!clManager_->AddBuffer("TSPTraversal", tspConstantsArg_,
reinterpret_cast<void*>(&traversalConstants_),
sizeof(TraversalConstants),
CLManager::COPY_HOST_PTR,
CLManager::READ_ONLY)) return false;
return true;
}
void Raycaster::AddTransferFunction(TransferFunction *_transferFunction) {
transferFunctions_.push_back(_transferFunction);
}
void Raycaster::SetModelParams(float _pitch, float _yaw, float _roll) {
pitch_ = _pitch;
yaw_ = _yaw;
roll_ = _roll;
}
void Raycaster::SetViewParams(float _translateX,
float _translateY,
float _translateZ) {
translateX_ = _translateX;
translateY_ = _translateY;
translateZ_ = _translateZ;
}
-64
View File
@@ -1,64 +0,0 @@
/*
* Author: Victor Sand (victor.sand@gmail.com)
*
*/
#include <openspace/flare/Renderer.h>
#include <utility>
using namespace osp;
Renderer::Renderer()
: winWidth_(0),
winHeight_(0),
leftMouseDown_(false),
rightMouseDown_(false),
currentMouseX_(0),
currentMouseY_(0),
lastMouseX_(0),
lastMouseY_(0) {
}
Renderer::~Renderer() {
}
void Renderer::SetWinWidth(unsigned int _winWidth) {
winWidth_ = _winWidth;
}
void Renderer::SetWinHeight(unsigned int _winHeight) {
winHeight_ = _winHeight;
}
void Renderer::SetMousePosition(float _mouseX, float _mouseY) {
lastMouseX_ = currentMouseX_;
lastMouseY_ = currentMouseY_;
currentMouseX_ = _mouseX;
currentMouseY_ = _mouseY;
}
void Renderer::SetMousePressed(bool _leftPressed, bool _rightPressed) {
leftMouseDown_ = _leftPressed;
rightMouseDown_ = _rightPressed;
}
void Renderer::SetKeyPressed(int _key, bool _pressed) {
std::map<int, bool>::iterator it;
it = keysPressed_.find(_key);
if (it == keysPressed_.end()) {
keysPressed_.insert(std::make_pair(_key, _pressed));
} else {
it->second = _pressed;
}
}
bool Renderer::KeyPressed(int _key) const {
std::map<int, bool>::const_iterator it;
it = keysPressed_.find(_key);
if (it == keysPressed_.end()) {
return false;
} else {
return it->second;
}
}
-729
View File
@@ -1,729 +0,0 @@
/*
* Author: Victor Sand (victor.sand@gmail.com)
*
*/
#include <openspace/flare/TSP.h>
#include <openspace/flare/Config.h>
#include <stdio.h>
#include <openspace/flare/Utils.h>
#include <cmath>
#include <list>
#include <queue>
#include <openspace/flare/TransferFunction.h>
#include <algorithm>
using namespace osp;
TSP::TSP(Config *_config) : config_(_config) {
}
TSP * TSP::New(Config *_config) {
return new TSP(_config);
}
TSP::~TSP() {
}
bool TSP::ReadHeader() {
INFO("\nReading header for TSP construction");
std::string inFilename = config_->TSPFilename();
std::FILE *in = fopen(inFilename.c_str(), "r");
if (!in) {
ERROR("Failed to open " << inFilename);
return false;
}
// Read header
size_t s = sizeof(unsigned int);
fread(reinterpret_cast<void*>(&gridType_), s, 1, in);
fread(reinterpret_cast<void*>(&numOrigTimesteps_), s, 1, in);
fread(reinterpret_cast<void*>(&numTimesteps_), s, 1, in);
fread(reinterpret_cast<void*>(&xBrickDim_), s, 1, in);
fread(reinterpret_cast<void*>(&yBrickDim_), s, 1, in);
fread(reinterpret_cast<void*>(&zBrickDim_), s, 1, in);
fread(reinterpret_cast<void*>(&xNumBricks_), s, 1, in);
fread(reinterpret_cast<void*>(&yNumBricks_), s, 1, in);
fread(reinterpret_cast<void*>(&zNumBricks_), s, 1, in);
INFO("Brick dimensions: "<<xBrickDim_<<" "<<yBrickDim_<<" "<< zBrickDim_);
INFO("Num bricks: "<<xNumBricks_<<" "<<yNumBricks_ <<" "<< zNumBricks_);
#ifdef WIN32
dataPos_ = _ftelli64(in);
#else
dataPos_ = ftello(in);
#endif
paddedBrickDim_ = xBrickDim_ + 2*paddingWidth_;
// TODO support dimensions of different size
numOTLevels_ = (unsigned int)(log((int)xNumBricks_)/log(2) + 1);
numOTNodes_ = (unsigned int)((pow(8, numOTLevels_) - 1) / 7);
numBSTLevels_ = (unsigned int)(log((int)numTimesteps_)/log(2) + 1);
numBSTNodes_ = (unsigned int)numTimesteps_*2 - 1;
numTotalNodes_ = numOTNodes_ * numBSTNodes_;
INFO("Num OT levels: " << numOTLevels_);
INFO("Num OT nodes: " << numOTNodes_);
INFO("Num BST levels: " << numBSTLevels_);
INFO("Num BST nodes: " << numBSTNodes_);
INFO("NUm total nodes: " << numTotalNodes_);
fclose(in);
// Allocate space for TSP structure
data_.resize(numTotalNodes_*NUM_DATA);
INFO("data size: " << data_.size());
return true;
}
bool TSP::Construct() {
INFO("\nConstructing TSP tree");
// Loop over the OTs (one per BST node)
for (unsigned int OT=0; OT<numBSTNodes_; ++OT) {
// Start at the root of each OT
unsigned int OTNode = OT*numOTNodes_;
// Calculate BST level (first level is level 0)
unsigned int BSTLevel = (unsigned int)(log(OT+1)/log(2));
// Traverse OT
unsigned int OTChild = 1;
unsigned int OTLevel = 0;
while (OTLevel < numOTLevels_) {
unsigned int OTNodesInLevel = static_cast<unsigned int>(pow(8, OTLevel));
for (unsigned int i=0; i<OTNodesInLevel; ++i) {
// Brick index
data_[OTNode*NUM_DATA + BRICK_INDEX] = (int)OTNode;
// Error metrics
//int localOTNode = (OTNode - OT*numOTNodes_);
data_[OTNode*NUM_DATA + TEMPORAL_ERR] = (int)(numBSTLevels_-1-BSTLevel);
data_[OTNode*NUM_DATA + SPATIAL_ERR] = (int)(numOTLevels_-1-OTLevel);
if (BSTLevel == 0) {
// Calculate OT child index (-1 if node is leaf)
int OTChildIndex =
(OTChild < numOTNodes_) ? (int)(OT*numOTNodes_+OTChild) : -1;
data_[OTNode*NUM_DATA + CHILD_INDEX] = OTChildIndex;
} else {
// Calculate BST child index (-1 if node is BST leaf)
// First BST node of current level
int firstNode =
static_cast<unsigned int>((2*pow(2, BSTLevel-1)-1)*numOTNodes_);
// First BST node of next level
int firstChild =
static_cast<unsigned int>((2*pow(2, BSTLevel)-1)*numOTNodes_);
// Difference between first nodes between levels
int levelGap = firstChild-firstNode;
// How many nodes away from the first node are we?
int offset = (OTNode-firstNode) / numOTNodes_;
// Use level gap and offset to calculate child index
int BSTChildIndex =
(BSTLevel < numBSTLevels_-1) ?
(int)(OTNode+levelGap+(offset*numOTNodes_)) : -1;
data_[OTNode*NUM_DATA + CHILD_INDEX] = BSTChildIndex;
}
OTNode++;
OTChild += 8;
}
OTLevel++;
}
}
return true;
}
bool TSP::CalculateSpatialError() {
unsigned int numBrickVals = paddedBrickDim_*paddedBrickDim_*paddedBrickDim_;
std::string inFilename = config_->TSPFilename();
std::FILE *in = fopen(inFilename.c_str(), "r");
if (!in) {
ERROR("Failed to open" << inFilename);
return false;
}
std::vector<float> buffer(numBrickVals);
std::vector<float> averages(numTotalNodes_);
std::vector<float> stdDevs(numTotalNodes_);
// First pass: Calculate average color for each brick
INFO("\nCalculating spatial error, first pass");
for (unsigned int brick=0; brick<numTotalNodes_; ++brick) {
// Offset in file
#ifdef WIN32
long long offset = dataPos_ + static_cast<long long>(brick*numBrickVals*sizeof(float));
_fseeki64(in, offset, SEEK_SET);
#else
off_t offset = dataPos_ + static_cast<off_t>(brick*numBrickVals*sizeof(float));
fseeko(in, offset, SEEK_SET);
#endif
fread(reinterpret_cast<void*>(&buffer[0]),
static_cast<size_t>(numBrickVals)*sizeof(float), 1, in);
float average = 0.f;
for (auto it=buffer.begin(); it!=buffer.end(); ++it) {
average += *it;
}
//INFO("averages[" << brick << "]");
averages[brick] = average/static_cast<float>(numBrickVals);
}
// Spatial SNR stats
float minError = 1e20f;
float maxError = 0.f;
std::vector<float> medianArray(numTotalNodes_);
// Second pass: For each brick, compare the covered leaf voxels with
// the brick average
INFO("Calculating spatial error, second pass");
for (unsigned int brick=0; brick<numTotalNodes_; ++brick) {
// Fetch mean intensity
float brickAvg = averages[brick];
// Sum for std dev computation
float stdDev = 0.f;
// Get a list of leaf bricks that the current brick covers
std::list<unsigned int> coveredLeafBricks =
CoveredLeafBricks(brick);
// If the brick is already a leaf, assign a negative error.
// Ad hoc "hack" to distinguish leafs from other nodes that happens
// to get a zero error due to rounding errors or other reasons.
if (coveredLeafBricks.size() == 1) {
stdDev = -0.1f;
} else {
// Calculate "standard deviation" corresponding to leaves
for (auto lb=coveredLeafBricks.begin();
lb!=coveredLeafBricks.end(); ++lb) {
// Read brick
#ifdef WIN32
long long offset = dataPos_ + static_cast<long long>((*lb)*numBrickVals*sizeof(float));
_fseeki64(in, offset, SEEK_SET);
#else
off_t offset = dataPos_+static_cast<off_t>((*lb)*numBrickVals*sizeof(float));
fseeko(in, offset, SEEK_SET);
#endif
fread(reinterpret_cast<void*>(&buffer[0]),
static_cast<size_t>(numBrickVals)*sizeof(float), 1, in);
// Add to sum
for (auto v=buffer.begin(); v!=buffer.end(); ++v) {
stdDev += pow(*v-brickAvg, 2.f);
}
}
// Finish calculation
if (sizeof(float) != sizeof(int)) {
ERROR("Float and int sizes don't match, can't reintepret");
return false;
}
stdDev /= static_cast<float>(coveredLeafBricks.size()*numBrickVals);
stdDev = sqrt(stdDev);
} // if not leaf
if (stdDev < minError) {
minError = stdDev;
} else if (stdDev > maxError) {
maxError = stdDev;
}
stdDevs[brick] = stdDev;
medianArray[brick] = stdDev;
}
fclose(in);
std::sort(medianArray.begin(), medianArray.end());
//float medError = medianArray[medianArray.size()/2];
/*
INFO("\nMin spatial std dev: " << minError);
INFO("Max spatial std dev: " << maxError);
INFO("Median spatial std dev: " << medError);
INFO("");
*/
// "Normalize" errors
float minNorm = 1e20f;
float maxNorm = 0.f;
for (unsigned int i=0; i<numTotalNodes_; ++i) {
//float normalized = (stdDevs[i]-minError)/(maxError-minError);
if (stdDevs[i] > 0.f) {
stdDevs[i] = pow(stdDevs[i], 0.5f);
}
data_[i*NUM_DATA+SPATIAL_ERR] = *reinterpret_cast<int*>(&stdDevs[i]);
if (stdDevs[i] < minNorm) {
minNorm = stdDevs[i];
} else if (stdDevs[i] > maxNorm) {
maxNorm = stdDevs[i];
}
}
std::sort(stdDevs.begin(), stdDevs.end());
float medNorm = stdDevs[stdDevs.size()/2];
minSpatialError_ = minNorm;
maxSpatialError_ = maxNorm;
medianSpatialError_ = medNorm;
INFO("\nMin normalized spatial std dev: " << minNorm);
INFO("Max normalized spatial std dev: " << maxNorm);
INFO("Median normalized spatial std dev: " << medNorm);
return true;
}
bool TSP::CalculateTemporalError() {
std::string inFilename = config_->TSPFilename();
std::FILE *in = fopen(inFilename.c_str(), "r");
if (!in) {
ERROR("Failed to open " << inFilename);
return false;
}
INFO("\nCalculating temporal error");
// Statistics
//float minErr = 1e20f;
//float maxErr = 0.f;
std::vector<float> meanArray(numTotalNodes_);
// Save errors
std::vector<float> errors(numTotalNodes_);
// Calculate temporal error for one brick at a time
for (unsigned int brick=0; brick<numTotalNodes_; ++brick) {
unsigned int numBrickVals =
paddedBrickDim_*paddedBrickDim_*paddedBrickDim_;
// Save the individual voxel's average over timesteps. Because the
// BSTs are built by averaging leaf nodes, we only need to sample
// the brick at the correct coordinate.
std::vector<float> voxelAverages(numBrickVals);
std::vector<float> voxelStdDevs(numBrickVals);
// Read the whole brick to fill the averages
#ifdef WIN32
long long offset = dataPos_ + static_cast<long long>(brick*numBrickVals*sizeof(float));
_fseeki64(in, offset, SEEK_SET);
#else
off_t offset = dataPos_+static_cast<off_t>(brick*numBrickVals*sizeof(float));
fseeko(in, offset, SEEK_SET);
#endif
fread(reinterpret_cast<void*>(&voxelAverages[0]),
static_cast<size_t>(numBrickVals)*sizeof(float), 1, in);
// Build a list of the BST leaf bricks (within the same octree level) that
// this brick covers
std::list<unsigned int> coveredBricks = CoveredBSTLeafBricks(brick);
// If the brick is at the lowest BST level, automatically set the error
// to -0.1 (enables using -1 as a marker for "no error accepted");
// Somewhat ad hoc to get around the fact that the error could be
// 0.0 higher up in the tree
if (coveredBricks.size() == 1) {
errors[brick] = -0.1f;
} else {
// Calculate standard deviation per voxel, average over brick
float avgStdDev = 0.f;
for (unsigned int voxel=0; voxel<numBrickVals; ++voxel) {
float stdDev = 0.f;
for (auto leaf = coveredBricks.begin();
leaf != coveredBricks.end(); ++leaf) {
// Sample the leaves at the corresponding voxel position
#ifdef WIN32
long long sampleOffset = dataPos_ +
static_cast<long long>((*leaf*numBrickVals + voxel)*sizeof(float));
_fseeki64(in, sampleOffset, SEEK_SET);
#else
off_t sampleOffset = dataPos_ +
static_cast<off_t>((*leaf*numBrickVals + voxel)*sizeof(float));
fseeko(in, sampleOffset, SEEK_SET);
#endif
float sample;
fread(reinterpret_cast<void*>(&sample), sizeof(float), 1, in);
stdDev += pow(sample-voxelAverages[voxel], 2.f);
}
stdDev /= static_cast<float>(coveredBricks.size());
stdDev = sqrt(stdDev);
avgStdDev += stdDev;
} // for voxel
avgStdDev /= static_cast<float>(numBrickVals);
meanArray[brick] = avgStdDev;
errors[brick] = avgStdDev;
}
/*
if (avgStdDev < minErr) {
minErr = avgStdDev;
} else if (avgStdDev > maxErr) {
maxErr = avgStdDev;
}
*/
} // for all bricks
fclose(in);
std::sort(meanArray.begin(), meanArray.end());
//float medErr = meanArray[meanArray.size()/2];
/*
INFO("\nMin temporal error: " << minErr);
INFO("Max temporal error: " << maxErr);
INFO("Median temporal error: " << medErr);
*/
// Adjust errors using user-provided exponents
float minNorm = 1e20f;
float maxNorm = 0.f;
for (unsigned int i=0; i<numTotalNodes_; ++i) {
if (errors[i] > 0.f) {
errors[i] = pow(errors[i], 0.25f);
}
data_[i*NUM_DATA+TEMPORAL_ERR] = *reinterpret_cast<int*>(&errors[i]);
if (errors[i] < minNorm) {
minNorm = errors[i];
} else if (errors[i] > maxNorm) {
maxNorm = errors[i];
}
}
std::sort(errors.begin(), errors.end());
float medNorm = errors[errors.size()/2];
minTemporalError_ = minNorm;
maxTemporalError_ = maxNorm;
medianTemporalError_ = medNorm;
INFO("\nMin normalized temporal std dev: " << minNorm);
INFO("Max normalized temporal std dev: " << maxNorm);
INFO("Median normalized temporal std dev: " << medNorm);
return true;
}
std::list<unsigned int> TSP::CoveredBSTLeafBricks(unsigned int _brickIndex) {
std::list<unsigned int> out;
// Traverse the BST children until we are at root
std::queue<unsigned int> queue;
queue.push(_brickIndex);
do {
unsigned int toVisit = queue.front();
queue.pop();
bool BSTRoot = toVisit < numOTNodes_;
if (BSTRoot) {
if (numBSTLevels_ == 1) {
out.push_back(toVisit);
} else {
queue.push(toVisit + numOTNodes_);
queue.push(toVisit + numOTNodes_*2);
}
} else {
int child = data_[toVisit*NUM_DATA + CHILD_INDEX];
if (child == -1) {
// Save leaf brick to list
out.push_back(toVisit);
} else {
// Queue children
queue.push(child);
queue.push(child+numOTNodes_);
}
}
} while (!queue.empty());
return out;
}
std::list<unsigned int> TSP::CoveredLeafBricks(unsigned int _brickIndex) {
std::list<unsigned int> out;
// Find what octree skeleton node the index belongs to
unsigned int OTNode = _brickIndex % numOTNodes_;
// Find what BST node the index corresponds to using int division
unsigned int BSTNode = _brickIndex / numOTNodes_;
// Calculate BST offset (to translate to root octree)
unsigned int BSTOffset = BSTNode * numOTNodes_;
// Traverse root octree structure to leaves
// When visiting the leaves, translate back to correct BST level and save
std::queue<unsigned int> queue;
queue.push(OTNode);
do {
// Get front of queue and pop it
unsigned int toVisit = queue.front();
queue.pop();
// See if the node has children
int child = data_[toVisit*NUM_DATA + CHILD_INDEX];
if (child == -1) {
// Translate back and save
out.push_back(toVisit+BSTOffset);
} else {
// Queue the eight children
for (int i=0; i<8; ++i) {
queue.push(child+i);
}
}
} while (!queue.empty());
return out;
}
float TSP::SquaredDist(Color _c1, Color _c2) {
// Weighted by the c1 opacity, because transparent voxels have
// less contribution to the final image
return _c1.a*( pow(_c1.r-_c2.r, 2.f) + pow(_c1.g-_c2.g, 2.f) +
pow(_c1.b-_c2.b, 2.f) ) + pow(_c1.a-_c2.a, 2.f);
}
bool TSP::ReadCache() {
std::string cacheFilename = config_->TSPFilename() + ".cache";
std::FILE *in = fopen(cacheFilename.c_str(), "r");
if (!in) {
ERROR("Failed to open " << cacheFilename);
return false;
}
fread(reinterpret_cast<void*>(&minSpatialError_), sizeof(float), 1, in);
fread(reinterpret_cast<void*>(&maxSpatialError_), sizeof(float), 1, in);
fread(reinterpret_cast<void*>(&medianSpatialError_), sizeof(float), 1, in);
fread(reinterpret_cast<void*>(&minTemporalError_), sizeof(float), 1, in);
fread(reinterpret_cast<void*>(&maxTemporalError_), sizeof(float), 1, in);
fread(reinterpret_cast<void*>(&medianTemporalError_), sizeof(float), 1, in);
size_t dataSize = static_cast<size_t>(numTotalNodes_*NUM_DATA)*sizeof(int);
fread(reinterpret_cast<void*>(&data_[0]), dataSize, 1, in);
fclose(in);
INFO("\nCached errors:");
INFO("Min spatial error: " << minSpatialError_);
INFO("Max spatial error: " << maxSpatialError_);
INFO("Median spatial error: " << medianSpatialError_);
INFO("Min temporal error: " << minTemporalError_);
INFO("Max temporal error: " << maxTemporalError_);
INFO("Median temporal error: " << medianTemporalError_);
return true;
}
bool TSP::WriteCache() {
std::string cacheFilename = config_->TSPFilename() + ".cache";
INFO("Writing cache to " << cacheFilename);
std::FILE *out = fopen(cacheFilename.c_str(), "w");
if (!out) {
ERROR("Failed to init " << cacheFilename);
return false;
}
fwrite(reinterpret_cast<void*>(&minSpatialError_), sizeof(float), 1, out);
fwrite(reinterpret_cast<void*>(&maxSpatialError_), sizeof(float), 1, out);
fwrite(reinterpret_cast<void*>(&medianSpatialError_), sizeof(float), 1, out);
fwrite(reinterpret_cast<void*>(&minTemporalError_), sizeof(float), 1, out);
fwrite(reinterpret_cast<void*>(&maxTemporalError_), sizeof(float), 1, out);
fwrite(reinterpret_cast<void*>(&medianTemporalError_), sizeof(float), 1,out);
fwrite(reinterpret_cast<void*>(&data_[0]), data_.size()*sizeof(float),1,out);
fclose(out);
/*
INFO("\nData:");
for (unsigned i=0; i<data_.size()/NUM_DATA; ++i) {
INFO("Brick nr " << i);
INFO("Brick index " << data_[i*NUM_DATA + BRICK_INDEX]);
INFO("Child index " << data_[i*NUM_DATA + CHILD_INDEX]);
INFO("Spatial err " << *reinterpret_cast<float*>(&data_[i*NUM_DATA + SPATIAL_ERR]));
INFO("Temporal err " << *reinterpret_cast<float*>(&data_[i*NUM_DATA + TEMPORAL_ERR]));
}
*/
return true;
}
/*
bool TSP::Construct() {
std::fstream in;
in.open(inFilename_.c_str(), std::ios_base::in | std::ios_base::binary);
if (!in.is_open()) {
ERROR("TSP Construct failed to open " << inFilename_);
return false;
}
// Read header
size_t s = sizeof(unsigned int);
in.read(reinterpret_cast<char*>(&structure_), s);
in.read(reinterpret_cast<char*>(&dataDimensionality_), s);
in.read(reinterpret_cast<char*>(&brickDim_), s);
in.read(reinterpret_cast<char*>(&brickDim_), s);
in.read(reinterpret_cast<char*>(&brickDim_), s);
in.read(reinterpret_cast<char*>(&numBricksPerAxis_), s);
in.read(reinterpret_cast<char*>(&numBricksPerAxis_), s);
in.read(reinterpret_cast<char*>(&numBricksPerAxis_), s);
in.read(reinterpret_cast<char*>(&numTimesteps_), s);
in.read(reinterpret_cast<char*>(&paddingWidth_), s);
in.read(reinterpret_cast<char*>(&dataSize_), s);
numOTLevels_ = log(numBricksPerAxis_)/log(2) + 1;
numOTNodes_ = (pow(8, numOTLevels_) - 1) / 7;
numBSTNodes_ = numTimesteps_ * 2 - 1;
numTotalNodes_ = numOTNodes_ * numBSTNodes_;
INFO("numOTLevels_: " << numBSTLevels_);
INFO("numOctreeNodes_: " << numOTNodes_);
INFO("numTotalNodes_: " << numTotalNodes_);
paddedBrickDim_ = brickDim_ + 2*paddingWidth_;
//INFO("TSP construction, num total nodes: " << numTotalNodes_);
// Allocate space for TSP structure
data_.resize(numTotalNodes_*NUM_DATA);
// Loop over levels in octree skeleton
for (unsigned int level=0; level<numOTLevels_; ++level) {
//INFO("Visiting level " << level);
INFO("level " << level);
// First index of this level
// 0 for level 0
// 1 for level 1
// 9 for level 2
// etc
unsigned int firstLevelIndex = (pow(8, level) - 1) / 7;
// Position of first child for this level
// Equals number of nodes up to this point
unsigned int firstChildOfLevel = (pow(8, level+1) - 1) / 7;
// Offset between children
unsigned int childrenOffset = 8;
// For each level, loop over all octree nodes
unsigned int numNodesInLevel = pow(8, level);
for (int OTNode=0; OTNode<numNodesInLevel; ++OTNode) {
//INFO("Visiting node " << OTNode << " at level " << level);
unsigned int OTNodeIndex = firstLevelIndex + OTNode;
unsigned int OTChild;
if (level == numOTLevels_ - 1) { // If leaf
data_[numBSTNodes_*OTNodeIndex*NUM_DATA+CHILD_INDEX] = -1;
} else {
OTChild = firstChildOfLevel+OTNode*childrenOffset;
data_[numBSTNodes_*NUM_DATA*OTNodeIndex+CHILD_INDEX] =
numBSTNodes_*OTChild;
}
// For each octree node, loop over BST nodes
int BSTChild = 1;
for (unsigned int BSTNode=0; BSTNode<numBSTNodes_; ++BSTNode) {
//INFO("Visiting BST node " << BSTNode);
unsigned int BSTNodeIndex = numBSTNodes_*OTNodeIndex + BSTNode;
if (BSTNode != 0) { // If not root
if (BSTNode < (numTimesteps_-1)) { // If not leaf
int BSTChildIndex = numBSTNodes_*OTNodeIndex + BSTChild;
data_[NUM_DATA*BSTNodeIndex+CHILD_INDEX] = BSTChildIndex;
} else {
data_[NUM_DATA*BSTNodeIndex+CHILD_INDEX] = -1;
}
}
data_[NUM_DATA*BSTNodeIndex + BRICK_INDEX] = BSTNodeIndex;
data_[NUM_DATA*BSTNodeIndex + SPATIAL_ERR] = numOTLevels_-1-level;
// TODO test
int tempErr;
if (BSTNode == 0) {
tempErr = 5;
} else if (BSTNode < 3) {
tempErr = 4;
} else if (BSTNode < 7) {
tempErr = 3;
} else if (BSTNode < 15) {
tempErr = 2;
} else if (BSTNode < 31) {
tempErr = 1;
} else {
tempErr = 0;
}
data_[NUM_DATA*BSTNodeIndex + TEMPORAL_ERR] = tempErr;
BSTChild += 2;
}
}
}
in.close();
return true;
}
*/
-225
View File
@@ -1,225 +0,0 @@
/*
* Author: Victor Sand (victor.sand@gmail.com)
*
*/
#include <openspace/flare/TransferFunction.h>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <openspace/flare/Utils.h>
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>
#include <math.h>
using namespace osp;
TransferFunction * TransferFunction::New() {
return new TransferFunction();
}
TransferFunction::TransferFunction() :
floatData_(NULL),
texture_(nullptr),
width_(0),
lower_(0.f),
upper_(1.f),
generatedTexture_(false),
inFilename_("NotSet"),
interpolation_(TransferFunction::LINEAR) {}
TransferFunction::TransferFunction(const TransferFunction &_tf) {
if (floatData_) delete floatData_;
}
TransferFunction::~TransferFunction() {}
bool TransferFunction::ReadFile() {
std::ifstream in;
in.open(inFilename_.c_str());
if (!in.is_open()) {
ERROR("Could not open file " << inFilename_);
return false;
}
std::string line;
mappingKeys_.clear();
while (std::getline(in, line)) {
boost::char_separator<char> sep(" ");
boost::tokenizer<boost::char_separator<char> > tokens(line, sep);
boost::tokenizer<boost::char_separator<char> >::iterator it=tokens.begin();
float intensity;
unsigned int r, g, b, a;
if (*it == "width") {
width_ = boost::lexical_cast<unsigned int>(*(boost::next(it)));
} else if (*it == "lower") {
lower_ = boost::lexical_cast<float>(*(boost::next(it)));
} else if (*it == "upper") {
upper_ = boost::lexical_cast<float>(*(boost::next(it)));
} else if (*it == "mappingkey") {
intensity = boost::lexical_cast<float>(*(++it));
r = boost::lexical_cast<unsigned int>(*(++it));
g = boost::lexical_cast<unsigned int>(*(++it));
b = boost::lexical_cast<unsigned int>(*(++it));
a = boost::lexical_cast<unsigned int>(*(++it));
MappingKey mp(intensity, r, g, b, a);
mappingKeys_.insert(mp);
} else {
ERROR("Parsing error");
return false;
}
}
in.close();
return true;
}
void TransferFunction::SetInFilename(const std::string &_inFilename) {
inFilename_ = _inFilename;
}
std::string TransferFunction::ToString() const {
std::stringstream ss;
ss << "Width: " << width_ << "\n";
ss << "Range: [" << lower_ << " " << upper_ << "]\n";
ss << "Number of mapping keys: " << mappingKeys_.size();
for (std::set<MappingKey>::iterator it = mappingKeys_.begin();
it != mappingKeys_.end();
it++) {
ss << "\n" << *it;
}
return ss.str();
}
bool TransferFunction::Sample(float &_r, float &_g, float &_b, float &_a,
float _i) {
if (!floatData_) {
ERROR("TF Sample() - no float data");
return false;
}
if (_i < 0.f || _i > 1.f) {
//ERROR("Invalid TF sample intensity: " << _i);
//return false;
}
if (_i < 0.f) _i = 0.f;
if (_i > 1.0) _i = 1.f;
int i0 = static_cast<int>(floorf((width_-1)*_i));
int i1 = (i0 < width_-1) ? i0+1 : i0;
float di = _i - floor(_i);
float tfr0 = floatData_[i0*4+0];
float tfr1 = floatData_[i1*4+0];
float tfg0 = floatData_[i0*4+1];
float tfg1 = floatData_[i1*4+1];
float tfb0 = floatData_[i0*4+2];
float tfb1 = floatData_[i1*4+2];
float tfa0 = floatData_[i0*4+3];
float tfa1 = floatData_[i1*4+3];
_r = Lerp(tfr0, tfr1, di);
_g = Lerp(tfg0, tfg1, di);
_b = Lerp(tfb0, tfb1, di);
_a = Lerp(tfa0, tfa1, di);
return true;
}
bool TransferFunction::ConstructTexture() {
if (mappingKeys_.empty()) {
ERROR("No mapping keys");
return false;
}
if (interpolation_ == TransferFunction::LINEAR) {
// Float values for R, G, B and A channels
// TODO temp
if (floatData_ == NULL) {
floatData_ = new float[4*width_];
}
unsigned int lowerIndex = (unsigned int)floorf(lower_*(float)width_);
unsigned int upperIndex = (unsigned int)floorf(upper_*(float)width_);
// Loop over channels
for (unsigned int channel=0; channel<4; channel++) {
// Init some mapping keys
std::set<MappingKey>::iterator it = mappingKeys_.begin();
MappingKey prev(lower_, 0, 0, 0, 0);
MappingKey next = *it;
MappingKey last(upper_, 0, 0, 0, 0);
// First mapping key switch is a special case
bool first = true;
for (unsigned int i=0; i<width_; i++) {
if (i <= lowerIndex || i > upperIndex) {
floatData_[4*i + channel] = 0.f;
} else {
// See if it's time to go to next pair of mapping keys
float pos = (float)i/width_;
if (!first && pos > next.Intensity()) {
prev = next;
it++;
if (it == mappingKeys_.end()) {
next = last;
} else {
next = *it;
}
}
first = false;
// Interpolate linearly between prev and next mapping key
//DEBUG("i: " << i);
//DEBUG("pos: " << pos);
//DEBUG("prev.Intensity(): " << prev.Intensity());
float dist = pos-prev.Intensity();
//DEBUG("dist: " << dist);
float weight = dist/(next.Intensity()-prev.Intensity());
//DEBUG("weight: " << weight);
floatData_[4*i + channel] =
((float)prev.Channel(channel)*(1.f-weight)+
(float)next.Channel(channel)*weight)/255.f;
}
}
}
// Create and fill the texture
std::vector<unsigned int> dim(2);
dim[0] = width_;
dim[1] = 1;
texture_ = new ghoul::opengl::Texture(floatData_, glm::size3_t(width_,1,1),ghoul::opengl::Texture::Format::RGBA, GL_RGBA, GL_FLOAT);
texture_->uploadTexture();
//texture_ = Texture2D::New(dim);
//texture_->Init(&floatData_[0]);
generatedTexture_ = true;
//delete[] values;
} else {
ERROR("Invalid interpolation mode");
return false;
}
return true;
}
std::ostream & operator<<(std::ostream &os, const TransferFunction &_tf) {
os << _tf.ToString();
return os;
}
-39
View File
@@ -1,39 +0,0 @@
/*
* Author: Victor Sand (victor.sand@gmail.com)
*
*/
#include <ghoul/opengl/ghoul_gl.h>
#include <openspace/flare/Utils.h>
unsigned int osp::CheckGLError(std::string _location) {
unsigned int error = glGetError();
switch (error) {
case GL_NO_ERROR:
break;
case GL_INVALID_ENUM:
ERROR(_location.c_str() << " GL_INVALID_ENUM");
break;
case GL_INVALID_VALUE:
ERROR(_location.c_str() << " GL_INVALID_VALUE");
break;
case GL_INVALID_OPERATION:
ERROR(_location.c_str() << " GL_INVALID_OPERATION");
break;
case GL_STACK_OVERFLOW:
ERROR(_location.c_str() << " GL_STACK_OVERFLOW");
break;
case GL_STACK_UNDERFLOW:
ERROR(_location.c_str() << " GL_STACK_UNDERFLOW");
break;
case GL_OUT_OF_MEMORY:
ERROR(_location.c_str() << " GL_OUT_OF_MEMORY");
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
ERROR(_location.c_str() << " GL_INVALID_FRAMEBUFFER_OPERATION");
break;
case GL_TABLE_TOO_LARGE:
ERROR(_location.c_str() << " GL_TABLE_TOO_LARGE");
break;
}
return error;
}
-452
View File
@@ -1,452 +0,0 @@
// The source is still in here to be cannibalized later (ab)
//#include <openspace/flare/flare.h>
//
//#include <ghoul/opengl/texture.h>
//
//#include <openspace/flare/Renderer.h>
//#include <openspace/flare/TransferFunction.h>
//#include <openspace/flare/BrickManager.h>
//#include <openspace/flare/TSP.h>
//#include <openspace/flare/CLManager.h>
//#include <openspace/flare/Utils.h>
//
//#include <ghoul/filesystem/filesystem.h>
//
//#include <sgct.h>
//
//#include <string>
//#include <cstdlib>
//#include <vector>
//#include <iostream>
//
//namespace {
// std::string _loggerCat = "Flare";
//}
//
//namespace openspace {
//using namespace osp;
//
//Flare::Flare()
// : Renderable(ghoul::Dictionary())
// , _oldTime(0.f)
// , _currentTime(0.f)
// , _leftMouseButton(false)
// , _currentMouseX(0)
// , _currentMouseY(0)
// , _lastMouseX(0)
// , _lastMouseY(0)
//{
// setBoundingSphere(PowerScaledScalar::CreatePSS(sqrt(3.0f)));
//}
//
//Flare::~Flare() {
// // Clean up like a good citizen
// delete _config;
// delete _raycaster;
// delete _animator;
//}
//
//void exit_msg(std::string m) {
// LDEBUG(m);
// exit(1);
//}
//
//
//bool Flare::initialize() {
// init();
// return true;
//}
//bool Flare::deinitialize() {
// return true;
//}
//
//void Flare::render(const Camera *camera, const psc& thisPosition, RuntimeData* runtimeData) {
// render();
//}
//void Flare::update() {
//
//}
//
//void Flare::render() {
// // Sync timestep
// //unsigned int ts = static_cast<unsigned int>(_timeStep.getVal());
// //LDEBUG("ts: " << ts);
// // Reload config if flag is set
// if (_reloadFlag.getVal()) _raycaster->Reload();
//
// // Set model and view params
// _raycaster->SetModelParams(_pitch.getVal(),
// _yaw.getVal(),
// _roll.getVal());
// _raycaster->SetViewParams(_translateX.getVal(),
// _translateY.getVal(),
// _translateZ.getVal());
// // Render
// if (!_raycaster->Render(_elapsedTime.getVal())) {
// LDEBUG("!_raycaster->Render(_elapsedTime.getVal())");
// exit(1);
// }
//
// // Save screenshot
// if (_config->TakeScreenshot()) sgct::Engine::instance()->takeScreenshot();
//
// // Update animator with synchronized time
// _animator->SetPaused(_animationPaused.getVal());
// _animator->SetFPSMode(_fpsMode.getVal());
// _animator->Update(_elapsedTime.getVal());
// _animator->ManualTimestep(_manualTimestep.getVal());
//}
//
//void Flare::initNavigation() {
// _animationPaused.setVal(false);
// _reloadFlag.setVal(false);
//
// // FPS mode should be OFF for cluster syncing
// _fpsMode.setVal(true);
// _manualTimestep.setVal(0);
//
// // Read initial values from config
// _pitch.setVal(_config->StartPitch());
// _yaw.setVal(_config->StartYaw());
// _roll.setVal(_config->StartRoll());
//
// _translateX.setVal(_config->TranslateX());
// _translateY.setVal(_config->TranslateY());
// _translateZ.setVal(_config->TranslateZ());
//}
//
//void Flare::init() {
// // Start with reading a config file
// _config = Config::New(absPath("${CONFIG}/flareConfig.txt"));
// if (!_config) {
// LDEBUG("!_Config");
// exit(1);
// }
//
// initNavigation();
// _reloadFlag.setVal(false);
//
// // Get the viewport coordinates from OpenGL
// GLint currentViewPort[4];
// glGetIntegerv( GL_VIEWPORT, currentViewPort);
//
// // Make sure texture width/height and global kernel worksizes are
// // multiples of the local worksize
//
// // Window dimensions
// unsigned int width = currentViewPort[2] - currentViewPort[0];
// unsigned int height = currentViewPort[3] - currentViewPort[1];
// unsigned int xFactor = width/_config->LocalWorkSizeX();
// unsigned int yFactor = height/_config->LocalWorkSizeY();
// width = xFactor * _config->LocalWorkSizeX();
// height = yFactor * _config->LocalWorkSizeY();
// width /= _config->TextureDivisionFactor();
// height /= _config->TextureDivisionFactor();
//
//
// // Create TSP structure from file
// TSP *tsp = TSP::New(_config);
// if (!tsp->ReadHeader()) {
// LDEBUG("!tsp->ReadHeader()");
// exit(1);
// }
// // Read cache if it exists, calculate otherwise
// if (tsp->ReadCache()) {
// INFO("\nUsing cached TSP file");
// } else {
// INFO("\nNo cached TSP file found");
// if (!tsp->Construct()) {
// LDEBUG("!tsp->Construct()");
// exit(1);
// }
// if (_config->CalculateError() == 0) {
// INFO("Not calculating errors");
// } else {
// if (!tsp->CalculateSpatialError()) {
// LDEBUG("!tsp->CalculateSpatialError()");
// exit(1);
// }
// if (!tsp->CalculateTemporalError()) {
// LDEBUG("!tsp->CalculateTemporalError()");
// exit(1);
// }
// if (!tsp->WriteCache()) {
// LDEBUG("!tsp->WriteCache()");
// exit(1);
// }
// }
// }
//
// // Create brick manager and init (has to be done after init OpenGL!)
// BrickManager *brickManager= BrickManager::New(_config);
// if (!brickManager->ReadHeader()) {
// LDEBUG("!brickManager->ReadHeader()");
// exit(1);
// }
// if (!brickManager->InitAtlas()) {
// LDEBUG("!brickManager->InitAtlas()");
// exit(1);
// }
//
// using ghoul::opengl::ShaderObject;
// using ghoul::opengl::ProgramObject;
//
// ProgramObject* cubeShaderProgram = nullptr;
// ShaderObject* cubeShaderProgram_vs = new ShaderObject(ShaderObject::ShaderType::ShaderTypeVertex,
// _config->CubeShaderVertFilename(),
// "cubeShaderProgram_vs"
// );
// ShaderObject* cubeShaderProgram_fs = new ShaderObject(ShaderObject::ShaderType::ShaderTypeFragment,
// _config->CubeShaderFragFilename(),
// "cubeShaderProgram_fs"
// );
//
// cubeShaderProgram = new ProgramObject;
// cubeShaderProgram->attachObject(cubeShaderProgram_vs);
// cubeShaderProgram->attachObject(cubeShaderProgram_fs);
//
// if( ! cubeShaderProgram->compileShaderObjects())
// LDEBUG("Could not compile cubeShaderProgram");
// if( ! cubeShaderProgram->linkProgramObject())
// LDEBUG("Could not link cubeShaderProgram");
//
// ProgramObject* quadShaderProgram = nullptr;
// ShaderObject* quadShaderProgram_vs = new ShaderObject(ShaderObject::ShaderType::ShaderTypeVertex,
// _config->QuadShaderVertFilename(),
// "quadShaderProgram_vs"
// );
// ShaderObject* quadShaderProgram_fs = new ShaderObject(ShaderObject::ShaderType::ShaderTypeFragment,
// _config->QuadShaderFragFilename(),
// "quadShaderProgram_fs"
// );
//
// quadShaderProgram = new ProgramObject;
// quadShaderProgram->attachObject(quadShaderProgram_vs);
// quadShaderProgram->attachObject(quadShaderProgram_fs);
//
// if( ! quadShaderProgram->compileShaderObjects())
// LDEBUG("Could not compile quadShaderProgram");
// if( ! quadShaderProgram->linkProgramObject())
// LDEBUG("Could not link quadShaderProgram");
//
// // Create shaders for color cube and output textured quad
// /*
// ShaderProgram *cubeShaderProgram = ShaderProgram::New();
// cubeShaderProgram->CreateShader(ShaderProgram::VERTEX,
// _config->CubeShaderVertFilename());
// cubeShaderProgram->CreateShader(ShaderProgram::FRAGMENT,
// _config->CubeShaderFragFilename());
// cubeShaderProgram->CreateProgram();
//
// ShaderProgram *quadShaderProgram = ShaderProgram::New();
// quadShaderProgram->CreateShader(ShaderProgram::VERTEX,
// _config->QuadShaderVertFilename());
// quadShaderProgram->CreateShader(ShaderProgram::FRAGMENT,
// _config->QuadShaderFragFilename());
// quadShaderProgram->CreateProgram();
// */
//
// // Create two textures to hold the color cube
// std::vector<unsigned int> dimensions(2);
// dimensions[0] = width;
// dimensions[1] = height;
// ghoul::opengl::Texture* cubeFrontTex = new ghoul::opengl::Texture(glm::size3_t(width, height, 1),
// ghoul::opengl::Texture::Format::RGBA, GL_RGBA, GL_FLOAT);
// cubeFrontTex->uploadTexture();
// ghoul::opengl::Texture* cubeBackTex = new ghoul::opengl::Texture(glm::size3_t(width, height, 1),
// ghoul::opengl::Texture::Format::RGBA, GL_RGBA, GL_FLOAT);
// cubeBackTex->uploadTexture();
// /*
// Texture2D *cubeFrontTex = Texture2D::New(dimensions);
// Texture2D *cubeBackTex = Texture2D::New(dimensions);
// cubeFrontTex->Init();
// cubeBackTex->Init();
//*/
// // Create an output texture to write to
// ghoul::opengl::Texture* quadTex = new ghoul::opengl::Texture(glm::size3_t(width, height, 1),
// ghoul::opengl::Texture::Format::RGBA, GL_RGBA, GL_FLOAT);
// quadTex->uploadTexture();
//
// //Texture2D *quadTex = Texture2D::New(dimensions);
// //quadTex->Init();
//
// // Create transfer functions
// TransferFunction *transferFunction = TransferFunction::New();
// transferFunction->SetInFilename(_config->TFFilename());
// if (!transferFunction->ReadFile()) exit_msg("!transferFunction->ReadFile()");
// if (!transferFunction->ConstructTexture()) exit_msg("!transferFunction->ConstructTexture()");
//
//
// // Create animator
// _animator = Animator::New(_config);
// // Use original (not adjusted) number of timesteps for animator
// _animator->SetNumTimesteps(brickManager->NumOrigTimesteps());
//
// // Create CL manager
// CLManager *clManager = CLManager::New();
//
// // Set up the raycaster
// _raycaster = Raycaster::New(_config);
// _raycaster->SetWinWidth(width);
// _raycaster->SetWinHeight(height);
// if (!_raycaster->InitCube()) exit_msg("!_raycaster->InitCube()");
// if (!_raycaster->InitQuad()) exit_msg("!_raycaster->InitQuad()");
// _raycaster->SetBrickManager(brickManager);
// _raycaster->SetCubeFrontTexture(cubeFrontTex);
// _raycaster->SetCubeBackTexture(cubeBackTex);
// _raycaster->SetQuadTexture(quadTex);
// _raycaster->SetCubeShaderProgram(cubeShaderProgram);
// _raycaster->SetQuadShaderProgram(quadShaderProgram);
// if (!_raycaster->InitFramebuffers()) exit_msg("!_raycaster->InitFramebuffers()");
// _raycaster->SetAnimator(_animator);
// _raycaster->AddTransferFunction(transferFunction);
//
// // Tie CL manager to renderer
// _raycaster->SetCLManager(clManager);
// _raycaster->SetTSP(tsp);
//
// if (!_raycaster->InitCL()) exit_msg("!_raycaster->InitCL()");
// if (!_raycaster->InitPipeline()) exit_msg("!_raycaster->InitCL()");
//}
//
//void Flare::keyboard(int key, int action) {
// if (action == GLFW_PRESS) {
// switch(key) {
// case 32: // space bar
// // Toggle animation paused
// INFO("Pausing");
// _animationPaused.setVal(!_animationPaused.getVal());
// break;
// case 'Z':
// case 'z':
// // Decrease timestep
// // NOTE: Can't decrease timestep with double buffered approach atm
// //manualTimestep_.setVal(-1);
// break;
// case 'X':
// case 'x':
// // Increase timestep
// _manualTimestep.setVal(1);
// break;
// case 'D':
// case 'd':
// _translateX.setVal(_translateX.getVal() + _config->ZoomFactor());
// break;
// case 'A':
// case 'a':
// _translateX.setVal(_translateX.getVal() - _config->ZoomFactor());
// break;
// case 'W':
// case 'w':
// _translateY.setVal(_translateY.getVal() + _config->ZoomFactor());
// break;
// case 'S':
// case 's':
// _translateY.setVal(_translateY.getVal() - _config->ZoomFactor());
// break;
// case 'Q':
// case 'q':
// _translateZ.setVal(_translateZ.getVal() + _config->ZoomFactor());
// break;
// case 'E':
// case 'e':
// _translateZ.setVal(_translateZ.getVal() - _config->ZoomFactor());
// break;
// case 'R':
// case 'r':
// _reloadFlag.setVal(true);
// break;
// case 'F':
// case 'f':
// _fpsMode.setVal(!_fpsMode.getVal());
// if (_fpsMode.getVal()) {
// INFO("Updating animation ASAP");
// } else {
// INFO("Using refresh interval variable");
// }
// break;
// }
// }
//}
//
//void Flare::mouse(int button, int action) {
// switch (button) {
// case GLFW_MOUSE_BUTTON_LEFT:
// _leftMouseButton = (action == GLFW_PRESS) ? true : false;
// std::size_t winId = sgct::Engine::instance()->getActiveWindowPtr()->getId();
// sgct::Engine::getMousePos(winId, &_lastMouseX, &_lastMouseY);
// }
//}
//
//void Flare::preSync() {
// // Update time
// _oldTime = _currentTime;
// _currentTime = static_cast<float>(sgct::Engine::getTime());
// _elapsedTime.setVal(_currentTime - _oldTime);
// _timeStep.setVal(_animator->CurrentTimestep());
//
// // Update automatic model transform
// if (!_animationPaused.getVal()) {
// _pitch.setVal(_pitch.getVal() + _config->PitchSpeed());
// _roll.setVal(_roll.getVal() + _config->RollSpeed());
// _yaw.setVal(_yaw.getVal() + _config->YawSpeed());
// }
//
// // Update mouse
// if (_leftMouseButton) {
// std::size_t winId = sgct::Engine::instance()->getActiveWindowPtr()->getId();
// sgct::Engine::getMousePos(winId ,&_currentMouseX, &_currentMouseY);
// _pitch.setVal(_pitch.getVal() + _config->MousePitchFactor() *
// static_cast<float>(_currentMouseX-_lastMouseX));
// _roll.setVal(_roll.getVal() + _config->MouseRollFactor() *
// static_cast<float>(_currentMouseY-_lastMouseY));
// }
//}
//
//void Flare::postSyncPreDraw() {
// _animator->SetCurrentTimestep(static_cast<unsigned int>(_timeStep.getVal()));
//}
//
//void Flare::postDraw() {
// // Reset manual timestep
// _manualTimestep.setVal(0);
//
// // Reset reload flag
// _reloadFlag.setVal(false);
//}
//
//void Flare::encode() {
// sgct::SharedData::instance()->writeInt(&_timeStep);
// sgct::SharedData::instance()->writeBool(&_animationPaused);
// sgct::SharedData::instance()->writeBool(&_fpsMode);
// sgct::SharedData::instance()->writeFloat(&_elapsedTime);
// sgct::SharedData::instance()->writeInt(&_manualTimestep);
// sgct::SharedData::instance()->writeFloat(&_pitch);
// sgct::SharedData::instance()->writeFloat(&_yaw);
// sgct::SharedData::instance()->writeFloat(&_roll);
// sgct::SharedData::instance()->writeFloat(&_translateX);
// sgct::SharedData::instance()->writeFloat(&_translateY);
// sgct::SharedData::instance()->writeFloat(&_translateZ);
// sgct::SharedData::instance()->writeBool(&_reloadFlag);
//}
//
//void Flare::decode() {
// sgct::SharedData::instance()->readInt(&_timeStep);
// sgct::SharedData::instance()->readBool(&_animationPaused);
// sgct::SharedData::instance()->readBool(&_fpsMode);
// sgct::SharedData::instance()->readFloat(&_elapsedTime);
// sgct::SharedData::instance()->readInt(&_manualTimestep);
// sgct::SharedData::instance()->readFloat(&_pitch);
// sgct::SharedData::instance()->readFloat(&_yaw);
// sgct::SharedData::instance()->readFloat(&_roll);
// sgct::SharedData::instance()->readFloat(&_translateX);
// sgct::SharedData::instance()->readFloat(&_translateY);
// sgct::SharedData::instance()->readFloat(&_translateZ);
// sgct::SharedData::instance()->readBool(&_reloadFlag);
//}
//
//} // namespace openspace
//
//
-3
View File
@@ -39,7 +39,6 @@
#include <openspace/rendering/planets/renderableplanet.h>
#include <openspace/rendering/renderableplane.h>
#include <openspace/rendering/renderablevolumegl.h>
#include <openspace/flare/flare.h>
// positioninformation
#include <openspace/scenegraph/staticephemeris.h>
@@ -78,8 +77,6 @@ void FactoryManager::initialize()
"RenderableSphericalGrid");
_manager->factory<Renderable>()->registerClass<RenderableWavefrontObject>(
"RenderableWavefrontObject");
//_manager->factory<Renderable>()->registerClass<RenderableVolumeCL>(
// "RenderableVolumeCL");
_manager->factory<Renderable>()->registerClass<RenderablePlane>(
"RenderablePlane");
_manager->factory<Renderable>()->registerClass<RenderableVolumeGL>(