Merge branch 'master' of github.com:OpenSpace/OpenSpace into feature/PerformanceATM_and_Stereo

This commit is contained in:
Emil Axelsson
2018-03-20 13:45:15 +01:00
341 changed files with 26398 additions and 1624 deletions
+6 -1
View File
@@ -26,7 +26,12 @@ install_manifest.txt
.cproject
.project
shaders/ABuffer/constants.hglsl
ScriptLog.txt
*.idea/
.vs/
.build-vs/
*.dir
cmake-build-*
x64/
customization.lua
COMMIT.md
screenshots
+12
View File
@@ -79,6 +79,18 @@ execute_process(
OUTPUT_STRIP_TRAILING_WHITESPACE
)
# See if working directory is clean or not
execute_process(
COMMAND git diff-index --quiet HEAD --
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
RESULT_VARIABLE OPENSPACE_GIT_STATUS_RETURN
)
if (NOT OPENSPACE_GIT_STATUS_RETURN EQUAL 0)
set(OPENSPACE_GIT_STATUS "uncomitted changes")
else()
set(OPENSPACE_GIT_STATUS "")
endif()
option(OPENSPACE_WARNINGS_AS_ERRORS "Treat warnings as errors" OFF)
include(src/CMakeLists.txt)
+35 -4
View File
@@ -22,11 +22,10 @@
# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #
##########################################################################################
include(${GHOUL_BASE_DIR}/support/cmake/copy_shared_libraries.cmake)
include(${GHOUL_BASE_DIR}/support/cmake/copy_shared_libraries.cmake)
include(${OPENSPACE_CMAKE_EXT_DIR}/application_definition.cmake)
include(${OPENSPACE_CMAKE_EXT_DIR}/global_variables.cmake)
#####
# OpenVR
#####
@@ -34,9 +33,9 @@ option(OPENSPACE_OPENVR_SUPPORT "Build OpenSpace application with OpenVR support
if (OPENSPACE_OPENVR_SUPPORT)
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${OPENSPACE_EXT_DIR}/sgct/cmake/modules/")
find_package(OpenVR REQUIRED)
set(SGCT_OPENVR_DEFINITIONS OPENVR_SUPPORT)
if (NOT SGCT_OPENVR_INCLUDE_DIRECTORY)
@@ -111,6 +110,38 @@ target_compile_definitions(OpenSpace PRIVATE
${SPOUT_DEFINITIONS}
)
# Web Browser and Web gui
# Why not put these in the module's path? Because they do not have access to the
# target as of July 2017, which is needed.
if (OPENSPACE_MODULE_WEBBROWSER AND CEF_ROOT)
# wanted by CEF
set(CMAKE_BUILD_TYPE Debug CACHE INTERNAL "CMAKE_BUILD_TYPE")
if (WIN32)
set(RESOURCE_FILE ${OPENSPACE_APPS_DIR}/OpenSpace/openspace.rc)
endif ()
# Add the CEF binary distribution's cmake/ directory to the module path and
# find CEF to initialize it properly.
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${WEBBROWSER_MODULE_PATH}/cmake")
include(webbrowser_helpers)
set_cef_targets("${CEF_ROOT}" OpenSpace)
run_cef_platform_config("${CEF_ROOT}" "${CEF_TARGET}" "${WEBBROWSER_MODULE_PATH}")
elseif (OPENSPACE_MODULE_WEBBROWSER)
message(WARNING "Web configured to be included, but no CEF_ROOT was found, please try configuring CMake again.")
endif ()
if (OPENSPACE_MODULE_WEBGUI AND WEBGUI_MODULE_PATH)
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${WEBGUI_MODULE_PATH}/cmake")
include(webgui_helpers)
build_webgui_source(OpenSpace)
elseif(OPENSPACE_MODULE_WEBGUI)
message(WARNING "WebGui is configured to be included, but the web source could not be found. Try configuring CMake again.")
endif()
# End Web Browser and Web gui
if (MSVC)
# This library is used for being able to output the callstack if an exception escapes
target_link_libraries(OpenSpace Dbghelp.lib)
+1 -1
View File
@@ -106,7 +106,7 @@ LONG WINAPI generateMiniDump(EXCEPTION_POINTERS* exceptionPointers) {
LINFO(fmt::format("Creating dump file: {}", dumpFile));
HANDLE hDumpFile = CreateFile(
HANDLE hDumpFile = CreateFileA(
dumpFile.c_str(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_WRITE | FILE_SHARE_READ,
+45
View File
@@ -0,0 +1,45 @@
##########################################################################################
# #
# OpenSpace #
# #
# Copyright (c) 2014-2018 #
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy of this #
# software and associated documentation files (the "Software"), to deal in the Software #
# without restriction, including without limitation the rights to use, copy, modify, #
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to #
# permit persons to whom the Software is furnished to do so, subject to the following #
# conditions: #
# #
# The above copyright notice and this permission notice shall be included in all copies #
# or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, #
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A #
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT #
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF #
# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE #
# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #
##########################################################################################
include(${OPENSPACE_CMAKE_EXT_DIR}/application_definition.cmake)
set_source_files_properties(
${CMAKE_CURRENT_SOURCE_DIR}/openspace.icns
PROPERTIES MACOSX_PACKAGE_LOCATION "Resources"
)
set(MACOSX_BUNDLE_ICON_FILE openspace.icns)
create_new_application(
Wormhole
MACOSX_BUNDLE
${CMAKE_CURRENT_SOURCE_DIR}/main.cpp
${CMAKE_CURRENT_SOURCE_DIR}/openspace.rc
${CMAKE_CURRENT_SOURCE_DIR}/openspace.icns
)
target_link_libraries(
Wormhole
libOpenSpace
)
+1
View File
@@ -0,0 +1 @@
set(DEFAULT_APPLICATION ON)
+141
View File
@@ -0,0 +1,141 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2018 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <ghoul/opengl/ghoul_gl.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/filesystem/directory.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/logging/consolelog.h>
#include <ghoul/ghoul.h>
#include <ghoul/cmdparser/commandlineparser.h>
#include <ghoul/cmdparser/singlecommand.h>
#include <openspace/engine/wrapper/windowwrapper.h>
#include <openspace/scripting/scriptengine.h>
#include <openspace/rendering/renderable.h>
#include <openspace/network/parallelserver.h>
#include <iostream>
#include <string>
#include <ghoul/glm.h>
#include <functional>
#include <sstream>
#include <iomanip>
#include <ios>
namespace {
const std::string _loggerCat = "Wormhole";
}
int main(int argc, char** argv) {
using namespace openspace;
std::vector<std::string> arguments(argv, argv + argc);
ghoul::cmdparser::CommandlineParser commandlineParser(
"Wormhole",
ghoul::cmdparser::CommandlineParser::AllowUnknownCommands::Yes
);
std::stringstream defaultPassword;
defaultPassword << std::hex << std::setfill('0') << std::setw(6) <<
(std::hash<size_t>{}(
std::chrono::system_clock::now().time_since_epoch().count()
) % 0xffffff);
std::stringstream defaultChangeHostPassword;
defaultChangeHostPassword << std::hex << std::setfill('0') << std::setw(6) <<
(std::hash<size_t>{}(
std::chrono::system_clock::now().time_since_epoch().count() + 1
) % 0xffffff);
std::string portString = "";
commandlineParser.addCommand(
std::make_unique<ghoul::cmdparser::SingleCommand<std::string>>(
portString,
"--port",
"-p",
"Sets the port to listen on"
)
);
std::string password = "";
commandlineParser.addCommand(
std::make_unique<ghoul::cmdparser::SingleCommand<std::string>>(
password,
"--password",
"-l",
"Sets the password to use"
)
);
if (password == "") {
password = defaultPassword.str();
LINFO(fmt::format("Connection password: {}", password));
}
std::string changeHostPassword = "";
commandlineParser.addCommand(
std::make_unique<ghoul::cmdparser::SingleCommand<std::string>>(
password,
"--hostpassword",
"-h",
"Sets the host password to use"
)
);
if (changeHostPassword == "") {
changeHostPassword = defaultChangeHostPassword.str();
LINFO(fmt::format("Host password: {}", changeHostPassword));
}
commandlineParser.setCommandLine(arguments);
commandlineParser.execute();
int port = 25001;
if (portString != "") {
try {
port = std::stoi(portString);
}
catch (...) {
LERROR(fmt::format("Invalid port: {}", portString));
}
}
ParallelServer server;
server.start(port, password, changeHostPassword);
server.setDefaultHostAddress("127.0.0.1");
LINFO(fmt::format("Server listening to port {}", port));
while (std::cin.get() != 'q') {}
server.stop();
LINFO("Server stopped");
return 0;
};
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

+1
View File
@@ -0,0 +1 @@
IDI_ICON1 ICON DISCARDABLE "openspace.ico"
-1
View File
@@ -9,7 +9,6 @@ asset.require('scene/solarsystem/planets')
asset.require('scene/solarsystem/planets/mars/moons/phobos')
asset.require('scene/solarsystem/planets/mars/moons/deimos')
assetHelper.requestAll(asset, 'scene/digitaluniverse')
-- Load default key bindings applicable to most scenes
asset.require('util/default_keybindings')
+1 -3
View File
@@ -1,3 +1 @@
return {
"kameleonmetadatatojson"
}
return {}
@@ -86,6 +86,9 @@ public:
/// The key that stores the factory documentation values
static constexpr const char* KeyFactoryDocumentation = "FactoryDocumentation";
/// The key that decides whether or not we should require incoming web socket connections
/// to authorize or not
static constexpr const char* KeyRequireSocketAuthentication = "RequireSocketAuthentication";
/// The key that stores the location of the asset file that is initially loaded
static constexpr const char* KeyConfigAsset = "Asset";
@@ -200,7 +203,13 @@ public:
/// The part of the key storing whether the OpenGL state should be checked each call
static constexpr const char* KeyCheckOpenGLState = "CheckOpenGLState";
/// The part of the key storing whether each OpenGL call should be logged
/// The part of the key storing whether the OpenGL state should be checked each call
static constexpr const char* KeyServerPasskey = "ServerPasskey";
/// Whitelist of client addresses that won't need autorization
static constexpr const char* KeyServerClientAddressWhitelist =
"ClientAddressWhitelist";
static constexpr const char* KeyLogEachOpenGLCall = "LogEachOpenGLCall";
/// This key determines whether the scene graph nodes should initialized multithreaded
@@ -233,6 +242,8 @@ public:
/// The key used to specify whether screenshots should contain the current date
static constexpr const char* KeyScreenshotUseDate = "ScreenshotUseDate";
static constexpr const char* KeyWebHelperLocation = "WebHelperLocation";
static constexpr const char* KeyCefWebGuiUrl = "CefWebGuiUrl";
/**
* Iteratively walks the directory structure starting with \p filename to find the
+3 -3
View File
@@ -51,7 +51,7 @@ class LoadingScreen;
class LuaConsole;
class ModuleEngine;
class NetworkEngine;
class ParallelConnection;
class ParallelPeer;
class RenderEngine;
class Scene;
class SyncEngine;
@@ -128,7 +128,7 @@ public:
ModuleEngine& moduleEngine();
LoadingScreen& loadingScreen();
NetworkEngine& networkEngine();
ParallelConnection& parallelConnection();
ParallelPeer& parallelPeer();
RenderEngine& renderEngine();
TimeManager& timeManager();
WindowWrapper& windowWrapper();
@@ -212,7 +212,7 @@ private:
std::unique_ptr<LuaConsole> _console;
std::unique_ptr<ModuleEngine> _moduleEngine;
std::unique_ptr<NetworkEngine> _networkEngine;
std::unique_ptr<ParallelConnection> _parallelConnection;
std::unique_ptr<ParallelPeer> _parallelPeer;
std::unique_ptr<RenderEngine> _renderEngine;
std::unique_ptr<SyncEngine> _syncEngine;
std::unique_ptr<TimeManager> _timeManager;
@@ -26,7 +26,7 @@
#define __OPENSPACE_CORE___KEYFRAMENAVIGATOR___H__
#include <openspace/util/timeline.h>
#include <openspace/network/parallelconnection.h>
#include <openspace/network/parallelpeer.h>
#include <ghoul/glm.h>
#include <glm/gtx/quaternion.hpp>
@@ -25,6 +25,7 @@
#ifndef __OPENSPACE_CORE___LUACONSOLE___H__
#define __OPENSPACE_CORE___LUACONSOLE___H__
#include <openspace/network/parallelpeer.h>
#include <openspace/network/parallelconnection.h>
#include <openspace/properties/propertyowner.h>
#include <openspace/properties/scalar/boolproperty.h>
+19 -131
View File
@@ -26,39 +26,18 @@
#define __OPENSPACE_CORE___PARALLELCONNECTION___H__
#include <openspace/network/messagestructures.h>
#include <openspace/properties/propertyowner.h>
#include <openspace/properties/stringproperty.h>
#include <openspace/properties/numericalproperty.h>
#include <openspace/properties/scalar/floatproperty.h>
#include <glm/gtx/quaternion.hpp>
#include <ghoul/io/socket/tcpsocket.h>
#include <ghoul/designpattern/event.h>
#include <string>
#include <vector>
#include <deque>
#include <atomic>
#include <thread>
#include <mutex>
#include <map>
#include <condition_variable>
#if defined(WIN32) || defined(__MING32__) || defined(__MING64__)
typedef size_t _SOCKET;
#else
typedef int _SOCKET;
#include <netdb.h>
#endif
struct addrinfo;
namespace openspace {
class ParallelConnection : public properties::PropertyOwner {
public:
class ParallelConnection {
public:
enum class Status : uint32_t {
Disconnected = 0,
Connecting,
ClientWithoutHost,
ClientWithHost,
Host
@@ -70,7 +49,8 @@ class ParallelConnection : public properties::PropertyOwner {
ConnectionStatus,
HostshipRequest,
HostshipResignation,
NConnections
NConnections,
Disconnection
};
struct Message {
@@ -94,115 +74,23 @@ class ParallelConnection : public properties::PropertyOwner {
std::vector<char> content;
};
ParallelConnection();
~ParallelConnection();
void clientConnect();
void setPort(std::string port);
void setAddress(std::string address);
void setName(std::string name);
bool isHost();
const std::string& hostName();
void requestHostship();
void resignHostship();
void setPassword(std::string password);
void setHostPassword(std::string hostPassword);
void signalDisconnect();
void preSynchronization();
void sendScript(std::string script);
void resetTimeOffset();
double latencyStandardDeviation() const;
double timeTolerance() const;
class ConnectionLostError : public ghoul::RuntimeError {
public:
explicit ConnectionLostError();
};
/**
* Returns the Lua library that contains all Lua functions available to affect the
* remote OS parallel connection. The functions contained are
* -
* \return The Lua library that contains all Lua functions available to affect the
* interaction
*/
static scripting::LuaLibrary luaLibrary();
Status status();
int nConnections();
std::shared_ptr<ghoul::Event<>> connectionEvent();
ParallelConnection(std::unique_ptr<ghoul::io::TcpSocket> socket);
bool isConnectedOrConnecting();
void sendDataMessage(const ParallelConnection::DataMessage& dataMessage);
bool sendMessage(const ParallelConnection::Message& message);
void disconnect();
ghoul::io::TcpSocket* socket();
ParallelConnection::Message receiveMessage();
private:
//@TODO change this into the ghoul hasher for client AND server
uint32_t hash(const std::string &val);
void queueOutMessage(const Message& message);
void queueOutDataMessage(const DataMessage& dataMessage);
void queueInMessage(const Message& message);
void disconnect();
void closeSocket();
bool initNetworkAPI();
void establishConnection(addrinfo *info);
void sendAuthentication();
void listenCommunication();
int receiveData(_SOCKET & socket, std::vector<char> &buffer, int length, int flags);
void handleMessage(const Message&);
void dataMessageReceived(const std::vector<char>& messageContent);
void connectionStatusMessageReceived(const std::vector<char>& messageContent);
void nConnectionsMessageReceived(const std::vector<char>& messageContent);
void sendCameraKeyframe();
void sendTimeKeyframe();
void sendFunc();
void threadManagement();
void setStatus(Status status);
void setHostName(const std::string& hostName);
void setNConnections(size_t nConnections);
double calculateBufferedKeyframeTime(double originalTime);
properties::StringProperty _password;
properties::StringProperty _hostPassword;
properties::StringProperty _port;
properties::StringProperty _address;
properties::StringProperty _name;
properties::FloatProperty _bufferTime;
properties::FloatProperty _timeKeyframeInterval;
properties::FloatProperty _cameraKeyframeInterval;
properties::FloatProperty _timeTolerance;
double _lastTimeKeyframeTimestamp;
double _lastCameraKeyframeTimestamp;
_SOCKET _clientSocket;
std::atomic<bool> _isConnected;
std::atomic<bool> _isRunning;
std::atomic<bool> _tryConnect;
std::atomic<bool> _disconnect;
std::atomic<bool> _initializationTimejumpRequired;
std::atomic<size_t> _nConnections;
std::atomic<Status> _status;
std::string _hostName;
std::condition_variable _disconnectCondition;
std::mutex _disconnectMutex;
std::condition_variable _sendCondition;
std::deque<Message> _sendBuffer;
std::mutex _sendBufferMutex;
std::deque<Message> _receiveBuffer;
std::mutex _receiveBufferMutex;
std::atomic<bool> _timeJumped;
std::mutex _latencyMutex;
std::deque<double> _latencyDiffs;
double _initialTimeDiff;
std::unique_ptr<std::thread> _connectionThread;
std::unique_ptr<std::thread> _sendThread;
std::unique_ptr<std::thread> _listenThread;
std::unique_ptr<std::thread> _handlerThread;
std::shared_ptr<ghoul::Event<>> _connectionEvent;
std::unique_ptr<ghoul::io::TcpSocket> _socket;
};
} // namespace openspace
+136
View File
@@ -0,0 +1,136 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2018 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef __OPENSPACE_CORE___PARALLELPEER___H__
#define __OPENSPACE_CORE___PARALLELPEER___H__
#include <openspace/network/parallelconnection.h>
#include <openspace/network/messagestructures.h>
#include <openspace/properties/propertyowner.h>
#include <openspace/properties/stringproperty.h>
#include <openspace/properties/numericalproperty.h>
#include <openspace/properties/scalar/floatproperty.h>
#include <glm/gtx/quaternion.hpp>
#include <ghoul/designpattern/event.h>
#include <ghoul/io/socket/tcpsocket.h>
#include <string>
#include <vector>
#include <deque>
#include <atomic>
#include <thread>
#include <mutex>
#include <map>
#include <condition_variable>
namespace openspace {
class ParallelPeer : public properties::PropertyOwner {
public:
ParallelPeer();
~ParallelPeer();
void connect();
void setPort(std::string port);
void setAddress(std::string address);
void setName(std::string name);
bool isHost();
const std::string& hostName();
void requestHostship();
void resignHostship();
void setPassword(std::string password);
void setHostPassword(std::string hostPassword);
void disconnect();
void preSynchronization();
void sendScript(std::string script);
void resetTimeOffset();
double latencyStandardDeviation() const;
double timeTolerance() const;
/**
* Returns the Lua library that contains all Lua functions available to affect the
* remote OS parallel connection.
*/
static scripting::LuaLibrary luaLibrary();
ParallelConnection::Status status();
int nConnections();
std::shared_ptr<ghoul::Event<>> connectionEvent();
private:
void queueInMessage(const ParallelConnection::Message& message);
void sendAuthentication();
void handleCommunication();
void handleMessage(const ParallelConnection::Message&);
void dataMessageReceived(const std::vector<char>& messageContent);
void connectionStatusMessageReceived(const std::vector<char>& messageContent);
void nConnectionsMessageReceived(const std::vector<char>& messageContent);
void sendCameraKeyframe();
void sendTimeKeyframe();
void setStatus(ParallelConnection::Status status);
void setHostName(const std::string& hostName);
void setNConnections(size_t nConnections);
double calculateBufferedKeyframeTime(double originalTime);
properties::StringProperty _password;
properties::StringProperty _hostPassword;
properties::StringProperty _port;
properties::StringProperty _address;
properties::StringProperty _name;
properties::FloatProperty _bufferTime;
properties::FloatProperty _timeKeyframeInterval;
properties::FloatProperty _cameraKeyframeInterval;
properties::FloatProperty _timeTolerance;
double _lastTimeKeyframeTimestamp;
double _lastCameraKeyframeTimestamp;
std::atomic<bool> _shouldDisconnect;
std::atomic<size_t> _nConnections;
std::atomic<ParallelConnection::Status> _status;
std::string _hostName;
std::deque<ParallelConnection::Message> _receiveBuffer;
std::mutex _receiveBufferMutex;
std::atomic<bool> _timeJumped;
std::mutex _latencyMutex;
std::deque<double> _latencyDiffs;
double _initialTimeDiff;
std::unique_ptr<std::thread> _receiveThread;
std::shared_ptr<ghoul::Event<>> _connectionEvent;
ParallelConnection _connection;
};
} // namespace openspace
#endif // __OPENSPACE_CORE___PARALLELPEER___H__
+123
View File
@@ -0,0 +1,123 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2018 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef __OPENSPACE_CORE___PARALLELSERVER___H__
#define __OPENSPACE_CORE___PARALLELSERVER___H__
#include <openspace/network/parallelconnection.h>
#include <openspace/util/concurrentqueue.h>
#include <ghoul/io/socket/tcpsocketserver.h>
#include <ghoul/io/socket/tcpsocket.h>
#include <string>
#include <unordered_map>
#include <atomic>
namespace openspace {
class ParallelServer {
public:
void start(int port,
const std::string& password,
const std::string& changeHostPassword);
void setDefaultHostAddress(std::string);
std::string defaultHostAddress() const;
void stop();
size_t nConnections() const;
private:
struct Peer {
size_t id;
std::string name;
ParallelConnection parallelConnection;
ParallelConnection::Status status;
std::thread thread;
};
struct PeerMessage {
size_t peerId;
ParallelConnection::Message message;
};
bool isConnected(std::shared_ptr<Peer> peer) const;
void sendMessage(std::shared_ptr<Peer> peer,
ParallelConnection::MessageType messageType,
const std::vector<char>& message);
void sendMessageToAll(ParallelConnection::MessageType messageType,
const std::vector<char>& message);
void sendMessageToClients(ParallelConnection::MessageType messageType,
const std::vector<char>& message);
void disconnect(std::shared_ptr<Peer> peer);
void setName(std::shared_ptr<Peer> peer, std::string name);
void assignHost(std::shared_ptr<Peer> peer);
void setToClient(std::shared_ptr<Peer> peer);
void setNConnections(size_t nConnections);
void sendConnectionStatus(std::shared_ptr<Peer> peer);
void handleAuthentication(std::shared_ptr<Peer> peer, std::vector<char> data);
void handleData(std::shared_ptr<Peer> peer, std::vector<char> data);
void handleHostshipRequest(std::shared_ptr<Peer> peer, std::vector<char> data);
void handleHostshipResignation(std::shared_ptr<Peer> peer, std::vector<char> data);
void handleDisconnection(std::shared_ptr<Peer> peer);
void handleNewPeers();
void eventLoop();
std::shared_ptr<Peer> peer(size_t i);
void handlePeer(size_t id);
void handlePeerMessage(PeerMessage peerMessage);
std::unordered_map<size_t, std::shared_ptr<Peer>> _peers;
mutable std::mutex _peerListMutex;
std::thread _serverThread;
std::thread _eventLoopThread;
ghoul::io::TcpSocketServer _socketServer;
size_t _passwordHash;
size_t _changeHostPasswordHash;
size_t _nextConnectionId = 1;
std::atomic_bool _shouldStop = false;
std::atomic_size_t _nConnections = 0;
std::atomic_size_t _hostPeerId = 0;
mutable std::mutex _hostInfoMutex;
std::string _hostName;
std::string _defaultHostAddress;
ConcurrentQueue<PeerMessage> _incomingMessages;
};
} // namespace openspace
#endif // __OPENSPACE_CORE___PARALLELSERVER___H__
@@ -0,0 +1,37 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef __OPENSPACE_CORE___BINARYPROPERTY___H__
#define __OPENSPACE_CORE___BINARYPROPERTY___H__
#include <openspace/properties/templateproperty.h>
#include <vector>
namespace openspace::properties {
REGISTER_TEMPLATEPROPERTY_HEADER(BinaryProperty, std::vector<char>)
} // namespace openspace::properties
#endif // __OPENSPACE_CORE___BINARYPROPERTY___H__
@@ -62,6 +62,8 @@ public:
virtual std::string className() const override;
std::string jsonValue() const override;
using TemplateProperty<T>::operator=;
@@ -79,7 +81,14 @@ protected:
static const std::string SteppingValueKey;
static const std::string ExponentValueKey;
std::string generateAdditionalDescription() const override;
std::string generateAdditionalJsonDescription() const override;
/**
* convert a lua formatted value to a JSON formatted value
* @param luaValue
* @return a json formatted string representation of the given lua value
*/
std::string luaToJson(std::string luaValue) const;
T _minimumValue;
T _maximumValue;
@@ -386,15 +386,34 @@ void NumericalProperty<T>::setExponent(float exponent) {
}
template <typename T>
std::string NumericalProperty<T>::generateAdditionalDescription() const {
std::string result;
result += MinimumValueKey + " = " + std::to_string(_minimumValue) + ",";
result += MaximumValueKey + " = " + std::to_string(_maximumValue) + ",";
result += SteppingValueKey + " = " + std::to_string(_stepping) + ",";
result += ExponentValueKey + " = " + std::to_string(_exponent);
std::string NumericalProperty<T>::generateAdditionalJsonDescription() const {
std::string result = "{ ";
result += "\"" + MinimumValueKey + "\": " + luaToJson(std::to_string(_minimumValue)) + ",";
result += "\"" + MaximumValueKey + "\": " + luaToJson(std::to_string(_maximumValue)) + ",";
result += "\"" + SteppingValueKey + "\": " + luaToJson(std::to_string(_stepping)) + ",";
result += "\"" + ExponentValueKey + "\": " + luaToJson(std::to_string(_exponent));
result += " }";
return result;
}
template <typename T>
std::string NumericalProperty<T>::luaToJson(std::string luaValue) const {
if(luaValue[0] == '{') {
luaValue.replace(0, 1, "[");
}
if (luaValue[luaValue.size() - 1] == '}') {
luaValue.replace(luaValue.size() - 1, 1, "]");
}
return luaValue;
}
template <typename T>
std::string NumericalProperty<T>::jsonValue() const {
std::string value;
getStringValue(value);
return luaToJson(value);
}
template <typename T>
void NumericalProperty<T>::setInterpolationTarget(ghoul::any value) {
try {
@@ -143,7 +143,7 @@ public:
private:
static const std::string OptionsKey;
std::string generateAdditionalDescription() const override;
std::string generateAdditionalJsonDescription() const override;
/// The list of options which have been registered with this OptionProperty
std::vector<Option> _options;
+64 -13
View File
@@ -93,6 +93,10 @@ public:
/// onChange callback
using OnChangeHandle = uint32_t;
/// An OnChangeHandle is returned by the onChange method to uniquely identify an
/// onDelete callback
using OnDeleteHandle = uint32_t;
/// This OnChangeHandle can be used to remove all onChange callbacks from this
/// Property
static OnChangeHandle OnChangeHandleAll;
@@ -114,7 +118,7 @@ public:
* The destructor taking care of deallocating all unused memory. This method will not
* remove the Property from the PropertyOwner.
*/
virtual ~Property() = default;
virtual ~Property();
/**
* This method returns the class name of the Property. The method is used by the
@@ -198,6 +202,14 @@ public:
*/
virtual bool getStringValue(std::string& value) const;
/**
* This method encodes the encapsulated value of this Property as a
* <code>std::string</code>.
* \return the string value
* \throws an exception if value couldn't be fetched
*/
std::string getStringValue() const;
/**
* This method sets the value encapsulated by this Property by deserializing the
* passed <code>std::string</code>. The specific details of the deserialization are up
@@ -222,6 +234,14 @@ public:
*/
OnChangeHandle onChange(std::function<void()> callback);
/**
* This method registers a <code>callback</code> function that will be called when
* the property is destructed.
* \pre The callback must not be empty
* \return An OnDeleteHandle that can be used in subsequent calls to remove a callback
*/
OnDeleteHandle onDelete(std::function<void()> callback);
/**
* This method deregisters a callback that was previously registered with the onChange
* method. If OnChangeHandleAll is passed to this function, all registered callbacks
@@ -233,6 +253,16 @@ public:
*/
void removeOnChange(OnChangeHandle handle);
/**
* This method deregisters a callback that was previously registered with the onDelete
* method.
* \param handle An OnDeleteHandle that was returned from a previous call to onDelete
* by this property.
* \pre handle must refer to a callback that has been previously registred
* \pre handle must refer to a callback that has not been removed previously
*/
void removeOnDelete(OnDeleteHandle handle);
/**
* This method returns the unique identifier of this Property.
* \return The unique identifier of this Property
@@ -365,6 +395,18 @@ public:
*/
const ghoul::Dictionary& metaData() const;
/**
* Convert the Property into a string containing a JSON representation of the Property.
* Includes description of the object.
* @return the JSON string
*/
virtual std::string toJson() const;
/**
* Get a valid JSON formatted representation of the Property's value.
* @return the value in a json compatible format
*/
virtual std::string jsonValue() const;
/// Interpolation methods
virtual void setInterpolationTarget(ghoul::any value);
@@ -374,12 +416,6 @@ public:
virtual void interpolateValue(float t,
ghoul::EasingFunc<float> easingFunction = nullptr);
protected:
static const char* IdentifierKey;
static const char* NameKey;
static const char* TypeKey;
static const char* MetaDataKey;
/**
* Creates the information that is general to every Property and adds the
* <code>Identifier</code>, <code>Name</code>, <code>Type</code>, and
@@ -388,16 +424,16 @@ protected:
* class wants to add meta data that is not curated by the Property class
* \return The base description common to all Property classes
*/
std::string generateBaseDescription() const;
std::string generateBaseJsonDescription() const;
/**
* Creates the information for the <code>MetaData</code> key-part of the Lua
* Creates the information for the <code>MetaData</code> key-part of the json
* description for the Property. The result can be included as one key-value pair in
* the description text generated by subclasses. Only the metadata curated by the
* Property class is used in this method.
* \return The metadata information text for the property
*/
virtual std::string generateMetaDataDescription() const;
virtual std::string generateMetaDataJsonDescription() const;
/**
* Creates the information that is specific to each subclass of Property%s. If a
@@ -410,13 +446,23 @@ protected:
* and this method being the override points to customize the behavior.
* \return The information specific to each subclass of Property
*/
virtual std::string generateAdditionalDescription() const;
virtual std::string generateAdditionalJsonDescription() const;
protected:
static const char* IdentifierKey;
static const char* NameKey;
static const char* TypeKey;
static const char* DescriptionKey;
static const char* JsonValueKey;
static const char* MetaDataKey;
static const char* AdditionalDataKey;
/**
* This method must be called by all subclasses whenever the encapsulated value has
* changed and a potential listener has to be informed.
* changed and potential listeners need to be informed.
*/
void notifyListener();
void notifyChangeListeners();
/// The PropetyOwner this Property belongs to, or <code>nullptr</code>
PropertyOwner* _owner;
@@ -436,7 +482,12 @@ protected:
/// The callback function sthat will be invoked whenever the value changes
std::vector<std::pair<OnChangeHandle, std::function<void()>>> _onChangeCallbacks;
/// The callback function sthat will be invoked whenever the value changes
std::vector<std::pair<OnDeleteHandle, std::function<void()>>> _onDeleteCallbacks;
private:
void notifyDeleteListeners();
OnChangeHandle _currentHandleValue;
#ifdef _DEBUG
@@ -51,7 +51,7 @@ public:
private:
static const std::string OptionsKey;
std::string generateAdditionalDescription() const override;
std::string generateAdditionalJsonDescription() const override;
/// The list of options which have been registered with this OptionProperty
std::vector<Option> _options;
@@ -178,7 +178,7 @@ template <typename T>
void openspace::properties::TemplateProperty<T>::setValue(T val) {
if (val != _value) {
_value = std::move(val);
notifyListener();
notifyChangeListeners();
}
}
@@ -199,7 +199,7 @@ void TemplateProperty<T>::set(ghoul::any value) {
T v = ghoul::any_cast<T>(std::move(value));
if (v != _value) {
_value = std::move(v);
notifyListener();
notifyChangeListeners();
}
}
catch (ghoul::bad_any_cast&) {
@@ -65,6 +65,10 @@ public:
* \param value The ignored value
*/
void set(ghoul::any value) override;
std::string toJson() const override;
std::string jsonValue() const override;
};
} // namespace openspace::properties
@@ -47,14 +47,17 @@ public:
glm::vec4 sample(size_t t);
size_t width();
void setCallback(TfChangedCallback callback);
void setTextureFromTxt(std::shared_ptr<ghoul::opengl::Texture> ptr);
private:
void setTextureFromTxt();
void setTextureFromTxt() {
setTextureFromTxt(_texture);
}
void setTextureFromImage();
void uploadTexture();
std::string _filepath;
std::unique_ptr<ghoul::filesystem::File> _file = nullptr;
std::unique_ptr<ghoul::opengl::Texture> _texture = nullptr;
std::shared_ptr<ghoul::opengl::Texture> _texture = nullptr;
bool _needsUpdate = false;
TfChangedCallback _tfChangedCallback;
};
+1
View File
@@ -70,6 +70,7 @@ public:
Histogram equalize();
float equalize (float);
float entropy();
std::vector<char> getBinaryData() const;
float highestBinValue(bool equalized, int overBins=0);
float binWidth();
+15
View File
@@ -25,8 +25,10 @@
#ifndef __OPENSPACE_CORE___TIMEMANAGER___H__
#define __OPENSPACE_CORE___TIMEMANAGER___H__
#include <utility>
#include <vector>
#include <deque>
#include <functional>
#include <openspace/util/timeline.h>
#include <openspace/util/time.h>
#include <openspace/util/syncdata.h>
@@ -35,6 +37,9 @@ namespace openspace {
class TimeManager {
public:
using CallbackHandle = int;
using TimeChangeCallback = std::function<void()>;
Time& time();
std::vector<Syncable*> getSyncables();
void preSynchronization(double dt);
@@ -45,6 +50,10 @@ public:
void setTimeNextFrame(Time t);
size_t nKeyframes() const;
CallbackHandle addTimeChangeCallback(TimeChangeCallback cb);
CallbackHandle addDeltaTimeChangeCallback(TimeChangeCallback cb);
void removeTimeChangeCallback(CallbackHandle handle);
void removeDeltaTimeChangeCallback(CallbackHandle handle);
private:
bool _shouldSetTime = false;
Time _timeNextFrame;
@@ -52,6 +61,12 @@ private:
SyncData<Time> _currentTime;
void consumeKeyframes(double dt);
double _latestConsumedTimestamp;
int _nextCallbackHandle = 0;
std::vector<std::pair<CallbackHandle, TimeChangeCallback>> _timeChangeCallbacks;
std::vector<std::pair<CallbackHandle, TimeChangeCallback>> _deltaTimeChangeCallbacks;
double _lastTime = 0;
double _lastDeltaTime = 0;
};
} // namespace openspace
@@ -118,9 +118,9 @@ DashboardItemParallelConnection::DashboardItemParallelConnection(
}
void DashboardItemParallelConnection::render(glm::vec2& penPosition) {
ParallelConnection::Status status = OsEng.parallelConnection().status();
size_t nConnections = OsEng.parallelConnection().nConnections();
const std::string& hostName = OsEng.parallelConnection().hostName();
ParallelConnection::Status status = OsEng.parallelPeer().status();
size_t nConnections = OsEng.parallelPeer().nConnections();
const std::string& hostName = OsEng.parallelPeer().hostName();
std::string connectionInfo = "";
int nClients = static_cast<int>(nConnections);
@@ -169,9 +169,9 @@ void DashboardItemParallelConnection::render(glm::vec2& penPosition) {
}
glm::vec2 DashboardItemParallelConnection::size() const {
ParallelConnection::Status status = OsEng.parallelConnection().status();
size_t nConnections = OsEng.parallelConnection().nConnections();
const std::string& hostName = OsEng.parallelConnection().hostName();
ParallelConnection::Status status = OsEng.parallelPeer().status();
size_t nConnections = OsEng.parallelPeer().nConnections();
const std::string& hostName = OsEng.parallelPeer().hostName();
std::string connectionInfo = "";
int nClients = static_cast<int>(nConnections);
+47
View File
@@ -0,0 +1,47 @@
##########################################################################################
# #
# OpenSpace #
# #
# Copyright (c) 2014-2017 #
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy of this #
# software and associated documentation files (the "Software"), to deal in the Software #
# without restriction, including without limitation the rights to use, copy, modify, #
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to #
# permit persons to whom the Software is furnished to do so, subject to the following #
# conditions: #
# #
# The above copyright notice and this permission notice shall be included in all copies #
# or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, #
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A #
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT #
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF #
# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE #
# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #
##########################################################################################
include(${OPENSPACE_CMAKE_EXT_DIR}/module_definition.cmake)
set(CEFWEBGUI_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR} CACHE INTERNAL "CEFWEBGUI_MODULE_PATH")
set(CEFWEBGUI_SOURCE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/web CACHE INTERNAL "CEFWEBGUI_MODULE_PATH")
set(OPENSPACE_HEADER_FILES
cefwebguimodule.h
include/guirenderhandler.h
)
source_group("Header Files" FILES ${OPENSPACE_HEADER_FILES})
set(OPENSPACE_SOURCE_FILES
cefwebguimodule.cpp
src/guirenderhandler.cpp
)
source_group("Source Files" FILES ${OPENSPACE_SOURCE_FILES})
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
create_new_module(
CefWebGui
cefwebgui_module
${OPENSPACE_HEADER_FILES} ${OPENSPACE_SOURCE_FILES}
)
+80
View File
@@ -0,0 +1,80 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/webbrowser/webbrowsermodule.h>
#include "cefwebguimodule.h"
namespace {
const std::string _loggerCat = "CefWebGui";
}
namespace openspace {
CefWebGuiModule::CefWebGuiModule()
: OpenSpaceModule(CefWebGuiModule::Name)
{}
void CefWebGuiModule::internalInitialize(const ghoul::Dictionary&) {
_guiInstance = std::make_shared<BrowserInstance>(new GUIRenderHandler());
_guiLocation = OsEng.configurationManager().value<std::string>(
ConfigurationManager::KeyCefWebGuiUrl);
OsEng.registerModuleCallback(
OpenSpaceEngine::CallbackOption::Initialize,
[this]() {
LDEBUGC("WebBrowser", fmt::format("Loading GUI from {}", _guiLocation));
_guiInstance->loadUrl(_guiLocation);
auto webBrowserModule = OsEng.moduleEngine().module<WebBrowserModule>();
if (webBrowserModule != nullptr) {
webBrowserModule->attachEventHandler(_guiInstance);
webBrowserModule->addBrowser(_guiInstance);
}
}
);
OsEng.registerModuleCallback(
OpenSpaceEngine::CallbackOption::Render,
[this](){
WindowWrapper& wrapper = OsEng.windowWrapper();
if (wrapper.isMaster()) {
if (wrapper.windowHasResized()) {
_guiInstance->reshape(wrapper.currentWindowSize());
}
_guiInstance->draw();
}
});
OsEng.registerModuleCallback(
OpenSpaceEngine::CallbackOption::Deinitialize,
[this](){
_guiInstance->close(true);
auto webBrowserModule = OsEng.moduleEngine().module<WebBrowserModule>();
if (webBrowserModule != nullptr) {
webBrowserModule->removeBrowser(_guiInstance);
}
_guiInstance.reset();
});
}
}
+48
View File
@@ -0,0 +1,48 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef OPENSPACE_CEFWEBGUIMODULE_H
#define OPENSPACE_CEFWEBGUIMODULE_H
#include <openspace/util/openspacemodule.h>
#include <include/openspace/engine/configurationmanager.h>
#include "modules/webbrowser/include/browserinstance.h"
#include "modules/cefwebgui/include/guirenderhandler.h"
namespace openspace {
class CefWebGuiModule : public OpenSpaceModule {
public:
static constexpr const char* Name = "CefWebGui";
CefWebGuiModule();
void internalInitialize(const ghoul::Dictionary& configuration) override;
private:
std::shared_ptr<BrowserInstance> _guiInstance;
std::string _guiLocation;
};
}
#endif //OPENSPACE_WEBGUIMODULE_H
+7
View File
@@ -0,0 +1,7 @@
set(DEFAULT_MODULE OFF)
set(OPEMSPACE_DEPENCENCIES
webbrowser
webgui
server
)
@@ -0,0 +1,54 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef __OPENSPACE_MODULE_WEBBROWSER___GUI_RENDER_HANDLER___H__
#define __OPENSPACE_MODULE_WEBBROWSER___GUI_RENDER_HANDLER___H__
#include <memory>
#include <include/openspace/engine/openspaceengine.h>
#include <include/openspace/rendering/renderengine.h>
#include <include/openspace/engine/wrapper/windowwrapper.h>
#include <ghoul/opengl/ghoul_gl.h>
#include <fmt/format.h>
#include <include/cef_app.h>
#include "modules/webbrowser/include/webrenderhandler.h"
namespace openspace {
class GUIRenderHandler : public WebRenderHandler {
public:
GUIRenderHandler();
void initializeGL();
void draw(void);
void render() {};
private:
std::unique_ptr<ghoul::opengl::ProgramObject> _programObject;
GLuint _program, _vao, _vbo;
};
} // namespace openspace
#endif // __OPENSPACE_MODULE_WEBBROWSER___GUI_RENDER_HANDLER___H__
+35
View File
@@ -0,0 +1,35 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#version __CONTEXT__
in vec2 Texcoord;
out vec4 outputColor;
uniform sampler2D tex;
void main() {
outputColor = texture2D(tex, Texcoord);
}
+38
View File
@@ -0,0 +1,38 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#version __CONTEXT__
layout(location = 0) in vec2 position;
uniform mat4 ortho;
out vec2 Texcoord;
void main() {
Texcoord = (vec2(position.x + 1.0f, position.y - 1.0f) * 0.5);
Texcoord.y *= -1.0f;
gl_Position = vec4(position, 0.0, 1.0);
}
@@ -0,0 +1,95 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <glm/gtc/matrix_transform.hpp>
#include <ghoul/filesystem/filesystem.h>
#include "modules/cefwebgui/include/guirenderhandler.h"
namespace {
std::string _loggerCat = "WebGUI:RenderHandler";
}
namespace openspace {
GUIRenderHandler::GUIRenderHandler() {
OsEng.registerModuleCallback(
OpenSpaceEngine::CallbackOption::InitializeGL,
[this](){
LDEBUG("Initializing WebGUI RenderHandler OpenGL");
initializeGL();
}
);
}
void GUIRenderHandler::initializeGL() {
LDEBUG("Initializing CEF GL environment...");
_programObject = ghoul::opengl::ProgramObject::Build(
"WebGUICEFProgram",
absPath("${MODULE_CEFWEBGUI}/shaders/gui_vs.glsl"),
absPath("${MODULE_CEFWEBGUI}/shaders/gui_fs.glsl")
);
float data[] = {-1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, 1.0f, 1.0f};
glGenVertexArrays(1, &_vao);
glBindVertexArray(_vao);
glGenBuffers(1, &_vbo);
glGenTextures(1, &_texture);
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), 0);
glBindVertexArray(0);
LDEBUG("Initializing CEF GL environment... done!");
}
void GUIRenderHandler::draw(void) {
if (_programObject->isDirty()) {
_programObject->rebuildFromFile();
}
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
_programObject->activate();
ghoul::opengl::TextureUnit unit;
unit.activate();
glBindTexture(GL_TEXTURE_2D, _texture);
_programObject->setUniform("tex", unit);
glBindVertexArray(_vao);
glDrawArrays(GL_TRIANGLES, 0, 6);
glBindVertexArray(0);
_programObject->deactivate();
glEnable(GL_CULL_FACE);
}
} // namespace openspace
+1 -1
View File
@@ -69,7 +69,7 @@ ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) {
&(OsEng.windowWrapper()),
&(OsEng.navigationHandler()),
&(OsEng.renderEngine()),
&(OsEng.parallelConnection()),
&(OsEng.parallelPeer()),
&(OsEng.console()),
&(OsEng.dashboard())
};
@@ -38,6 +38,7 @@ public:
void render() override;
private:
void renderDisconnected();
void renderConnecting();
void renderClientWithHost();
void renderClientWithoutHost();
void renderClientCommon();
+3 -1
View File
@@ -219,7 +219,6 @@ static void RenderDrawLists(ImDrawData* drawData) {
glDisable(GL_SCISSOR_TEST);
}
void addScreenSpaceRenderableLocal(std::string texturePath) {
if (!FileSys.fileExists(absPath(texturePath))) {
LWARNING(fmt::format("Could not find image '{}'", texturePath));
@@ -930,6 +929,7 @@ void GUI::render() {
addImageBufferSize,
ImGuiInputTextFlags_EnterReturnsTrue
);
if (addImageOnline) {
addScreenSpaceRenderableOnline(std::string(addImageOnlineBuffer));
}
@@ -952,6 +952,7 @@ void GUI::render() {
);
}
#ifdef SHOW_IMGUI_HELPERS
ImGui::Checkbox("ImGUI Internals", &_showInternals);
if (_showInternals) {
ImGui::Begin("Style Editor");
@@ -966,6 +967,7 @@ void GUI::render() {
ImGui::ShowMetricsWindow();
ImGui::End();
}
#endif
ImGui::End();
}
+22 -9
View File
@@ -29,7 +29,7 @@
#include <openspace/engine/openspaceengine.h>
#include <openspace/util/timemanager.h>
#include <openspace/interaction/navigationhandler.h>
#include <openspace/network/parallelconnection.h>
#include <openspace/network/parallelpeer.h>
#include <openspace/network/messagestructures.h>
#include <ghoul/fmt.h>
@@ -51,12 +51,22 @@ void GuiParallelComponent::renderDisconnected() {
const bool connect = ImGui::Button("Connect");
if (connect) {
OsEng.parallelConnection().clientConnect();
OsEng.parallelPeer().connect();
}
}
void GuiParallelComponent::renderConnecting() {
ImGui::Text("Connecting...");
const bool cancel = ImGui::Button("Cancel connection");
if (cancel) {
OsEng.parallelPeer().disconnect();
}
}
void GuiParallelComponent::renderClientWithHost() {
ParallelConnection& parallel = OsEng.parallelConnection();
ParallelPeer& parallel = OsEng.parallelPeer();
std::string connectionInfo = "Session hosted by \"" + parallel.hostName() + "\"\n";
size_t nConnections = parallel.nConnections();
@@ -98,7 +108,7 @@ void GuiParallelComponent::renderClientWithHost() {
}
void GuiParallelComponent::renderClientWithoutHost() {
ParallelConnection& parallel = OsEng.parallelConnection();
ParallelPeer& parallel = OsEng.parallelPeer();
std::string connectionInfo = "Connected to parallel session with no host\n";
size_t nConnections = parallel.nConnections();
@@ -122,7 +132,7 @@ void GuiParallelComponent::renderClientWithoutHost() {
}
void GuiParallelComponent::renderClientCommon() {
ParallelConnection& parallel = OsEng.parallelConnection();
ParallelPeer& parallel = OsEng.parallelPeer();
bool requestHostship = ImGui::Button("Request hostship");
const bool disconnect = ImGui::Button("Disconnect");
@@ -132,12 +142,12 @@ void GuiParallelComponent::renderClientCommon() {
}
if (disconnect) {
parallel.signalDisconnect();
parallel.disconnect();
}
}
void GuiParallelComponent::renderHost() {
ParallelConnection& parallel = OsEng.parallelConnection();
ParallelPeer& parallel = OsEng.parallelPeer();
size_t nConnections = parallel.nConnections();
std::string connectionInfo = "";
@@ -165,12 +175,15 @@ void GuiParallelComponent::render() {
_isEnabled = v;
_isCollapsed = ImGui::IsWindowCollapsed();
ParallelConnection::Status status = OsEng.parallelConnection().status();
ParallelConnection::Status status = OsEng.parallelPeer().status();
switch (status) {
case ParallelConnection::Status::Disconnected:
renderDisconnected();
break;
case ParallelConnection::Status::Connecting:
renderConnecting();
break;
case ParallelConnection::Status::ClientWithHost:
renderClientWithHost();
break;
@@ -182,7 +195,7 @@ void GuiParallelComponent::render() {
break;
}
GuiPropertyComponent::renderPropertyOwner(&OsEng.parallelConnection());
GuiPropertyComponent::renderPropertyOwner(&OsEng.parallelPeer());
ImGui::End();
}
@@ -326,6 +326,10 @@ std::string KameleonVolumeReader::simulationEnd() const {
return _model->getGlobalAttribute("end_time").getAttributeString();
}
std::string KameleonVolumeReader::getVisUnit(const std::string& variable) const {
return _model->getNativeUnit(variable);
}
std::string KameleonVolumeReader::time() const {
double start =
ccmc::Time(simulationStart()).getEpoch();
@@ -72,8 +72,9 @@ public:
std::string time() const;
std::string simulationStart() const;
std::string simulationEnd() const;
std::string getVisUnit(const std::string& variable) const;
float elapsedTime() const;
double minValue(const std::string& variable) const;
double maxValue(const std::string& variable) const;
@@ -153,7 +153,7 @@ RenderableKameleonVolume::RenderableKameleonVolume(const ghoul::Dictionary& dict
, _transferFunctionPath(TransferFunctionInfo)
, _cache(CacheInfo)
, _raycaster(nullptr)
, _transferFunction(nullptr)
, _transferFunctionHandler(nullptr)
{
glm::vec3 dimensions;
@@ -172,9 +172,7 @@ RenderableKameleonVolume::RenderableKameleonVolume(const ghoul::Dictionary& dict
std::string transferFunctionPath;
if (dictionary.getValue(KeyTransferFunction, transferFunctionPath)) {
_transferFunctionPath = transferFunctionPath;
_transferFunction = std::make_shared<TransferFunction>(
absPath(transferFunctionPath)
);
_transferFunctionHandler = std::make_shared<volume::TransferFunctionHandler>(_transferFunctionPath);
}
std::string sourcePath;
@@ -263,13 +261,9 @@ void RenderableKameleonVolume::initializeGL() {
load();
_volumeTexture->uploadTexture();
_transferFunction->update();
_transferFunctionHandler->initialize();
_raycaster = std::make_unique<volume::BasicVolumeRaycaster>(
_volumeTexture,
_transferFunction,
_clipPlanes
);
_raycaster = std::make_unique<volume::BasicVolumeRaycaster>(_volumeTexture, _transferFunctionHandler, _clipPlanes);
_raycaster->setStepSize(_stepSize);
_gridType.onChange([this] {
@@ -318,6 +312,7 @@ void RenderableKameleonVolume::initializeGL() {
addProperty(_gridType);
addProperty(_cache);
addPropertySubOwner(_clipPlanes.get());
addPropertySubOwner(_transferFunctionHandler.get());
}
void RenderableKameleonVolume::updateRaycasterModelTransform() {
@@ -30,8 +30,7 @@
#include <openspace/properties/stringproperty.h>
#include <openspace/util/boxgeometry.h>
#include <openspace/rendering/renderable.h>
#include <openspace/rendering/transferfunction.h>
#include <modules/volume/transferfunctionhandler.h>
#include <modules/kameleon/include/kameleonwrapper.h>
#include <modules/volume/rawvolume.h>
#include <modules/volume/rendering/basicvolumeraycaster.h>
@@ -94,7 +93,7 @@ private:
std::unique_ptr<volume::BasicVolumeRaycaster> _raycaster;
std::shared_ptr<ghoul::opengl::Texture> _volumeTexture;
std::shared_ptr<TransferFunction> _transferFunction;
std::shared_ptr<volume::TransferFunctionHandler> _transferFunctionHandler;
};
} // namespace kameleonvolume
@@ -49,6 +49,10 @@ namespace {
constexpr const char* KeyMinValue = "MinValue";
constexpr const char* KeyMaxValue = "MaxValue";
constexpr const char* KeyVisUnit = "VisUnit";
constexpr const char* _loggerCat = "KameleonVolumeToRawTask";
} // namespace
namespace openspace {
@@ -100,7 +104,6 @@ void KameleonVolumeToRawTask::perform(const Task::ProgressCallback& progressCall
reader.maxValue(variables[2]));
}
std::unique_ptr<volume::RawVolume<float>> rawVolume = reader.readFloatVolume(
_dimensions,
_variable,
@@ -128,6 +131,7 @@ void KameleonVolumeToRawTask::perform(const Task::ProgressCallback& progressCall
outputMetadata.setValue<glm::vec3>(KeyDimensions, _dimensions);
outputMetadata.setValue<glm::vec3>(KeyLowerDomainBound, _lowerDomainBound);
outputMetadata.setValue<glm::vec3>(KeyUpperDomainBound, _upperDomainBound);
outputMetadata.setValue<float>(
KeyMinValue,
static_cast<float>(reader.minValue(_variable))
@@ -136,6 +140,10 @@ void KameleonVolumeToRawTask::perform(const Task::ProgressCallback& progressCall
KeyMaxValue,
static_cast<float>(reader.maxValue(_variable))
);
outputMetadata.setValue<std::string>(
KeyVisUnit,
static_cast<std::string>(reader.getVisUnit(_variable))
);
ghoul::DictionaryLuaFormatter formatter;
std::string metadataString = formatter.format(outputMetadata);
@@ -201,7 +209,13 @@ documentation::Documentation KameleonVolumeToRawTask::documentation() {
new DoubleVector3Verifier,
Optional::Yes,
"A vector representing the lower bound of the domain, "
"in the native kameleon grid units",
"in the native kameleon grid units"
},
{
KeyVisUnit,
new StringAnnotationVerifier("A valid kameleon unit"),
Optional::Yes,
"The unit of the data",
}
}
};
@@ -47,6 +47,7 @@ private:
std::string _dictionaryOutputPath;
std::string _variable;
std::string _units;
glm::uvec3 _dimensions;
bool _autoDomainBounds;
glm::vec3 _lowerDomainBound;
+64
View File
@@ -0,0 +1,64 @@
##########################################################################################
# #
# OpenSpace #
# #
# Copyright (c) 2014-2017 #
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy of this #
# software and associated documentation files (the "Software"), to deal in the Software #
# without restriction, including without limitation the rights to use, copy, modify, #
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to #
# permit persons to whom the Software is furnished to do so, subject to the following #
# conditions: #
# #
# The above copyright notice and this permission notice shall be included in all copies #
# or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, #
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A #
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT #
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF #
# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE #
# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #
##########################################################################################
include(${OPENSPACE_CMAKE_EXT_DIR}/module_definition.cmake)
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
set(HEADER_FILES
include/connectionpool.h
include/connection.h
include/jsonconverters.h
include/topic.h
include/authorizationtopic.h
include/getpropertytopic.h
include/luascripttopic.h
include/subscriptiontopic.h
include/setpropertytopic.h
include/timetopic.h
include/triggerpropertytopic.h
${CMAKE_CURRENT_SOURCE_DIR}/servermodule.h
)
source_group("Header Files" FILES ${HEADER_FILES})
set(SOURCE_FILES
src/connectionpool.cpp
src/connection.cpp
src/jsonconverters.cpp
src/topics/topic.cpp
src/topics/authorizationtopic.cpp
src/topics/getpropertytopic.cpp
src/topics/luascripttopic.cpp
src/topics/subscriptiontopic.cpp
src/topics/setpropertytopic.cpp
src/topics/timetopic.cpp
src/topics/triggerpropertytopic.cpp
${CMAKE_CURRENT_SOURCE_DIR}/servermodule.cpp
)
source_group("Source Files" FILES ${SOURCE_FILES})
create_new_module(
"Server"
server_module
${HEADER_FILES} ${SOURCE_FILES}
)
+1
View File
@@ -0,0 +1 @@
set(DEFAULT_MODULE ON)
@@ -0,0 +1,68 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef OPENSPACE_MODULES_SERVER__AUTHENTICATION_TOPIC_H
#define OPENSPACE_MODULES_SERVER__AUTHENTICATION_TOPIC_H
#include <ctime>
#include <ext/json/json.hpp>
#include <ghoul/logging/logmanager.h>
#include <fmt/format.h>
#include "topic.h"
#include "connection.h"
namespace openspace {
class AuthorizationTopic : public Topic {
public:
AuthorizationTopic();
~AuthorizationTopic() {};
void handleJson(nlohmann::json json);
bool isDone();
/* https://httpstatuses.com/ */
static const struct Statuses {
enum StatusCode {
OK = 200,
Accepted = 202,
BadRequest = 400,
Unauthorized = 401,
NotAcceptable = 406,
NotImplemented = 501
};
};
private:
bool _isAuthenticated;
const std::string getKey() const;
bool authorize(const std::string key);
nlohmann::json message(const std::string &message, const int &statusCode = Statuses::NotImplemented);
};
}
#endif //OPENSPACE_MODULES_SERVER__AUTHENTICATION_TOPIC_H
+79
View File
@@ -0,0 +1,79 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef OPENSPACE_MODOULES_SERVER__CONNECTION_H
#define OPENSPACE_MODOULES_SERVER__CONNECTION_H
#include <memory>
#include <string>
#include <ghoul/io/socket/tcpsocketserver.h>
#include <ghoul/io/socket/websocketserver.h>
#include <ghoul/misc/templatefactory.h>
#include <ext/json/json.hpp>
#include <ghoul/logging/logmanager.h>
#include <fmt/format.h>
#include <include/openspace/engine/openspaceengine.h>
#include <include/openspace/engine/configurationmanager.h>
#include "topic.h"
namespace openspace {
using TopicId = size_t;
class Connection {
public:
Connection(std::shared_ptr<ghoul::io::Socket> s, const std::string &address);
void handleMessage(std::string message);
void sendMessage(const std::string& message);
void handleJson(nlohmann::json json);
void sendJson(const nlohmann::json& json);
void setAuthorized(const bool status);
bool isAuthorized();
std::shared_ptr<ghoul::io::Socket> socket();
std::thread& thread();
void setThread(std::thread&& thread);
private:
ghoul::TemplateFactory<Topic> _topicFactory;
std::map<TopicId, std::unique_ptr<Topic>> _topics;
std::shared_ptr<ghoul::io::Socket> _socket;
std::thread _thread;
std::string _address;
bool _requireAuthorization;
bool _isAuthorized;
std::map <TopicId, std::string> _messageQueue;
std::map <TopicId, std::chrono::system_clock::time_point> _sentMessages;
bool isWhitelisted();
};
}
#endif //OPENSPACE_MODOULES_SERVER__CONNECTION_H
+65
View File
@@ -0,0 +1,65 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef __OPENSPACE_MODULE_SERVER___CONNECTIONPOOL___H__
#define __OPENSPACE_MODULE_SERVER___CONNECTIONPOOL___H__
#include <ghoul/io/socket/socketserver.h>
#include <memory>
#include <thread>
#include <mutex>
#include <map>
#include <functional>
#include <vector>
#include <atomic>
namespace openspace {
class ConnectionPool {
public:
ConnectionPool(std::function<void(std::shared_ptr<ghoul::io::Socket> socket)> handleSocket);
~ConnectionPool();
void addServer(std::shared_ptr<ghoul::io::SocketServer> server);
void removeServer(ghoul::io::SocketServer* server);
void clearServers();
void updateConnections();
private:
void disconnectAllConnections();
std::mutex _connectionMutex;
void removeDisconnectedSockets();
void acceptNewSockets();
std::function<void(std::shared_ptr<ghoul::io::Socket>)> _handleSocket;
std::vector<std::shared_ptr<ghoul::io::SocketServer>> _socketServers;
std::vector<std::shared_ptr<ghoul::io::Socket>> _sockets;
};
} // namespace openspace
#endif // __OPENSPACE_MODULE_SERVER___CONNECTIONPOOL___H__
+48
View File
@@ -0,0 +1,48 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef OPENSPACE_MODULES_SERVER__GETPROPERTY_TOPIC_H
#define OPENSPACE_MODULES_SERVER__GETPROPERTY_TOPIC_H
#include <openspace/query/query.h>
#include "topic.h"
#include "connection.h"
namespace openspace {
class GetPropertyTopic : public Topic {
public:
GetPropertyTopic();
~GetPropertyTopic() {};
void handleJson(nlohmann::json json);
bool isDone();
private:
nlohmann::json getAllProperties();
nlohmann::json getPropertyFromKey(const std::string& key);
};
}
#endif //OPENSPACE_MODULES_SERVER__GETPROPERTY_TOPIC_H
+61
View File
@@ -0,0 +1,61 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef OPENSPACE_MODULES_SERVER__JSON_CONVERTERS_INL
#define OPENSPACE_MODULES_SERVER__JSON_CONVERTERS_INL
#include <openspace/properties/property.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/rendering/renderable.h>
#include <ext/json/json.hpp>
#include <ghoul/glm.h>
using json = nlohmann::json;
namespace openspace::properties {
void to_json(json &j, const Property &p);
void to_json(json &j, const Property* pP);
void to_json(json &j, const PropertyOwner &p);
void to_json(json &j, const PropertyOwner *p);
} // namespace openspace::properties
namespace openspace {
void to_json(json &j, const SceneGraphNode &n);
void to_json(json &j, const SceneGraphNode* pN);
void to_json(json &j, const Renderable &r);
void to_json(json &j, const Renderable* pR);
} // namespace openspace
namespace glm {
void to_json(json &j, const dvec3 &v);
}
#endif
+43
View File
@@ -0,0 +1,43 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef OPENSPACE_MODULES_SERVER__LUASCRIPTTOPIC_H
#define OPENSPACE_MODULES_SERVER__LUASCRIPTTOPIC_H
#include <ext/json/json.hpp>
#include <modules/server/include/topic.h>
namespace openspace {
class LuaScriptTopic : public Topic {
public:
LuaScriptTopic() : Topic() {};
~LuaScriptTopic() {};
void handleJson(nlohmann::json json);
bool isDone() { return true; };
};
}
#endif //OPENSPACE_MODULES_SERVER__LUASCRIPTTOPIC_H
+46
View File
@@ -0,0 +1,46 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef OPENSPACE_MODULES_SERVER__SETPROPERTYTOPIC_H
#define OPENSPACE_MODULES_SERVER__SETPROPERTYTOPIC_H
#include <ext/json/json.hpp>
#include <modules/server/include/topic.h>
namespace openspace {
class SetPropertyTopic : public Topic {
public:
SetPropertyTopic() : Topic() {};
~SetPropertyTopic() {};
void handleJson(nlohmann::json json);
bool isDone() { return true; };
private:
void setTime(const std::string& value);
};
}
#endif //OPENSPACE_MODULES_SERVER__SETPROPERTYTOPIC_H
@@ -0,0 +1,52 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef OPENSPACE_MODULES_SERVER__SUBSCRIPTION_TOPIC_H
#define OPENSPACE_MODULES_SERVER__SUBSCRIPTION_TOPIC_H
#include <openspace/util/timemanager.h>
#include <openspace/query/query.h>
#include "topic.h"
#include "connection.h"
namespace openspace {
class property;
class SubscriptionTopic : public Topic {
public:
SubscriptionTopic();
~SubscriptionTopic();
void handleJson(nlohmann::json json);
bool isDone();
private:
bool _requestedResourceIsSubscribable;
bool _isSubscribedTo;
int _onChangeHandle;
int _onDeleteHandle;
properties::Property* _prop;
};
}
#endif //OPENSPACE_MODULES_SERVER__SUBSCRIPTION_TOPIC_H
+50
View File
@@ -0,0 +1,50 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef OPENSPACE_MODULES_SERVER__TIME_TOPIC_H
#define OPENSPACE_MODULES_SERVER__TIME_TOPIC_H
#include <openspace/util/timemanager.h>
#include "topic.h"
namespace openspace {
class TimeTopic : public Topic {
public:
TimeTopic();
~TimeTopic();
void handleJson(nlohmann::json json);
bool isDone();
private:
nlohmann::json currentTime();
nlohmann::json deltaTime();
int _timeCallbackHandle;
int _deltaTimeCallbackHandle;
std::chrono::system_clock::time_point _lastUpdateTime;
};
}
#endif //OPENSPACE_MODULES_SERVER__TIME_TOPIC_H
+59
View File
@@ -0,0 +1,59 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef OPENSPACE_MODULES_SERVER__TOPIC_H
#define OPENSPACE_MODULES_SERVER__TOPIC_H
#include <ext/json/json.hpp>
namespace openspace {
class Connection;
class Topic {
public:
Topic() {};
virtual ~Topic() {};
void initialize(Connection* connection, size_t topicId);
nlohmann::json wrappedPayload(const nlohmann::json &payload) const;
nlohmann::json wrappedError(std::string message = "Could not complete request.", int code = 500);
virtual void handleJson(nlohmann::json json) = 0;
virtual bool isDone() = 0;
protected:
size_t _topicId;
Connection* _connection;
};
class BounceTopic : public Topic {
public:
BounceTopic() : Topic() {};
~BounceTopic() {};
void handleJson(nlohmann::json json);
bool isDone() { return false; }
};
}
#endif //OPENSPACE_MODULES_SERVER__TOPIC_H
@@ -0,0 +1,43 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef OPENSPACE_MODULES_SERVER__TRIGGERPROPERTYTOPIC_H
#define OPENSPACE_MODULES_SERVER__TRIGGERPROPERTYTOPIC_H
#include <ext/json/json.hpp>
#include <modules/server/include/topic.h>
namespace openspace {
class TriggerPropertyTopic : public Topic {
public:
TriggerPropertyTopic() : Topic() {};
~TriggerPropertyTopic() {};
void handleJson(nlohmann::json json);
bool isDone() { return true; };
};
}
#endif //OPENSPACE_MODULES_SERVER__TRIGGERPROPERTYTOPIC_H
+143
View File
@@ -0,0 +1,143 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/server/servermodule.h>
#include <ghoul/io/socket/websocket.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/scripting/scriptengine.h>
namespace {
const char* _loggerCat = "ServerModule";
}
namespace openspace {
ServerModule::ServerModule()
: OpenSpaceModule(ServerModule::Name)
{}
ServerModule::~ServerModule() {
disconnectAll();
cleanUpFinishedThreads();
}
void ServerModule::internalInitialize(const ghoul::Dictionary& configuration) {
using namespace ghoul::io;
std::unique_ptr<TcpSocketServer> tcpServer = std::make_unique<TcpSocketServer>();
std::unique_ptr<WebSocketServer> wsServer = std::make_unique<WebSocketServer>();
// Temporary hard coded addresses and ports.
tcpServer->listen("localhost", 8000);
wsServer->listen("localhost", 8001);
LDEBUG(fmt::format("TCP Server listening on {}:{}",
tcpServer->address(), tcpServer->port()));
LDEBUG(fmt::format("WS Server listening on {}:{}",
wsServer->address(), wsServer->port()));
_servers.push_back(std::move(tcpServer));
_servers.push_back(std::move(wsServer));
OsEng.registerModuleCallback(
OpenSpaceEngine::CallbackOption::PreSync,
[this]() { preSync(); }
);
}
void ServerModule::preSync() {
// Set up new connections.
for (auto& server : _servers) {
std::shared_ptr<ghoul::io::Socket> socket;
while ((socket = server->nextPendingSocket())) {
socket->startStreams();
std::shared_ptr<Connection> connection =
std::make_shared<Connection>(socket, server->address());
connection->setThread(
std::thread([this, connection] () { handleConnection(connection); })
);
_connections.push_back({ std::move(connection), false });
}
}
// Consume all messages put into the message queue by the socket threads.
consumeMessages();
// Join threads for sockets that disconnected.
cleanUpFinishedThreads();
}
void ServerModule::cleanUpFinishedThreads() {
for (auto& connectionData : _connections) {
std::shared_ptr<Connection>& connection = connectionData.connection;
if (!connection->socket() || !connection->socket()->isConnected()) {
if (connection->thread().joinable()) {
connection->thread().join();
connectionData.markedForRemoval = true;
}
}
}
_connections.erase(std::remove_if(
_connections.begin(),
_connections.end(),
[](const auto& connectionData) {
return connectionData.markedForRemoval;
}
), _connections.end());
}
void ServerModule::disconnectAll() {
for (auto& connectionData : _connections) {
std::shared_ptr<Connection>& connection = connectionData.connection;
if (connection->socket() && connection->socket()->isConnected()) {
connection->socket()->disconnect(
static_cast<int>(ghoul::io::WebSocket::ClosingReason::ClosingAll)
);
}
}
}
void ServerModule::handleConnection(std::shared_ptr<Connection> connection) {
std::string messageString;
while (connection->socket()->getMessage(messageString)) {
std::lock_guard<std::mutex> lock(_messageQueueMutex);
_messageQueue.push_back(Message({
connection,
std::move(messageString)
}));
}
}
void ServerModule::consumeMessages() {
std::lock_guard<std::mutex> lock(_messageQueueMutex);
while (_messageQueue.size() > 0) {
Message m = _messageQueue.front();
_messageQueue.pop_front();
if (std::shared_ptr<Connection> c = m.connection.lock()) {
c->handleMessage(m.messageString);
}
}
}
} // namespace openspace
+80
View File
@@ -0,0 +1,80 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef __OPENSPACE_MODULE_SERVER___SERVERMODULE___H__
#define __OPENSPACE_MODULE_SERVER___SERVERMODULE___H__
#include <openspace/util/openspacemodule.h>
#include <ghoul/io/socket/tcpsocketserver.h>
#include <ghoul/misc/templatefactory.h>
#include <deque>
#include <memory>
#include <thread>
#include <mutex>
#include <cstdint>
#include <map>
#include <ext/json/json.hpp>
#include <fmt/format.h>
#include "include/connection.h"
#include "include/topic.h"
namespace openspace {
struct Message {
std::weak_ptr<Connection> connection;
std::string messageString;
};
class ServerModule : public OpenSpaceModule {
public:
static constexpr const char* Name = "Server";
ServerModule();
virtual ~ServerModule();
protected:
void internalInitialize(const ghoul::Dictionary& configuration) override;
private:
struct ConnectionData {
std::shared_ptr<Connection> connection;
bool markedForRemoval = false;
};
void handleConnection(std::shared_ptr<Connection> connection);
void cleanUpFinishedThreads();
void consumeMessages();
void disconnectAll();
void preSync();
std::mutex _messageQueueMutex;
std::deque<Message> _messageQueue;
std::vector<ConnectionData> _connections;
std::vector<std::unique_ptr<ghoul::io::SocketServer>> _servers;
};
} // namespace openspace
#endif // __OPENSPACE_MODULE_SERVER___SERVERMODULE___H__
+200
View File
@@ -0,0 +1,200 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/server/include/connection.h>
#include <modules/server/include/authorizationtopic.h>
#include <modules/server/include/getpropertytopic.h>
#include <modules/server/include/luascripttopic.h>
#include <modules/server/include/setpropertytopic.h>
#include <modules/server/include/subscriptiontopic.h>
#include <modules/server/include/timetopic.h>
#include <modules/server/include/triggerpropertytopic.h>
namespace {
const char* _loggerCat = "ServerModule: Connection";
const char* MessageKeyType = "type";
const char* MessageKeyPayload = "payload";
const char* MessageKeyTopic = "topic";
const char* AuthenticationTopicKey = "authorize";
const char* GetPropertyTopicKey = "get";
const char* LuaScriptTopicKey = "luascript";
const char* SetPropertyTopicKey = "set";
const char* SubscriptionTopicKey = "subscribe";
const char* TimeTopicKey = "time";
const char* TriggerPropertyTopicKey = "trigger";
const char* BounceTopicKey = "bounce";
const int ThrottleMessageWaitInMs = 100;
}
namespace openspace {
Connection::Connection(std::shared_ptr<ghoul::io::Socket> s, const std::string &address)
: _socket(s)
, _isAuthorized(false)
, _address(address)
{
_topicFactory.registerClass<AuthorizationTopic>(AuthenticationTopicKey);
_topicFactory.registerClass<GetPropertyTopic>(GetPropertyTopicKey);
_topicFactory.registerClass<LuaScriptTopic>(LuaScriptTopicKey);
_topicFactory.registerClass<SetPropertyTopic>(SetPropertyTopicKey);
_topicFactory.registerClass<SubscriptionTopic>(SubscriptionTopicKey);
_topicFactory.registerClass<TimeTopic>(TimeTopicKey);
_topicFactory.registerClass<TriggerPropertyTopic>(TriggerPropertyTopicKey);
_topicFactory.registerClass<BounceTopic>(BounceTopicKey);
// see if the default config for requiring auth (on) is overwritten
const bool hasAuthenticationConfiguration = OsEng.configurationManager().hasKeyAndValue<bool>(
ConfigurationManager::KeyRequireSocketAuthentication);
if (hasAuthenticationConfiguration) {
_requireAuthorization = OsEng.configurationManager().value<bool>(
ConfigurationManager::KeyRequireSocketAuthentication);
} else {
_requireAuthorization = true;
}
}
void Connection::handleMessage(std::string message) {
try {
nlohmann::json j = nlohmann::json::parse(message.c_str());
try {
handleJson(j);
}
catch (...) {
LERROR(fmt::format("JSON handling error from: {}", message));
}
} catch (...) {
if (!isAuthorized()) {
LERROR("");
_socket->disconnect();
LERROR(fmt::format(
"Could not parse JSON: '{}'. Connection is unauthorized. Disconnecting.",
message
));
return;
} else {
LERROR(fmt::format("Could not parse JSON: '{}'", message));
}
}
}
void Connection::handleJson(nlohmann::json j) {
auto topicJson = j.find(MessageKeyTopic);
auto payloadJson = j.find(MessageKeyPayload);
if (topicJson == j.end() || !topicJson->is_number_integer()) {
LERROR("Topic must be an integer");
return;
}
if (payloadJson == j.end() || !payloadJson->is_object()) {
LERROR("Payload must be an object");
return;
}
// The topic id may be an already discussed topic, or a new one.
TopicId topicId = *topicJson;
auto topicIt = _topics.find(topicId);
if (topicIt == _topics.end()) {
// The topic id is not registered: Initialize a new topic.
auto typeJson = j.find(MessageKeyType);
if (typeJson == j.end() || !typeJson->is_string()) {
LERROR(fmt::format("A type must be specified (`{}`) as a string when "
"a new topic is initialized", MessageKeyType));
return;
}
std::string type = *typeJson;
if (!isAuthorized() && type != AuthenticationTopicKey) {
LERROR("Connection isn't authorized.");
return;
}
std::unique_ptr<Topic> topic = _topicFactory.create(type);
topic->initialize(this, topicId);
topic->handleJson(*payloadJson);
if (!topic->isDone()) {
_topics.emplace(topicId, std::move(topic));
}
} else {
if (!isAuthorized()) {
LERROR("Connection isn't authorized.");
return;
}
// Dispatch the message to the existing topic.
std::unique_ptr<Topic> &topic = topicIt->second;
topic->handleJson(*payloadJson);
if (topic->isDone()) {
_topics.erase(topicIt);
}
}
}
void Connection::sendMessage(const std::string &message) {
_socket->putMessage(message);
}
void Connection::sendJson(const nlohmann::json &j) {
sendMessage(j.dump());
}
bool Connection::isAuthorized() {
// require either auth to be disabled or client to be authenticated
return !_requireAuthorization || isWhitelisted() || _isAuthorized;
}
void Connection::setThread(std::thread&& thread) {
_thread = std::move(thread);
}
std::thread& Connection::thread() {
return _thread;
}
std::shared_ptr<ghoul::io::Socket> Connection::socket() {
return _socket;
}
void Connection::setAuthorized(const bool status) {
_isAuthorized = status;
}
bool Connection::isWhitelisted() {
const bool hasWhitelist = OsEng.configurationManager().hasKeyAndValue<std::string>(
ConfigurationManager::KeyServerClientAddressWhitelist);
if (!hasWhitelist) {
return false;
}
const auto whitelist = OsEng.configurationManager().value<std::string>(
ConfigurationManager::KeyServerClientAddressWhitelist);
return whitelist.find(_address) != std::string::npos;
}
} // namespace openspace
+87
View File
@@ -0,0 +1,87 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/server/include/connectionpool.h>
#include <ghoul/io/socket/socket.h>
#include <vector>
#include <algorithm>
namespace openspace {
ConnectionPool::ConnectionPool(std::function<void(std::shared_ptr<ghoul::io::Socket> socket)> handleSocket)
: _handleSocket(std::move(handleSocket))
{}
ConnectionPool::~ConnectionPool() {
disconnectAllConnections();
}
void ConnectionPool::addServer(std::shared_ptr<ghoul::io::SocketServer> server) {
_socketServers.push_back(server);
}
void ConnectionPool::removeServer(ghoul::io::SocketServer* server) {
std::remove_if(_socketServers.begin(), _socketServers.end(), [server](const auto& s) {
return s.get() == server;
});
}
void ConnectionPool::clearServers() {
_socketServers.clear();
}
void ConnectionPool::updateConnections() {
removeDisconnectedSockets();
acceptNewSockets();
}
void ConnectionPool::acceptNewSockets() {
for (auto& server : _socketServers) {
std::shared_ptr<ghoul::io::Socket> socket;
while (socket = server->nextPendingSocket()) {
_handleSocket(socket);
_sockets.push_back(socket);
}
}
}
void ConnectionPool::removeDisconnectedSockets() {
std::remove_if(_sockets.begin(), _sockets.end(), [](const std::shared_ptr<ghoul::io::Socket> socket) {
return !socket || !socket->isConnected();
});
}
void ConnectionPool::disconnectAllConnections() {
for (auto& socket : _sockets) {
if (socket && socket->isConnected()) {
socket->disconnect();
}
}
_sockets.clear();
}
} // namespace openspace
+121
View File
@@ -0,0 +1,121 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/server/include/jsonconverters.h>
#include <openspace/properties/property.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/rendering/renderable.h>
#include <ghoul/logging/logmanager.h>
#include <ext/json/json.hpp>
using json = nlohmann::json;
namespace openspace::properties {
void to_json(json &j, const Property &p) {
j = {
{ "Description", json::parse(p.generateBaseJsonDescription()) },
{ "Value", p.jsonValue() }
};
j["Description"]["description"] = p.description();
}
void to_json(json &j, const Property* pP) {
j = *pP;
}
void to_json(json &j, const PropertyOwner &p) {
j = {
{ "identifier", p.identifier() },
{ "description", p.description() },
{ "properties", p.properties() },
{ "subowners", p.propertySubOwners() },
{ "tag", p.tags() }
};
}
void to_json(json &j, const PropertyOwner* p) {
j = *p;
}
} // namespace openspace::properties
namespace openspace {
void to_json(json &j, const SceneGraphNode &n) {
j = {
{ "identifier", n.identifier() },
{ "worldPosition", n.worldPosition() },
{ "position", n.position() },
{ "tags", n.tags() },
{ "propertiesCount", n.properties().size() },
{ "properties", n.properties() },
{ "subowners", n.propertySubOwners() }
};
/*
auto renderable = n.renderable();
if (renderable != nullptr) {
j["renderable"] = renderable;
}*/
auto parent = n.parent();
if (parent != nullptr) {
j["parent"] = {
{ "identifier", parent->identifier() }
};
}
}
void to_json(json &j, const SceneGraphNode* pN) {
// Use reference converter instead of pointer
j = *pN;
}
void to_json(json &j, const Renderable &r) {
j = {
{ "properties", r.properties() },
{ "enabled", r.isEnabled() }
};
}
void to_json(json &j, const Renderable* pR) {
// Use reference converter instead of pointer
j = *pR;
}
} // namespace openspace
namespace glm {
void to_json(json &j, const dvec3 &v) {
j = {
{ "value", {v.x, v.y, v.z} },
{ "type", "vec3" }
};
}
}
@@ -0,0 +1,83 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include "include/authorizationtopic.h"
namespace {
std::string _loggerCat = "AuthorizationTopic";
}
namespace openspace {
AuthorizationTopic::AuthorizationTopic()
: Topic()
, _isAuthenticated(false) {};
bool AuthorizationTopic::isDone() {
return _isAuthenticated;
}
void AuthorizationTopic::handleJson(nlohmann::json json) {
if (isDone()) {
_connection->sendJson(message("Already authorized.", Statuses::OK));
} else {
try {
auto providedKey = json.at("key").get<std::string>();
if (authorize(providedKey)) {
_connection->sendJson(message("Authorization OK.", Statuses::Accepted));
_connection->setAuthorized(true);
LINFO("Client successfully authorized.");
} else {
_connection->sendJson(message("Invalid key", Statuses::NotAcceptable));
}
} catch (const std::out_of_range& e) {
_connection->sendJson(message("Invalid request, key must be provided.", Statuses::BadRequest));
} catch (const std::domain_error& e) {
_connection->sendJson(message("Invalid request, invalid key format.", Statuses::BadRequest));
}
}
};
bool AuthorizationTopic::authorize(const std::string key) {
_isAuthenticated = key == getKey();
return _isAuthenticated;
}
const std::string AuthorizationTopic::getKey() const {
const bool hasConfigPassword = OsEng.configurationManager().hasKeyAndValue<std::string>(
ConfigurationManager::KeyServerPasskey);
if (hasConfigPassword) {
return OsEng.configurationManager().value<std::string>(
ConfigurationManager::KeyServerPasskey);
}
return "17308";
}
nlohmann::json AuthorizationTopic::message(const std::string &message, const int &statusCode) {
nlohmann::json error = {{"message", message}, {"code", statusCode}};
return error;
}
}
@@ -0,0 +1,102 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/server/include/jsonconverters.h>
#include <openspace/properties/property.h>
#include <openspace/interaction/luaconsole.h>
#include <openspace/network/parallelconnection.h>
#include <openspace/engine/wrapper/windowwrapper.h>
#include <openspace/interaction/navigationhandler.h>
#include <openspace/engine/virtualpropertymanager.h>
#include <openspace/rendering/screenspacerenderable.h>
#include <openspace/scene/scene.h>
#include <modules/server/include/getpropertytopic.h>
#include <modules/volume/transferfunctionhandler.h>
using nlohmann::json;
namespace {
const char* _loggerCat = "GetPropertyTopic";
const char* AllPropertiesValue = "__allProperties";
const char* AllNodesValue = "__allNodes";
const char* AllScreenSpaceRenderablesValue = "__screenSpaceRenderables";
const char* PropertyKey = "property";
const char* RootPropertyOwner = "__rootOwner";
}
namespace openspace {
GetPropertyTopic::GetPropertyTopic()
: Topic() {}
bool GetPropertyTopic::isDone() {
return true;
}
void GetPropertyTopic::handleJson(json j) {
std::string requestedKey = j.at(PropertyKey).get<std::string>();
LDEBUG("Getting property '" + requestedKey + "'...");
json response;
if (requestedKey == AllPropertiesValue) {
response = getAllProperties();
}
else if (requestedKey == AllNodesValue) {
response = wrappedPayload(sceneGraph()->allSceneGraphNodes());
}
else if (requestedKey == AllScreenSpaceRenderablesValue) {
response = wrappedPayload({ { "value", OsEng.renderEngine().screenSpaceRenderables() } });
}
else if (requestedKey == RootPropertyOwner) {
response = wrappedPayload(OsEng.rootPropertyOwner());
}
else {
response = getPropertyFromKey(requestedKey);
}
_connection->sendJson(response);
}
json GetPropertyTopic::getAllProperties() {
json payload{
{ "value", {
OsEng.renderEngine(),
OsEng.console(),
OsEng.parallelPeer(),
OsEng.windowWrapper(),
OsEng.navigationHandler(),
OsEng.virtualPropertyManager(),
}}
};
return wrappedPayload(payload);
}
json GetPropertyTopic::getPropertyFromKey(const std::string& key) {
properties::Property* prop = property(key);
if (prop != nullptr) {
return wrappedPayload(prop);
}
return wrappedError(fmt::format("property '{}' not found", key), 404);
}
} // namespace openspace
@@ -0,0 +1,49 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <openspace/engine/openspaceengine.h>
#include <openspace/scripting/scriptengine.h>
#include <ghoul/logging/logmanager.h>
#include <modules/server/include/luascripttopic.h>
namespace {
const std::string ScriptKey = "script";
const std::string _loggerCat = "LuaScriptTopic";
}
namespace openspace {
void LuaScriptTopic::handleJson(nlohmann::json json) {
try {
auto script = json.at(ScriptKey).get<std::string>();
LDEBUG("Queueing Lua script: " + script);
OsEng.scriptEngine().queueScript(script, scripting::ScriptEngine::RemoteScripting::No);
}
catch (std::out_of_range& e) {
LERROR("Could run script -- key or value is missing in payload");
LERROR(e.what());
}
}
}
@@ -0,0 +1,73 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <openspace/query/query.h>
#include <openspace/properties/property.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/util/timemanager.h>
#include <ghoul/logging/logmanager.h>
#include <modules/server/include/setpropertytopic.h>
namespace {
const std::string PropertyKey = "property";
const std::string ValueKey = "value";
const std::string _loggerCat = "SetPropertyTopic";
const std::string SpecialKeyTime = "__time";
}
namespace openspace {
void SetPropertyTopic::handleJson(nlohmann::json json) {
try {
auto propertyKey = json.at(PropertyKey).get<std::string>();
auto value = json.at(ValueKey).get<std::string>();
if (propertyKey == SpecialKeyTime) {
setTime(value);
}
else {
auto prop = property(propertyKey);
if (prop != nullptr) {
LDEBUG("Setting " + propertyKey + " to " + value + ".");
if (!prop->setStringValue(value)) {
LERROR("Failed!");
}
}
}
}
catch (std::out_of_range& e) {
LERROR("Could not set property -- key or value is missing in payload");
LERROR(e.what());
}
catch (ghoul::RuntimeError e) {
LERROR("Could not set property -- runtime error:");
LERROR(e.what());
}
}
void SetPropertyTopic::setTime(const std::string& timeValue) {
OsEng.timeManager().time().setTime(timeValue);
}
}
@@ -0,0 +1,98 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <openspace/query/query.h>
#include <openspace/properties/property.h>
#include <modules/server/include/jsonconverters.h>
#include "include/subscriptiontopic.h"
namespace {
const char* _loggerCat = "SubscriptionTopic";
const char* PropertyKey = "property";
const char* EventKey = "event";
const char* StartSubscription = "start_subscription";
const char* StopSubscription = "stop_subscription";
const int UnsetCallbackHandle = -1;
}
using nlohmann::json;
namespace openspace {
SubscriptionTopic::SubscriptionTopic()
: Topic()
, _requestedResourceIsSubscribable(false)
, _onChangeHandle(UnsetCallbackHandle)
, _onDeleteHandle(UnsetCallbackHandle) {}
SubscriptionTopic::~SubscriptionTopic() {
if (_onChangeHandle != UnsetCallbackHandle) {
_prop->removeOnChange(_onChangeHandle);
}
if (!_onDeleteHandle) {
_prop->removeOnDelete(_onDeleteHandle);
}
}
bool SubscriptionTopic::isDone() {
return !_requestedResourceIsSubscribable || !_isSubscribedTo;
}
void SubscriptionTopic::handleJson(json j) {
std::string key = j.at(PropertyKey).get<std::string>();
std::string event = j.at(EventKey).get<std::string>();
if (event == StartSubscription) {
LDEBUG("Subscribing to property '" + key + "'...");
_prop = property(key);
if (_prop != nullptr) {
_requestedResourceIsSubscribable = true;
_isSubscribedTo = true;
auto onChange = [this, key]() {
LDEBUG("Updating subscription '" + key + "'.");
_connection->sendJson(wrappedPayload(_prop));
};
_onChangeHandle = _prop->onChange(onChange);
_prop->onDelete([this]() {
_onChangeHandle = UnsetCallbackHandle;
_onDeleteHandle = UnsetCallbackHandle;
_isSubscribedTo = false;
});
// immediately send the value
onChange();
}
else {
LWARNING("Could not subscribe. Property '" + key + "' not found.");
}
}
if (event == StopSubscription) {
_isSubscribedTo = false;
}
}
} // namespace openspace
+108
View File
@@ -0,0 +1,108 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <openspace/query/query.h>
#include <openspace/properties/property.h>
#include "modules/server/include/connection.h"
#include "modules/server/include/timetopic.h"
#include <chrono>
namespace {
const char* _loggerCat = "TimeTopic";
const char* PropertyKey = "property";
const char* CurrentTimeKey = "currentTime";
const char* DeltaTimeKey = "deltaTime";
const int UNSET_ONCHANGE_HANDLE = -1;
const std::chrono::milliseconds TimeUpdateInterval(100);
}
using nlohmann::json;
namespace openspace {
TimeTopic::TimeTopic()
: Topic()
, _timeCallbackHandle(UNSET_ONCHANGE_HANDLE)
, _deltaTimeCallbackHandle(UNSET_ONCHANGE_HANDLE)
, _lastUpdateTime(std::chrono::system_clock::now())
{
LDEBUG("Starting new time subscription");
}
TimeTopic::~TimeTopic() {
if (_timeCallbackHandle != UNSET_ONCHANGE_HANDLE) {
OsEng.timeManager().removeTimeChangeCallback(_timeCallbackHandle);
}
if (_deltaTimeCallbackHandle != UNSET_ONCHANGE_HANDLE) {
OsEng.timeManager().removeDeltaTimeChangeCallback(_deltaTimeCallbackHandle);
}
}
bool TimeTopic::isDone() {
return false;
}
void TimeTopic::handleJson(json j) {
std::string requestedKey = j.at(PropertyKey).get<std::string>();
LDEBUG("Subscribing to " + requestedKey);
if (requestedKey == CurrentTimeKey) {
_timeCallbackHandle = OsEng.timeManager().addTimeChangeCallback([this]() {
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
if (now - _lastUpdateTime > TimeUpdateInterval) {
_connection->sendJson(currentTime());
_lastUpdateTime = now;
}
});
_connection->sendJson(currentTime());
}
else if (requestedKey == DeltaTimeKey) {
_deltaTimeCallbackHandle = OsEng.timeManager().addDeltaTimeChangeCallback(
[this]() {
_connection->sendJson(deltaTime());
if (_timeCallbackHandle != UNSET_ONCHANGE_HANDLE) {
_connection->sendJson(currentTime());
_lastUpdateTime = std::chrono::system_clock::now();;
}
}
);
_connection->sendJson(deltaTime());
}
else {
LWARNING("Cannot get " + requestedKey);
}
}
json TimeTopic::currentTime() {
json timeJson = { { "time", OsEng.timeManager().time().ISO8601() } };
return wrappedPayload(timeJson);
}
json TimeTopic::deltaTime() {
json timeJson = { { "deltaTime", OsEng.timeManager().time().deltaTime() } };
return wrappedPayload(timeJson);
}
} // namespace openspace
+58
View File
@@ -0,0 +1,58 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/server/servermodule.h>
#include <modules/server/include/topic.h>
namespace openspace {
void Topic::initialize(Connection* connection, size_t topicId) {
_connection = connection;
_topicId = topicId;
};
nlohmann::json Topic::wrappedPayload(const nlohmann::json &payload) const {
// TODO: add message time
nlohmann::json j = {
{ "topic", _topicId },
{ "payload", payload }
};
return j;
};
nlohmann::json Topic::wrappedError(std::string message, int code) {
nlohmann::json j = {
{ "topic", _topicId },
{ "status", "error" },
{ "message", message },
{ "code", code }
};
return j;
};
void BounceTopic::handleJson(nlohmann::json json) {
_connection->sendJson(json);
};
}
@@ -0,0 +1,63 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <openspace/query/query.h>
#include <openspace/properties/property.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/util/timemanager.h>
#include <ghoul/logging/logmanager.h>
#include <modules/server/include/triggerpropertytopic.h>
namespace {
const std::string PropertyKey = "property";
const std::string ValueKey = "value";
const std::string _loggerCat = "TriggerPropertyTopic";
}
namespace openspace {
void TriggerPropertyTopic::handleJson(nlohmann::json json) {
try {
auto propertyKey = json.at(PropertyKey).get<std::string>();
auto prop = property(propertyKey);
if (prop != nullptr) {
LDEBUG("Triggering " + propertyKey);
prop->set("poke");
}
else {
LWARNING("Could not find property " + propertyKey);
}
}
catch (std::out_of_range& e) {
LERROR("Could not poke property -- key or value is missing in payload");
LERROR(e.what());
}
catch (ghoul::RuntimeError e) {
LERROR("Could not poke property -- runtime error:");
LERROR(e.what());
}
}
}
+1 -1
View File
@@ -271,7 +271,7 @@ bool HttpSynchronization::trySyncFromUrl(std::string listUrl) {
int success = rename(tempName.c_str(), originalName.c_str());
if (success != 0) {
LERRORC(
"URLSynchronization",
"HTTPSynchronization",
fmt::format(
"Error renaming file {} to {}", tempName, originalName
)
+8
View File
@@ -25,6 +25,7 @@
include(${OPENSPACE_CMAKE_EXT_DIR}/module_definition.cmake)
set(HEADER_FILES
${CMAKE_CURRENT_SOURCE_DIR}/envelope.h
${CMAKE_CURRENT_SOURCE_DIR}/rawvolume.h
${CMAKE_CURRENT_SOURCE_DIR}/rawvolume.inl
${CMAKE_CURRENT_SOURCE_DIR}/rawvolumereader.h
@@ -33,6 +34,9 @@ set(HEADER_FILES
${CMAKE_CURRENT_SOURCE_DIR}/rawvolumewriter.inl
${CMAKE_CURRENT_SOURCE_DIR}/textureslicevolumereader.h
${CMAKE_CURRENT_SOURCE_DIR}/textureslicevolumereader.inl
${CMAKE_CURRENT_SOURCE_DIR}/transferfunction.h
${CMAKE_CURRENT_SOURCE_DIR}/transferfunctionhandler.h
${CMAKE_CURRENT_SOURCE_DIR}/transferfunctionproperty.h
${CMAKE_CURRENT_SOURCE_DIR}/lrucache.h
${CMAKE_CURRENT_SOURCE_DIR}/linearlrucache.h
${CMAKE_CURRENT_SOURCE_DIR}/volumegridtype.h
@@ -47,10 +51,14 @@ set(HEADER_FILES
source_group("Header Files" FILES ${HEADER_FILES})
set(SOURCE_FILES
${CMAKE_CURRENT_SOURCE_DIR}/envelope.cpp
${CMAKE_CURRENT_SOURCE_DIR}/rawvolume.inl
${CMAKE_CURRENT_SOURCE_DIR}/rawvolumereader.inl
${CMAKE_CURRENT_SOURCE_DIR}/rawvolumewriter.inl
${CMAKE_CURRENT_SOURCE_DIR}/textureslicevolumereader.inl
${CMAKE_CURRENT_SOURCE_DIR}/transferfunction.cpp
${CMAKE_CURRENT_SOURCE_DIR}/transferfunctionhandler.cpp
${CMAKE_CURRENT_SOURCE_DIR}/transferfunctionproperty.cpp
${CMAKE_CURRENT_SOURCE_DIR}/volumesampler.inl
${CMAKE_CURRENT_SOURCE_DIR}/volumegridtype.cpp
${CMAKE_CURRENT_SOURCE_DIR}/volumeutils.cpp
+176
View File
@@ -0,0 +1,176 @@
#include <modules/volume/envelope.h>
namespace openspace {
namespace volume {
Envelope::Envelope() { }
Envelope::Envelope(std::vector<EnvelopePoint> vec) {
_points = vec;
}
bool Envelope::operator!=(const Envelope& env) const {
const double minDist = 0.0001;
if (_points.size() != env._points.size())
return true;
auto iter = _points.begin();
auto envIter = env._points.begin();
for (; iter != _points.end(); ++iter, ++envIter) {
if (abs(iter->position.first - envIter->position.first) > minDist ||
abs(iter->position.second - envIter->position.second) > minDist ||
iter->color != envIter->color)
return true;
}
return false;
}
void Envelope::setPoints(std::vector<EnvelopePoint> vec) {
this->_points = vec;
}
std::vector<EnvelopePoint> Envelope::getPoints() {
return _points;
}
bool Envelope::isValueInEnvelope(float pos) const {
if (!_points.empty()) {
if (_points.front().position.first <= pos && _points.back().position.first >= pos)
return true;
}
return false;
}
bool Envelope::isEnvelopeValid() const {
auto currentIter = _points.begin();
auto nextIter = currentIter + 1;
for (; nextIter != _points.end(); ++currentIter, ++nextIter) {
if (currentIter->position.first > nextIter->position.first)
return false;
}
return true;
}
glm::vec3 Envelope::normalizeColor(glm::vec3 vec) const{
return glm::vec3{ vec.r / 255.f, vec.g / 255.f , vec.b / 255.f };
}
glm::vec4 Envelope::getValueAtPosition(float pos) const {
auto afterIter = _points.begin();
glm::vec4 color{ 0.f, 0.f , 0.f , 0.f };
while (afterIter->position.first < pos ) {
if(afterIter == _points.end())
return color;
++afterIter;
}
if (afterIter->position.first == pos) {
return glm::vec4{ afterIter->color, afterIter->position.second };
}
auto beforeIter = afterIter -1;
float dist = afterIter->position.first - beforeIter->position.first;
float alpha;
if(dist < 0.0001)
color = { normalizeColor((beforeIter->color + afterIter->color) / 2.f),
std::max(beforeIter->position.second, afterIter->position.second) };
else
color = { normalizeColor(beforeIter->color *(abs(pos - afterIter->position.first) / dist) + afterIter->color *(abs(pos - beforeIter->position.first) / dist)),
beforeIter->position.second *(abs(pos - afterIter->position.first) / dist) + afterIter->position.second *(abs(pos - beforeIter->position.first) / dist) };
return color;
}
int EnvelopePoint::HexadecimalToDecimal(std::string hex) const {
int hexLength = hex.length();
double dec = 0;
for (int i = 0; i < hexLength; ++i)
{
char b = hex[i];
if (b >= 48 && b <= 57)
b -= 48;
else if (b >= 65 && b <= 70)
b -= 55;
else if (b >= 97 && b <= 102)
b -= 87;
dec += b * pow(16, ((hexLength - i) - 1));
}
return (int)dec;
}
std::string EnvelopePoint::DecimalToHexadecimal(int dec) const {
if (dec < 1) return "00";
int hex = dec;
std::string hexStr = "";
while (dec > 0)
{
hex = dec % 16;
if (hex < 10)
hexStr = hexStr.insert(0, std::string(1, (hex + 48)));
else
hexStr = hexStr.insert(0, std::string(1, (hex + 55)));
dec /= 16;
}
return hexStr;
}
glm::vec3 EnvelopePoint::hexadecimalToRGBConversion(std::string hex) const {
float r = static_cast<float>(HexadecimalToDecimal(hex.substr(1, 2)));
float g = static_cast<float>(HexadecimalToDecimal(hex.substr(3, 2)));
float b = static_cast<float>(HexadecimalToDecimal(hex.substr(5, 2)));
return glm::vec3(r, g, b);
}
std::string EnvelopePoint::getHexadecimalFromVec3(glm::vec3 vec) const {
std::string r = DecimalToHexadecimal(static_cast<int>(vec.r));
std::string g = DecimalToHexadecimal(static_cast<int>(vec.g));
std::string b = DecimalToHexadecimal(static_cast<int>(vec.b));
return ("#" + r + g + b);
}
json Envelope::getJSONPoints() const {
json j;
for (int i = 0; i < _points.size(); i++) {
j[i] = {
{ "color", _points.at(i).colorHex },
{ "position",{
{ "x", _points.at(i).position.first },
{ "y", _points.at(i).position.second },
},
}
};
}
return j;
}
json Envelope::getJSONEnvelope() const {
json j;
j["points"] = getJSONPoints();
return j;
}
void Envelope::setEnvelopeLuaTable(lua_State* state) const {
for (auto iter = _points.begin(); iter != _points.end(); ++iter) {
lua_newtable(state);
lua_pushstring(state, iter->colorHex.c_str());
lua_setfield(state, -2, "color");
lua_newtable(state);
lua_pushnumber(state, static_cast<lua_Number>(iter->position.first));
lua_setfield(state, -2, "x");
lua_pushnumber(state, static_cast<lua_Number>(iter->position.second));
lua_setfield(state, -2, "y");
lua_setfield(state, -2, "position");
lua_setfield(state, -2, ("[\"" + std::to_string(iter - _points.begin() + 1) + "\"]").c_str());
}
}
}//namespace volume
}//namespace openspace
+77
View File
@@ -0,0 +1,77 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef __OPENSPACE_MODULE_VOLUME___ENVELOPE___H__
#define __OPENSPACE_MODULE_VOLUME___ENVELOPE___H__
#include <ghoul/opengl/texture.h>
#include <ghoul/glm.h>
#include <ext/json/json.hpp>
#include <ghoul/lua/ghoul_lua.h>
using json = nlohmann::json;
namespace openspace {
namespace volume {
class EnvelopePoint {
public:
EnvelopePoint(glm::vec3 c, float x, float y) : color(c), colorHex(getHexadecimalFromVec3(c)), position(std::make_pair(x, y)) {}
EnvelopePoint(std::string c, float x, float y) : color(hexadecimalToRGBConversion(c)), colorHex(c), position(std::make_pair(x, y)) {}
int HexadecimalToDecimal(std::string hex) const;
std::string DecimalToHexadecimal(int dec) const;
glm::vec3 hexadecimalToRGBConversion(std::string hex) const;
std::string getHexadecimalFromVec3(glm::vec3 vec) const;
glm::vec3 color;
std::string colorHex;
std::pair<float, float> position;
};
class Envelope {
public:
Envelope();
Envelope(std::vector<EnvelopePoint> vec);
void setPoints(std::vector<EnvelopePoint> vec);
std::vector<EnvelopePoint> getPoints();
glm::vec4 getValueAtPosition(float pos) const;
glm::vec3 normalizeColor(glm::vec3 vec) const;
json getJSONPoints() const;
json getJSONEnvelope() const;
void setEnvelopeLuaTable(lua_State* state) const;
bool isValueInEnvelope(float pos) const;
bool isEnvelopeValid() const;
bool operator!=(const Envelope& env) const;
private:
std::vector<EnvelopePoint> _points;
};
}//namespace volume
}//namespace openspace
#endif __OPENSPACE_MODULE_VOLUME___ENVELOPE___H__
@@ -26,6 +26,7 @@
#include <ghoul/glm.h>
#include <ghoul/opengl/ghoul_gl.h>
#include <ghoul/filesystem/filesystem.h>
#include <sstream>
#include <ghoul/opengl/programobject.h>
#include <ghoul/opengl/textureunit.h>
@@ -43,19 +44,19 @@ namespace {
namespace openspace::volume {
BasicVolumeRaycaster::BasicVolumeRaycaster(
std::shared_ptr<ghoul::opengl::Texture> volumeTexture,
std::shared_ptr<TransferFunction> transferFunction,
std::shared_ptr<VolumeClipPlanes> clipPlanes)
: _clipPlanes(clipPlanes)
, _volumeTexture(volumeTexture)
, _transferFunction(transferFunction)
std::shared_ptr<ghoul::opengl::Texture> volumeTexture,
std::shared_ptr<TransferFunctionHandler> transferFunctionHandler,
std::shared_ptr<VolumeClipPlanes> clipPlanes)
: _volumeTexture(volumeTexture)
, _transferFunctionHandler(transferFunctionHandler)
, _clipPlanes(clipPlanes)
, _boundingBox(glm::vec3(1.0))
, _opacity(20.0)
, _rNormalization(0.0)
, _rUpperBound(1.0)
, _valueRemapping(0.0, 1.0)
{}
BasicVolumeRaycaster::~BasicVolumeRaycaster() {}
void BasicVolumeRaycaster::initialize() {
@@ -111,7 +112,7 @@ void BasicVolumeRaycaster::preRaycast(
const RaycastData& data,
ghoul::opengl::ProgramObject& program)
{
if (!_volumeTexture || !_transferFunction) {
if (!_volumeTexture || !_transferFunctionHandler) {
return;
}
@@ -122,7 +123,7 @@ void BasicVolumeRaycaster::preRaycast(
_tfUnit = std::make_unique<ghoul::opengl::TextureUnit>();
_tfUnit->activate();
_transferFunction->getTexture().bind();
_transferFunctionHandler->getTexture().bind();
program.setUniform("transferFunction_" + id, _tfUnit->unitNumber());
_textureUnit = std::make_unique<ghoul::opengl::TextureUnit>();
@@ -142,7 +143,6 @@ void BasicVolumeRaycaster::preRaycast(
program.setUniform("opacity_" + id, _opacity);
program.setUniform("rNormalization_" + id, _rNormalization);
program.setUniform("rUpperBound_" + id, _rUpperBound);
program.setUniform("valueRemapping_" + id, _valueRemapping);
}
void BasicVolumeRaycaster::postRaycast(const RaycastData&, ghoul::opengl::ProgramObject&)
@@ -166,25 +166,26 @@ bool BasicVolumeRaycaster::cameraIsInside(const RenderData& data,
}
std::string BasicVolumeRaycaster::getBoundsVsPath() const {
return GlslBoundsVsPath;
return absPath(GlslBoundsVsPath);
}
std::string BasicVolumeRaycaster::getBoundsFsPath() const {
return GlslBoundsFsPath;
return absPath(GlslBoundsFsPath);
}
std::string BasicVolumeRaycaster::getRaycastPath() const {
return GlslRaycastPath;
return absPath(GlslRaycastPath);
}
std::string BasicVolumeRaycaster::getHelperPath() const {
return GlslHelperPath;
return absPath(GlslHelperPath);
}
void BasicVolumeRaycaster::setTransferFunction(
std::shared_ptr<TransferFunction> transferFunction)
void BasicVolumeRaycaster::setTransferFunctionHandler(
std::shared_ptr<TransferFunctionHandler> transferFunctionHandler)
{
_transferFunction = transferFunction;
_transferFunctionHandler = transferFunctionHandler;
}
void BasicVolumeRaycaster::setVolumeTexture(
@@ -225,10 +226,6 @@ float BasicVolumeRaycaster::rUpperBound() const {
return _rUpperBound;
}
void BasicVolumeRaycaster::setValueRemapping(float mapZeroTo, float mapOneTo) {
_valueRemapping = glm::vec2(mapZeroTo, mapOneTo);
}
VolumeGridType BasicVolumeRaycaster::gridType() const {
return _gridType;
}
@@ -241,4 +238,5 @@ void BasicVolumeRaycaster::setModelTransform(const glm::mat4 & transform) {
_modelTransform = transform;
}
} // namespace openspace::volume
@@ -34,7 +34,7 @@
#include <openspace/rendering/volumeraycaster.h>
#include <openspace/util/boxgeometry.h>
#include <openspace/rendering/transferfunction.h>
#include <modules/volume/transferfunctionhandler.h>
#include <modules/volume/rendering/volumeclipplanes.h>
#include <modules/volume/volumegridtype.h>
@@ -56,7 +56,7 @@ class BasicVolumeRaycaster : public VolumeRaycaster {
public:
BasicVolumeRaycaster(
std::shared_ptr<ghoul::opengl::Texture> texture,
std::shared_ptr<TransferFunction> transferFunction,
std::shared_ptr<TransferFunctionHandler> transferFunctionHandler,
std::shared_ptr<VolumeClipPlanes> clipPlanes);
virtual ~BasicVolumeRaycaster();
void initialize();
@@ -77,9 +77,11 @@ public:
std::string getRaycastPath() const override;
std::string getHelperPath() const override;
void setVolumeTexture(std::shared_ptr<ghoul::opengl::Texture> texture);
std::shared_ptr<ghoul::opengl::Texture> volumeTexture() const;
void setTransferFunction(std::shared_ptr<TransferFunction> transferFunction);
void setTransferFunctionHandler(std::shared_ptr<TransferFunctionHandler> transferFunctionHandler);
void setStepSize(float stepSize);
float opacity() const;
void setOpacity(float opacity);
@@ -87,7 +89,6 @@ public:
void setRNormalization(float rNormalization);
float rUpperBound() const;
void setRUpperBound(float rNormalization);
void setValueRemapping(float mapZeroTo, float mapOneTo);
VolumeGridType gridType() const;
void setGridType(VolumeGridType gridType);
void setModelTransform(const glm::mat4& transform);
@@ -97,14 +98,13 @@ private:
std::shared_ptr<VolumeClipPlanes> _clipPlanes;
std::shared_ptr<ghoul::opengl::Texture> _volumeTexture;
std::shared_ptr<TransferFunction> _transferFunction;
std::shared_ptr<TransferFunctionHandler> _transferFunctionHandler;
BoxGeometry _boundingBox;
VolumeGridType _gridType;
glm::mat4 _modelTransform;
float _opacity;
float _rNormalization;
float _rUpperBound;
glm::vec2 _valueRemapping;
std::unique_ptr<ghoul::opengl::TextureUnit> _tfUnit;
std::unique_ptr<ghoul::opengl::TextureUnit> _textureUnit;
@@ -113,6 +113,4 @@ private:
} // namespace volume
} // namespace openspace
#endif // __OPENSPACE_MODULE_VOLUME___BASICVOLUMERAYCASTER___H__
@@ -53,8 +53,6 @@ namespace {
const char* KeySourceDirectory = "SourceDirectory";
const char* KeyLowerDomainBound = "LowerDomainBound";
const char* KeyUpperDomainBound = "UpperDomainBound";
const char* KeyLowerValueBound = "LowerValueBound";
const char* KeyUpperValueBound = "UpperValueBound";
const char* KeyClipPlanes = "ClipPlanes";
const char* KeySecondsBefore = "SecondsBefore";
const char* KeySecondsAfter = "SecondsAfter";
@@ -62,6 +60,7 @@ namespace {
const char* KeyMinValue = "MinValue";
const char* KeyMaxValue = "MaxValue";
const char* KeyTime = "Time";
const char* KeyUnit = "VisUnit";
const float SecondsInOneDay = 60 * 60 * 24;
static const openspace::properties::Property::PropertyInfo StepSizeInfo = {
@@ -165,13 +164,12 @@ RenderableTimeVaryingVolume::RenderableTimeVaryingVolume(
, _secondsAfter(SecondsAfterInfo, 0.f, 0.01f, SecondsInOneDay)
, _sourceDirectory(SourceDirectoryInfo)
, _transferFunctionPath(TransferFunctionInfo)
, _lowerValueBound(lowerValueBoundInfo, 0.f, 0.f, 1000000.f)
, _upperValueBound(upperValueBoundInfo, 0.f, 0.f, 1000000.f)
, _triggerTimeJump(TriggerTimeJumpInfo)
, _jumpToTimestep(JumpToTimestepInfo, 0, 0, 256)
, _currentTimestep(CurrentTimeStepInfo, 0, 0, 256)
, _raycaster(nullptr)
, _transferFunction(nullptr)
, _transferFunctionHandler(nullptr)
{
documentation::testSpecificationAndThrow(
Documentation(),
@@ -181,9 +179,8 @@ RenderableTimeVaryingVolume::RenderableTimeVaryingVolume(
_sourceDirectory = absPath(dictionary.value<std::string>(KeySourceDirectory));
_transferFunctionPath = absPath(dictionary.value<std::string>(KeyTransferFunction));
_lowerValueBound = dictionary.value<float>(KeyLowerValueBound);
_upperValueBound = dictionary.value<float>(KeyUpperValueBound);
_transferFunction = std::make_shared<TransferFunction>(_transferFunctionPath);
_transferFunctionHandler = std::make_shared<TransferFunctionHandler>(_transferFunctionPath);
_gridType.addOptions({
{ static_cast<int>(volume::VolumeGridType::Cartesian), "Cartesian grid" },
@@ -236,6 +233,9 @@ void RenderableTimeVaryingVolume::initializeGL() {
if (extension == "dictionary") {
loadTimestepMetadata(path);
}
if (extension == "tf") {
_transferFunctionHandler->setFilepath(path);
}
}
@@ -250,11 +250,16 @@ void RenderableTimeVaryingVolume::initializeGL() {
float min = t.minValue;
float diff = t.maxValue - t.minValue;
float *data = t.rawVolume->data();
for (size_t i = 0; i < t.rawVolume->nCells(); ++i) {
data[i] = glm::clamp((data[i] - min) / diff, 0.0f, 1.0f);
}
t.histogram = std::make_shared<Histogram>(0.0, 1.0, 100);
for (int i = 0; i < t.rawVolume->nCells(); ++i) {
t.histogram->add(data[i]);
}
// TODO: handle normalization properly for different timesteps + transfer function
t.texture = std::make_shared<ghoul::opengl::Texture>(
@@ -273,13 +278,11 @@ void RenderableTimeVaryingVolume::initializeGL() {
t.texture->uploadTexture();
}
_transferFunctionHandler->initialize();
_clipPlanes->initialize();
_transferFunction->update();
_raycaster = std::make_unique<volume::BasicVolumeRaycaster>(
nullptr,
_transferFunction,
_clipPlanes
);
_raycaster = std::make_unique<volume::BasicVolumeRaycaster>(nullptr, _transferFunctionHandler, _clipPlanes);
_raycaster->initialize();
OsEng.renderEngine().raycasterManager().attachRaycaster(*_raycaster.get());
auto onChange = [&](bool enabled) {
@@ -309,14 +312,14 @@ void RenderableTimeVaryingVolume::initializeGL() {
addProperty(_transferFunctionPath);
addProperty(_sourceDirectory);
addPropertySubOwner(_clipPlanes.get());
addPropertySubOwner(_transferFunctionHandler.get());
addProperty(_triggerTimeJump);
addProperty(_jumpToTimestep);
addProperty(_currentTimestep);
addProperty(_opacity);
addProperty(_rNormalization);
addProperty(_rUpperBound);
addProperty(_lowerValueBound);
addProperty(_upperValueBound);
_raycaster->setGridType(
(_gridType.value() == 1) ?
@@ -332,9 +335,9 @@ void RenderableTimeVaryingVolume::initializeGL() {
});
_transferFunctionPath.onChange([this] {
_transferFunction =
std::make_shared<TransferFunction>(_transferFunctionPath);
_raycaster->setTransferFunction(_transferFunction);
_transferFunctionHandler =
std::make_shared<TransferFunctionHandler>(_transferFunctionPath);
_raycaster->setTransferFunctionHandler(_transferFunctionHandler);
});
}
@@ -353,6 +356,7 @@ void RenderableTimeVaryingVolume::loadTimestepMetadata(const std::string& path)
t.upperDomainBound = dictionary.value<glm::vec3>(KeyUpperDomainBound);
t.minValue = dictionary.value<float>(KeyMinValue);
t.maxValue = dictionary.value<float>(KeyMaxValue);
t.unit = dictionary.value<std::string>(KeyUnit);
std::string timeString = dictionary.value<std::string>(KeyTime);
t.time = Time::convertTime(timeString);
@@ -430,7 +434,6 @@ void RenderableTimeVaryingVolume::jumpToTimestep(int target) {
}
void RenderableTimeVaryingVolume::update(const UpdateData&) {
_transferFunction->update();
if (_raycaster) {
Timestep* t = currentTimestep();
_currentTimestep = timestepIndex(t);
@@ -453,18 +456,9 @@ void RenderableTimeVaryingVolume::update(const UpdateData&) {
);
}
_raycaster->setVolumeTexture(t->texture);
// Remap volume value to that TF value 0 is sampled for lowerValueBound, and 1
// is sampled for upperLowerBound.
// This means that volume values = 0 need to be remapped to how localMin
// relates to the global range.
float zeroMap = (t->minValue - _lowerValueBound) /
(_upperValueBound - _lowerValueBound);
// Volume values = 1 are mapped to how localMax relates to the global range.
float oneMap = (t->maxValue - _lowerValueBound) /
(_upperValueBound - _lowerValueBound);
_raycaster->setValueRemapping(zeroMap, oneMap);
_transferFunctionHandler->setUnit(t->unit);
_transferFunctionHandler->setMinAndMaxValue(t->minValue, t->maxValue);
_transferFunctionHandler->setHistogramProperty(t->histogram);
} else {
_raycaster->setVolumeTexture(nullptr);
}
@@ -510,20 +504,6 @@ documentation::Documentation RenderableTimeVaryingVolume::Documentation() {
Optional::No,
"Specifies the transfer function file path"
},
{
KeyLowerValueBound,
new DoubleVerifier,
Optional::No,
"Specifies the lower value bound."
"This number will be mapped to 0 before uploadin to the GPU."
},
{
KeyUpperValueBound,
new DoubleVerifier,
Optional::No,
"Specifies the lower value bound."
"This number will be mapped to 0 before uploadin to the GPU."
},
{
KeyGridType,
new StringInListVerifier({"Cartesian", "Spherical"}),
@@ -30,12 +30,14 @@
#include <modules/volume/rawvolume.h>
#include <modules/volume/rendering/basicvolumeraycaster.h>
#include <modules/volume/rendering/volumeclipplanes.h>
#include <modules/volume/transferfunctionhandler.h>
#include <openspace/properties/vectorproperty.h>
#include <openspace/properties/optionproperty.h>
#include <openspace/properties/stringproperty.h>
#include <openspace/rendering/transferfunction.h>
#include <openspace/util/boxgeometry.h>
#include <openspace/util/histogram.h>
namespace openspace {
@@ -66,10 +68,12 @@ private:
glm::uvec3 dimensions;
glm::vec3 lowerDomainBound;
glm::vec3 upperDomainBound;
std::string unit;
bool inRam;
bool onGpu;
std::unique_ptr<RawVolume<float>> rawVolume;
std::shared_ptr<ghoul::opengl::Texture> texture;
std::shared_ptr<openspace::Histogram> histogram;
};
Timestep* currentTimestep();
@@ -90,8 +94,6 @@ private:
properties::FloatProperty _secondsAfter;
properties::StringProperty _sourceDirectory;
properties::StringProperty _transferFunctionPath;
properties::FloatProperty _lowerValueBound;
properties::FloatProperty _upperValueBound;
properties::TriggerProperty _triggerTimeJump;
properties::IntProperty _jumpToTimestep;
@@ -100,7 +102,8 @@ private:
std::map<double, Timestep> _volumeTimesteps;
std::unique_ptr<BasicVolumeRaycaster> _raycaster;
std::shared_ptr<TransferFunction> _transferFunction;
std::shared_ptr<TransferFunctionHandler> _transferFunctionHandler;
};
} // namespace volume
-6
View File
@@ -33,10 +33,6 @@ uniform vec2 clipOffsets_#{id}[8];
uniform float opacity_#{id} = 10.0;
// Value remapping:
// Linearly remap volume values of zero to x and one to y
// before using the values to sample the transfer function.
uniform vec2 valueRemapping_#{id} = vec2(0.0, 1.0);
// Normalization factor x for radius r [0, 1].
// value *= 1/(r^x)
@@ -71,8 +67,6 @@ void sample#{id}(vec3 samplePos, vec3 dir, inout vec3 accumulatedColor,
if (clipAlpha > 0) {
float val = texture(volumeTexture_#{id}, transformedPos).r;
val = mix(valueRemapping_#{id}.x, valueRemapping_#{id}.y, val);
if (rNormalization_#{id} > 0 && gridType_#{id} == 1) {
val *= pow(transformedPos.x, rNormalization_#{id});
}
+243
View File
@@ -0,0 +1,243 @@
/****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/volume/transferfunction.h>
#include <ghoul/misc/dictionary.h>
#include <ext/json/json.hpp>
#include <memory>
#include <iostream>
#include <fstream>
#include <ghoul/misc/dictionaryluaformatter.h>
#include <ghoul/filesystem/filesystem.h>
using json = nlohmann::json;
namespace openspace {
namespace volume {
TransferFunction::TransferFunction() {
}
TransferFunction::TransferFunction(int s) {
}
TransferFunction::TransferFunction(std::string s) {
setEnvelopesFromString(s);
}
TransferFunction::TransferFunction(const TransferFunction& tf) : _envelopes(tf._envelopes), _loadableFilePath(tf._loadableFilePath) { }
TransferFunction::TransferFunction(TransferFunction&& tf) : _envelopes(std::move(tf._envelopes)), _loadableFilePath(std::move(tf._loadableFilePath)) { }
TransferFunction& TransferFunction::operator=(const TransferFunction& tf) {
_envelopes = tf._envelopes;
_loadableFilePath = tf._loadableFilePath;
return *this;
}
TransferFunction& TransferFunction::operator=(TransferFunction&& tf) {
_envelopes = std::move(tf._envelopes);
_loadableFilePath = std::move(tf._loadableFilePath);
return *this;
}
bool TransferFunction::setEnvelopesFromString(std::string s) {
json j = json::parse(s);
for (json::iterator it = j.begin(); it != j.end(); ++it) {
Envelope env;
std::vector < EnvelopePoint> tmpVec;
for (size_t i = 0; i < 4; i++) {
std::string color = (*it)["points"][i]["color"].get<std::string>();
float x_value = (*it)["points"][i]["position"]["x"].get<float>();
float y_value = (*it)["points"][i]["position"]["y"].get<float>();
tmpVec.emplace_back(color, x_value, y_value);
}
env.setPoints(tmpVec);
_envelopes.emplace_back(env);
}
return true;
}
//TODO, implement this
bool TransferFunction::setEnvelopesFromLua(lua_State* state) {
bool success = (lua_istable(state, -1) == 1);
if (success) {
lua_pushnil(state);
while (lua_next(state, -2)) {
Envelope env;
std::vector<EnvelopePoint> tmpVec;
/*lua_pushnil(state);
while (lua_next(state, -2)) {
lua_pushnil(state);
while (lua_next(state, -2)) {
PrintTable(state);
std::string color = static_cast<std::string>(lua_tostring(state, -1));
lua_pop(state, 1);
lua_pushnil(state);
lua_next(state, -2);
float x_value = static_cast<float>(lua_tonumber(state, -1));
lua_pop(state, 1);
lua_next(state, -2);
float y_value = static_cast<float>(lua_tonumber(state, -1));
lua_pop(state, 1);
tmpVec.emplace_back(color, x_value, y_value);
lua_pop(state, 1);
}
}*/
lua_pop(state, 2);
}
lua_pop(state, 1);
}
return success;
}
bool TransferFunction::getEnvelopesToLua(lua_State* state) {
lua_newtable(state);
for (auto iter = _envelopes.begin(); iter != _envelopes.end(); ++iter) {
lua_newtable(state);
iter->setEnvelopeLuaTable(state);
lua_setfield(state, -2, ("[\"" + std::to_string(iter - _envelopes.begin() + 1) + "\"]").c_str());
}
return true;
}
void TransferFunction::loadEnvelopesFromFile(const std::string& path) {
lua_State* L = luaL_newstate();
std::string absFilename = absPath(path);
ghoul::Dictionary dictionary;
ghoul::lua::loadDictionaryFromFile(path, dictionary, L);
std::vector<std::string> transferfunctionKeys = dictionary.keys();
for (auto transferfunctionKey : transferfunctionKeys) {
ghoul::Dictionary transferfunctionDictionary = dictionary.value<ghoul::Dictionary>(transferfunctionKey);
std::vector<std::string> envelopeKeys = transferfunctionDictionary.keys();
for (auto envelopeKey : envelopeKeys) {
ghoul::Dictionary envelopeDictionary = transferfunctionDictionary.value<ghoul::Dictionary>(envelopeKey);
std::vector<std::string> pointKeys = envelopeDictionary.keys();
Envelope env;
std::vector < EnvelopePoint> tmpVec;
for (auto pointKey : pointKeys) {
ghoul::Dictionary pointDictionary = envelopeDictionary.value<ghoul::Dictionary>(pointKey);
std::string color = pointDictionary.value<std::string>("color");
ghoul::Dictionary positionDictionary = pointDictionary.value<ghoul::Dictionary>("position");
float posX = positionDictionary.value<float>("x");
float posY = positionDictionary.value<float>("y");
tmpVec.emplace_back(color, posX, posY);
}
env.setPoints(tmpVec);
_envelopes.emplace_back(env);
}
}
}
void TransferFunction::saveEnvelopesToFile(const std::string& path) {
ghoul::Dictionary dictionary;
lua_State* state = luaL_newstate();
getEnvelopesToLua(state);
ghoul::lua::luaDictionaryFromState(state, dictionary);
ghoul::DictionaryLuaFormatter formatter;
std::ofstream tfFile;
tfFile.open(path);
tfFile << "return {";
tfFile << formatter.format(dictionary);
tfFile << "}";
tfFile.close();
}
bool TransferFunction::operator!=(const TransferFunction& tf) {
if (_envelopes.size() != tf._envelopes.size())
return true;
if (_loadableFilePath != tf._loadableFilePath)
return true;
auto iter = _envelopes.begin();
auto tfIter = tf._envelopes.begin();
for (; iter != _envelopes.end(); ++iter, ++tfIter) {
if (*iter != *tfIter)
return true;
}
return false;
}
bool TransferFunction::hasEnvelopes() const {
return !_envelopes.empty();
}
std::string TransferFunction::getSerializedToString() const {
if (_envelopes.empty())
return "";
json j;
auto envIter = _envelopes.begin();
for (; envIter != _envelopes.end(); ++envIter) {
j[std::distance(_envelopes.begin(), envIter)] = { envIter->getJSONEnvelope() };
}
return j.dump();
}
bool TransferFunction::createTexture(std::shared_ptr<ghoul::opengl::Texture> ptr) {
if (_envelopes.empty()) {
return false;
}
else {
float* transferFunction = new float[_width * 4]();
for (int i = 0; i < 4 * _width; ++i) {
transferFunction[i] = 0.0f;
}
for (size_t i = 0; i <= (_width - 1); i++) {
float position = static_cast<float>(i) / static_cast<float>(_width);
int count = 0;
glm::vec4 rgbFromEnvelopes{0.f, 0.f, 0.f, 0.f};
float alpha = 0.f;
for (auto iter = _envelopes.begin(); iter != _envelopes.end(); ++iter) {
if (iter->isValueInEnvelope(position) && iter->isEnvelopeValid()) {
count++;
glm::vec4 tmp = iter->getValueAtPosition(position);
rgbFromEnvelopes.r += tmp.r * tmp.a;
rgbFromEnvelopes.g += tmp.g * tmp.a;
rgbFromEnvelopes.b += tmp.b * tmp.a;
if (alpha < tmp.a)
alpha = tmp.a;
}
}
rgbFromEnvelopes /= static_cast<float>(count == 0 ? 1 : count);
rgbFromEnvelopes.w = alpha;
for (size_t channel = 0; channel < 4; ++channel) {
size_t position = 4 * i + channel;
float value = rgbFromEnvelopes[channel];
transferFunction[position] = value;
}
}
ptr->setPixelData(transferFunction);
return true;
}
}
}
}
+69
View File
@@ -0,0 +1,69 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef __OPENSPACE_MODULE_VOLUME___TRANSFERFUNCTION___H__
#define __OPENSPACE_MODULE_VOLUME___TRANSFERFUNCTION___H__
#include <ghoul/glm.h>
#include <modules/volume/envelope.h>
namespace ghoul { class Dictionary; }
namespace openspace {
namespace volume {
class TransferFunction {
public:
TransferFunction();
TransferFunction(int s);
TransferFunction(std::string);
TransferFunction(const TransferFunction& tf);
TransferFunction(TransferFunction&& tf);
bool getEnvelopesToLua(lua_State* state);
bool setEnvelopesFromString(std::string s);
bool setEnvelopesFromLua(lua_State* lua);
void loadEnvelopesFromFile(const std::string& path);
void saveEnvelopesToFile(const std::string& path);
TransferFunction& operator=(const TransferFunction& tf);
TransferFunction& operator=(TransferFunction&& tf);
bool operator!=(const TransferFunction& tf);
bool hasEnvelopes() const;
bool createTexture(std::shared_ptr<ghoul::opengl::Texture> ptr);
std::string getSerializedToString() const;
private:
int _width = 1024;
double lower = 0.0;
double upper = 1.0;
std::string _loadableFilePath;
std::vector<Envelope> _envelopes;
};
}//namespace volume
}//namespace openspace
#endif __OPENSPACE_MODULE_VOLUME___TRANSFERFUNCTION___H__
+180
View File
@@ -0,0 +1,180 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/volume/transferfunctionhandler.h>
#include <ghoul/misc/dictionary.h>
#include <openspace/properties/scalarproperty.h>
#include <iostream>
#include <fstream>
#include <ghoul/opengl/ghoul_gl.h>
#include <ghoul/filesystem/filesystem.h>
static const openspace::properties::Property::PropertyInfo TransferFunctionInfo = {
"TransferFunction",
"TransferFunction",
"All the envelopes used in the transfer function"
};
static const openspace::properties::Property::PropertyInfo HistogramInfo = {
"Histogram",
"Histogram",
"All the data"
};
static const openspace::properties::Property::PropertyInfo DataUnitInfo = {
"DataUnit",
"DataUnit",
"Unit of the data"
};
static const openspace::properties::Property::PropertyInfo MinValueInfo = {
"MinValue",
"MinValue",
"Minimum value in the data"
};
static const openspace::properties::Property::PropertyInfo MaxValueInfo = {
"MaxValue",
"MaxValue",
"Maximum value in the data"
};
static const openspace::properties::Property::PropertyInfo SaveTransferFunctionInfo = {
"SaveTransferFunction",
"Save Transfer Function",
"Save your transfer function"
};
namespace openspace {
namespace volume {
ghoul::opengl::Texture::FilterMode filtermode = ghoul::opengl::Texture::FilterMode::Linear;
ghoul::opengl::Texture::WrappingMode wrappingmode = ghoul::opengl::Texture::WrappingMode::ClampToEdge;
TransferFunctionHandler::TransferFunctionHandler(const properties::StringProperty& prop)
: properties::PropertyOwner({ "TransferFunctionHandler" }),
_transferFunctionPath(prop),
_transferFunctionProperty(TransferFunctionInfo),
_dataUnit(DataUnitInfo),
_minValue(MinValueInfo),
_maxValue(MaxValueInfo),
_histogramProperty(HistogramInfo),
_saveTransferFunction(SaveTransferFunctionInfo)
{
_transferFunction = std::make_shared<openspace::TransferFunction>(_transferFunctionPath);
}
void TransferFunctionHandler::initialize() {
addProperty(_transferFunctionPath);
addProperty(_transferFunctionProperty);
addProperty(_histogramProperty);
addProperty(_dataUnit);
addProperty(_minValue);
addProperty(_maxValue);
addProperty(_saveTransferFunction);
this->addTag("TF");
_texture = std::make_shared<ghoul::opengl::Texture>(
glm::size3_t(1024, 1, 1), ghoul::opengl::Texture::Format::RGBA,
GL_RGBA, GL_FLOAT, filtermode, wrappingmode);
if (_filePath != "") {
loadStoredEnvelopes();
}
_transferFunctionProperty.onChange([this]() {
setTexture();
});
_saveTransferFunction.onChange([this]() {
saveEnvelopes();
});
}
void TransferFunctionHandler::setHistogramProperty(std::shared_ptr<openspace::Histogram> histogram) {
_histogramProperty.setValue(histogram->getBinaryData());
}
void TransferFunctionHandler::setTexture() {
if (_transferFunctionProperty.value().createTexture(_texture)) {
uploadTexture();
useTxtTexture = false;
}
}
void TransferFunctionHandler::setUnit(const std::string& unit) {
_dataUnit.set(unit);
}
void TransferFunctionHandler::setMinAndMaxValue(const float& min, const float& max) {
std::stringstream s_min;
s_min << min;
std::string s = s_min.str();
_minValue.set(s);
std::stringstream s_max;
s_max << max;
std::string t = s_max.str();
_maxValue.set(t);
}
void TransferFunctionHandler::loadStoredEnvelopes() {
TransferFunction tf;
tf.loadEnvelopesFromFile(_filePath);
if (tf.hasEnvelopes()) {
_transferFunctionProperty.setValue(tf);
setTexture();
}
}
void TransferFunctionHandler::saveEnvelopes() {
_transferFunctionProperty.value().saveEnvelopesToFile(_filePath);
}
void TransferFunctionHandler::setFilepath(const std::string& path) {
_filePath = path;
}
ghoul::opengl::Texture& TransferFunctionHandler::getTexture() {
return *_texture.get();
}
void TransferFunctionHandler::uploadTexture() {
_texture->uploadTexture();
}
bool TransferFunctionHandler::hasTexture() {
if (_texture == nullptr)
return false;
return true;
}
std::shared_ptr<openspace::TransferFunction> TransferFunctionHandler::getTransferFunction() {
return _transferFunction;
}
} //namespace volume
} // namespace openspace
+86
View File
@@ -0,0 +1,86 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef __OPENSPACE_MODULE_VOLUME___TRANSFERFUNCTIONHANDLER___H__
#define __OPENSPACE_MODULE_VOLUME___TRANSFERFUNCTIONHANDLER___H__
#include <functional>
#include <ghoul/opengl/texture.h>
#include <ghoul/glm.h>
#include <openspace/properties/propertyowner.h>
#include <openspace/properties/triggerproperty.h>
#include <openspace/properties/stringproperty.h>
#include <openspace/properties/binaryproperty.h>
#include <openspace/properties/scalarproperty.h>
#include <openspace/util/histogram.h>
#include <modules/volume/transferfunctionproperty.h>
#include <modules/volume/transferfunction.h>
#include <openspace/rendering/transferfunction.h>
#include <vector>
#include <memory>
namespace openspace {
namespace volume {
class Envelope;
class TransferFunctionHandler : public properties::PropertyOwner{
public:
TransferFunctionHandler(const properties::StringProperty& prop);
void initialize();
void setHistogramProperty(std::shared_ptr<openspace::Histogram> histogram);
void setTexture();
void loadStoredEnvelopes();
void saveEnvelopes();
void setFilepath(const std::string& path);
void setUnit(const std::string& unit);
void setMinAndMaxValue(const float& min, const float& max);
ghoul::opengl::Texture& getTexture();
void uploadTexture();
bool hasTexture();
std::shared_ptr<openspace::TransferFunction> getTransferFunction();
private:
bool useTxtTexture = true;
properties::StringProperty _transferFunctionPath;
properties::StringProperty _dataUnit;
properties::StringProperty _minValue;
properties::StringProperty _maxValue;
properties::TriggerProperty _saveTransferFunction;
std::string _filePath;
properties::TransferFunctionProperty _transferFunctionProperty;
properties::BinaryProperty _histogramProperty;
std::shared_ptr<openspace::TransferFunction> _transferFunction;
std::shared_ptr<ghoul::opengl::Texture> _texture = nullptr;
};
}//namespace volume
}//namespace openspace
#endif __OPENSPACE_MODULE_VOLUME___TRANSFERFUNCTIONHANDLER___H__
@@ -0,0 +1,64 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/volume/transferfunctionproperty.h>
#include <ghoul/lua/ghoul_lua.h>
namespace openspace::properties {
#define DEFAULT_FROM_LUA_LAMBDA(TYPE, DEFAULT_VALUE) \
[](lua_State* state, bool& success) -> TYPE { \
TYPE TF; \
success = true; \
TF.setEnvelopesFromLua(state); \
return TF; \
}
#define DEFAULT_TO_LUA_LAMBDA(TYPE) \
[](lua_State* state, TYPE value) -> bool { \
bool success = value.getEnvelopesToLua(state); \
return success; \
}
#define DEFAULT_FROM_STRING_LAMBDA(TYPE, DEFAULT_VALUE) \
[](std::string val, bool& success) -> TYPE { \
TYPE TF; \
success = TF.setEnvelopesFromString(val); \
return TF; \
}
#define DEFAULT_TO_STRING_LAMBDA(TYPE) \
[](std::string& outValue, TYPE inValue) -> bool { \
outValue = inValue.getSerializedToString(); \
return true; \
}
REGISTER_TEMPLATEPROPERTY_SOURCE(TransferFunctionProperty, volume::TransferFunction, 0,
DEFAULT_FROM_LUA_LAMBDA(volume::TransferFunction, volume::TransferFunction(0)),
DEFAULT_TO_LUA_LAMBDA(volume::TransferFunction),
DEFAULT_FROM_STRING_LAMBDA(volume::TransferFunction, volume::TransferFunction(0)),
DEFAULT_TO_STRING_LAMBDA(volume::TransferFunction),
LUA_TTABLE);
} // namespace openspace::properties
+37
View File
@@ -0,0 +1,37 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef __OPENSPACE_CORE___TRANSFERFUNCTIONPROPERTY___H__
#define __OPENSPACE_CORE___TRANSFERFUNCTIONPROPERTY___H__
#include <openspace/properties/templateproperty.h>
#include <modules/volume/transferfunction.h>
namespace openspace::properties {
REGISTER_TEMPLATEPROPERTY_HEADER(TransferFunctionProperty, volume::TransferFunction)
} // namespace openspace::properties
#endif // __OPENSPACE_CORE___TRANSFERFUNCTIONPROPERTY___H__
+1
View File
@@ -0,0 +1 @@
ext
+216
View File
@@ -0,0 +1,216 @@
##########################################################################################
# #
# OpenSpace #
# #
# Copyright (c) 2014-2017 #
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy of this #
# software and associated documentation files (the "Software"), to deal in the Software #
# without restriction, including without limitation the rights to use, copy, modify, #
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to #
# permit persons to whom the Software is furnished to do so, subject to the following #
# conditions: #
# #
# The above copyright notice and this permission notice shall be included in all copies #
# or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, #
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A #
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT #
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF #
# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE #
# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #
##########################################################################################
include(${OPENSPACE_CMAKE_EXT_DIR}/module_definition.cmake)
set(WEBBROWSER_MODULE_NAME WebBrowser)
set(WEBBROWSER_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR} CACHE INTERNAL "WEBBROWSER_MODULE_PATH")
# wanted by CEF
set(PROJECT_ARCH "x86_64")
set(CMAKE_BUILD_TYPE Debug)
##########################################################################################
# Download CEF
# Copyright (c) 2016 The Chromium Embedded Framework Authors. All rights
# reserved. Use of this source code is governed by a BSD-style license that
# can be found in the LICENSE file.
cmake_minimum_required(VERSION 2.8.12.1)
# Only generate Debug and Release configuration types.
set(CMAKE_CONFIGURATION_TYPES Debug Release)
# Use folders in the resulting project files.
set_property(GLOBAL PROPERTY OS_FOLDERS ON)
# Specify the CEF distribution version.
set(CEF_VERSION "3.3029.1617.gaf831b6")
# Add this project's cmake/ directory to the module path.
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
include(cef_support)
# determine the current build platform
set_current_cef_build_platform()
# Download and extract the CEF binary distribution (executes DownloadCEF.cmake).
DownloadCEF("${CEF_PLATFORM}" "${CEF_VERSION}" "${CMAKE_CURRENT_SOURCE_DIR}/ext/cef")
# Add the CEF binary distribution's cmake/ directory to the module path.
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CEF_ROOT}/cmake")
# Load the CEF configuration (executes FindCEF.cmake).
find_package(CEF REQUIRED)
# Include the libcef_dll_wrapper target (executes libcef_dll/CMakeLists.txt).
add_subdirectory(${CEF_LIBCEF_DLL_WRAPPER_PATH} libcef_dll_wrapper)
##########################################################################################
# Add CEF client files
set(WEBBROWSER_SOURCES
webbrowsermodule.cpp
src/browserclient.cpp
src/eventhandler.cpp
src/webbrowserapp.cpp
src/defaultbrowserlauncher.cpp
)
set(WEBBROWSER_SOURCES_LINUX
)
set(WEBBROWSER_SOURCES_MACOSX
)
set(WEBBROWSER_SOURCES_WINDOWS
OpenSpace.exe.manifest
cef_webgui.rc
resource.h
simple_handler_win.cc
)
APPEND_PLATFORM_SOURCES(WEBBROWSER_SOURCES)
source_group(WebBrowser FILES ${WEBBROWSER_SOURCES})
set(WEBBROWSER_RESOURCES_SOURCES_WINDOWS
)
APPEND_PLATFORM_SOURCES(WEBBROWSER_RESOURCES_SOURCES)
source_group(WebBrowser\\\\res FILES ${WEBBROWSER_RESOURCES_SOURCES})
set(WEBBROWSER_SOURCES
${WEBBROWSER_SOURCES}
${WEBBROWSER_RESOURCES_SOURCES}
)
# CEF helper sources
set(WEBBROWSER_HELPER_SOURCES
src/webbrowserapp.cpp
)
set(WEBBROWSER_HELPER_SOURCES_MACOSX
src/processhelpermac.cpp
)
set(WEBBROWSER_HELPER_SOURCES_WINDOWS
src/processhelperwindows.cpp
)
APPEND_PLATFORM_SOURCES(WEBBROWSER_HELPER_SOURCES)
source_group(WebBrowser\\\\helper FILES ${WEBBROWSER_HELPER_SOURCES})
set(WEBBROWSER_RESOURCES_MAC_SOURCES_MACOSX
mac/Info.plist
mac/webgui.icns
)
APPEND_PLATFORM_SOURCES(WEBBROWSER_RESOURCES_MAC_SOURCES)
source_group(WebBrowser\\\\mac FILES ${WEBBROWSER_RESOURCES_MAC_SOURCES})
set(WEBBROWSER_RESOURCES_MAC_ENGLISH_LPROJ_SRCS_MACOSX
mac/English.lproj/InfoPlist.strings
mac/English.lproj/MainMenu.xib
)
APPEND_PLATFORM_SOURCES(WEBBROWSER_RESOURCES_MAC_ENGLISH_LPROJ_SRCS)
source_group(WebBrowser\\\\mac\\\\English.lproj FILES ${WEBBROWSER_RESOURCES_MAC_ENGLISH_LPROJ_SRCS})
set(WEBBROWSER_RESOURCES_SRCS
${WEBBROWSER_RESOURCES_MAC_SOURCES}
${WEBBROWSER_RESOURCES_MAC_ENGLISH_LPROJ_SRCS}
)
# place helper in separate executable
set(CEF_HELPER_TARGET "openspace_web_helper" CACHE INTERNAL "CEF_HELPER_TARGET")
#
# CEF platform-specific config
#
if(OS_MACOSX)
# set global CEF helper app target
set(CEF_HELPER_APP "${CEF_TARGET_OUT_DIR}/${CEF_HELPER_TARGET}.app" CACHE INTERNAL "CEF_HELPER_APP")
# Helper executable target.
add_executable(${CEF_HELPER_TARGET} MACOSX_BUNDLE ${WEBBROWSER_HELPER_SOURCES})
SET_EXECUTABLE_TARGET_PROPERTIES(${CEF_HELPER_TARGET})
ADD_CEF_LOGICAL_TARGET("libcef_lib" "${CEF_LIB_DEBUG}" "${CEF_LIB_RELEASE}")
add_dependencies(${CEF_HELPER_TARGET} libcef_dll_wrapper)
target_link_libraries(${CEF_HELPER_TARGET} libcef_lib libcef_dll_wrapper ${CEF_STANDARD_LIBS})
set_target_properties(${CEF_HELPER_TARGET} PROPERTIES
MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/mac/helper-Info.plist
)
# Fix the framework rpath in the helper executable.
FIX_MACOSX_HELPER_FRAMEWORK_RPATH(${CEF_HELPER_TARGET})
endif()
if (OS_WINDOWS)
message(STATUS "Setting up WebBrowser CEF helper executable: ${CEF_HELPER_TARGET}")
SET_OPENSPACE_CEF_TARGET_OUT_DIR()
add_executable(${CEF_HELPER_TARGET} ${WEBBROWSER_HELPER_SOURCES})
SET_EXECUTABLE_TARGET_PROPERTIES(${CEF_HELPER_TARGET})
add_dependencies(${CEF_HELPER_TARGET} libcef_dll_wrapper)
# Logical target used to link the libcef library.
ADD_CEF_LOGICAL_TARGET("libcef_lib" "${CEF_LIB_DEBUG}" "${CEF_LIB_RELEASE}")
target_link_libraries(${CEF_HELPER_TARGET} libcef_lib libcef_dll_wrapper ${CEF_STANDARD_LIBS})
# Add the custom manifest files to the executable.
ADD_WINDOWS_CEF_MANIFEST("${CEF_TARGET_OUT_DIR}" "${WEBBROWSER_MODULE_PATH}" "${CEF_HELPER_TARGET}" "exe")
endif (OS_WINDOWS)
##########################################################################################
# Create OpenSpace module.
set(OPENSPACE_HEADER_FILES
webbrowsermodule.h
include/webrenderhandler.h
include/browserclient.h
include/screenspacerenderhandler.h
include/screenspacebrowser.h
include/browserinstance.h
include/eventhandler.h
include/webbrowserapp.h
include/defaultbrowserlauncher.h
include/cefhost.h
)
source_group("Header Files" FILES ${OPENSPACE_HEADER_FILES})
set(OPENSPACE_SOURCE_FILES
webbrowsermodule.cpp
src/webrenderhandler.cpp
src/browserclient.cpp
src/screenspacerenderhandler.cpp
src/screenspacebrowser.cpp
src/browserinstance.cpp
src/eventhandler.cpp
src/webbrowserapp.cpp
src/defaultbrowserlauncher.cpp
src/cefhost.cpp
)
source_group("Source Files" FILES ${OPENSPACE_SOURCE_FILES})
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
create_new_module(
${WEBBROWSER_MODULE_NAME}
webbrowser_module
${OPENSPACE_HEADER_FILES} ${OPENSPACE_SOURCE_FILES}
)
# Display CEF configuration settings.
PRINT_CEF_CONFIG()
target_include_directories(${webbrowser_module} PUBLIC ${CEF_ROOT})
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<!--The compatibility section will be merged from build/win/compatibility.manifest -->
<dependency>
<dependentAssembly>
<assemblyIdentity type="Win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"></assemblyIdentity>
</dependentAssembly>
</dependency>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="asInvoker" />
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
+79
View File
@@ -0,0 +1,79 @@
// Microsoft Visual C++ generated resource script.
//
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#define APSTUDIO_HIDDEN_SYMBOLS
#include "windows.h"
#undef APSTUDIO_HIDDEN_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (U.S.) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
#endif //_WIN32
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDI_CEFSIMPLE ICON "res\cefsimple.ico"
IDI_SMALL ICON "res\small.ico"
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE
BEGIN
"#define APSTUDIO_HIDDEN_SYMBOLS\r\n"
"#include ""windows.h""\r\n"
"#undef APSTUDIO_HIDDEN_SYMBOLS\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
#endif // English (U.S.) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED
+135
View File
@@ -0,0 +1,135 @@
#########################################################################################
# #
# OpenSpace #
# #
# Copyright (c) 2014-2017 #
# #
# 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. #
#########################################################################################
# This file consists of snippets taken from various CEF projects.
# Copyright (c) 2016 The Chromium Embedded Framework Authors. All rights
# reserved. Use of this source code is governed by a BSD-style license that
# can be found in the LICENSE file.
# Sets |CEF_PLATFORM| of parent (caller) scope. Determines the current build
# platform.
function(set_current_cef_build_platform)
if("${CMAKE_SYSTEM_NAME}" STREQUAL "Darwin")
set(CEF_PLATFORM "macosx64" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
if(CMAKE_SIZEOF_VOID_P MATCHES 8)
set(CEF_PLATFORM "linux64" PARENT_SCOPE)
else()
set(CEF_PLATFORM "linux32" PARENT_SCOPE)
endif()
elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "Windows")
if(CMAKE_SIZEOF_VOID_P MATCHES 8)
set(CEF_PLATFORM "windows64" PARENT_SCOPE)
else()
set(CEF_PLATFORM "windows32" PARENT_SCOPE)
endif()
endif()
endfunction()
# Download the CEF binary distribution for |platform| and |version| to
# |download_dir|. The |CEF_ROOT| variable will be set in global scope pointing
# to the extracted location.
# Visit http://opensource.spotify.com/cefbuilds/index.html for the list of
# supported platforms and versions.
function(DownloadCEF platform version download_dir)
# Specify the binary distribution type and download directory.
set(CEF_DISTRIBUTION "cef_binary_${version}_${platform}")
set(CEF_DOWNLOAD_DIR "${download_dir}")
# The location where we expect the extracted binary distribution.
set(CEF_ROOT "${CEF_DOWNLOAD_DIR}/${CEF_DISTRIBUTION}" CACHE INTERNAL "CEF_ROOT")
# Download and/or extract the binary distribution if necessary.
if(NOT IS_DIRECTORY "${CEF_ROOT}")
set(CEF_DOWNLOAD_FILENAME "${CEF_DISTRIBUTION}.tar.bz2")
set(CEF_DOWNLOAD_PATH "${CEF_DOWNLOAD_DIR}/${CEF_DOWNLOAD_FILENAME}")
if(NOT EXISTS "${CEF_DOWNLOAD_PATH}")
set(CEF_DOWNLOAD_URL "http://opensource.spotify.com/cefbuilds/${CEF_DOWNLOAD_FILENAME}")
# Download the SHA1 hash for the binary distribution.
message(STATUS "Downloading CEF: ${CEF_DOWNLOAD_PATH}.sha1...")
file(DOWNLOAD "${CEF_DOWNLOAD_URL}.sha1" "${CEF_DOWNLOAD_PATH}.sha1")
file(READ "${CEF_DOWNLOAD_PATH}.sha1" CEF_SHA1)
# Download the binary distribution and verify the hash.
message(STATUS "Downloading CEF: ${CEF_DOWNLOAD_PATH}...")
file(
DOWNLOAD "${CEF_DOWNLOAD_URL}" "${CEF_DOWNLOAD_PATH}"
EXPECTED_HASH SHA1=${CEF_SHA1}
SHOW_PROGRESS
)
endif()
# Extract the binary distribution.
message(STATUS "Extracting CEF: ${CEF_DOWNLOAD_PATH}...")
execute_process(
COMMAND ${CMAKE_COMMAND} -E tar xzf "${CEF_DOWNLOAD_DIR}/${CEF_DOWNLOAD_FILENAME}"
WORKING_DIRECTORY ${CEF_DOWNLOAD_DIR}
)
endif()
endfunction()
macro(SET_OPENSPACE_CEF_TARGET_OUT_DIR)
if(${CMAKE_GENERATOR} STREQUAL "Ninja" OR
${CMAKE_GENERATOR} STREQUAL "Unix Makefiles")
# By default Ninja and Make builds don't create a subdirectory named after
# the configuration.
# set(CEF_TARGET_OUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_BUILD_TYPE}")
set(CEF_TARGET_OUT_DIR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${CMAKE_BUILD_TYPE}")
# Output binaries (executables, libraries) to the correct directory.
# set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CEF_TARGET_OUT_DIR})
# set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CEF_TARGET_OUT_DIR})
else()
# set(CEF_TARGET_OUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIGURATION>")
set(CEF_TARGET_OUT_DIR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/$<CONFIGURATION>")
endif()
endmacro()
macro(ADD_WINDOWS_CEF_MANIFEST target_dir manifest_path target extension)
add_custom_command(
TARGET ${target}
POST_BUILD
COMMAND "mt.exe" -nologo
-manifest \"${manifest_path}/${target}.${extension}.manifest\" \"${manifest_path}/compatibility.manifest\"
-outputresource:"${target_dir}/${target}.${extension}"\;\#1
COMMENT "Adding manifest..."
)
endmacro()
# Add a logical target that can be used to link the specified libraries into an
# executable target.
macro(ADD_CEF_LOGICAL_TARGET target debug_lib release_lib)
add_library(${target} ${CEF_LIBTYPE} IMPORTED GLOBAL)
set_target_properties(${target} PROPERTIES
IMPORTED_LOCATION "${release_lib}"
IMPORTED_LOCATION_DEBUG "${debug_lib}"
IMPORTED_LOCATION_RELEASE "${release_lib}"
)
endmacro()
@@ -0,0 +1,133 @@
#########################################################################################
# #
# OpenSpace #
# #
# Copyright (c) 2014-2017 #
# #
# 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. #
#########################################################################################
function(set_cef_targets cef_root main_target)
# find cef cmake helpers
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${cef_root}/cmake")
include(cef_support)
find_package(CEF REQUIRED)
# ensure out target dir is set
SET_OPENSPACE_CEF_TARGET_OUT_DIR()
# main CEF executable target
set(CEF_TARGET ${main_target} PARENT_SCOPE)
endfunction()
function(run_cef_platform_config cef_root cef_target module_path)
# find cef cmake helpers
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${cef_root}/cmake")
include(cef_support)
find_package(CEF REQUIRED)
if (OS_MACOSX)
run_cef_macosx_config("${cef_target}" "${module_path}")
endif()
if (OS_WINDOWS)
run_cef_windows_config("${cef_target}" "${cef_root}" "${module_path}")
endif()
if (OS_LINUX)
run_cef_linux_config("${cef_target}")
endif()
endfunction()
function(run_cef_macosx_config CEF_ROOT module_path)
set(CEF_APP "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${CEF_TARGET}.app")
set(CEF_FINAL_APP "${CEF_TARGET_OUT_DIR}/${CEF_TARGET}.app")
set(CEF_FINAL_HELPER_APP "${CEF_FINAL_APP}/Contents/Frameworks/${CEF_HELPER_TARGET}.app")
set(CEF_FRAMEWORK_LOCATION "${CEF_BINARY_DIR}/Chromium Embedded Framework.framework")
set(CEF_FRAMEWORK_FINAL_LOCATION "${CEF_FINAL_APP}/Contents/Frameworks/Chromium Embedded Framework.framework")
add_dependencies(${CEF_TARGET} libcef_dll_wrapper "${CEF_HELPER_TARGET}")
target_link_libraries(${CEF_TARGET} libcef_lib libcef_dll_wrapper ${CEF_STANDARD_LIBS})
set_target_properties(${CEF_TARGET} PROPERTIES
RESOURCE "${WEBBROWSER_RESOURCES_SRCS}"
MACOSX_BUNDLE_INFO_PLIST ${module_path}/mac/Info.plist
)
# Copy files into the main app bundle.
add_custom_command(
TARGET ${CEF_TARGET}
POST_BUILD
# Copy the built app bundle into the proper cmake build type directory.
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CEF_APP}" "${CEF_FINAL_APP}"
# Copy the helper app bundle into the Frameworks directory.
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CEF_HELPER_APP}" "${CEF_FINAL_HELPER_APP}"
# Copy the CEF framework into the Frameworks directory.
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_FRAMEWORK_LOCATION}" "${CEF_FRAMEWORK_FINAL_LOCATION}"
VERBATIM
)
# copy dynamic libraries to bundle
file(GLOB LIBRARIES_TO_COPY "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/*.dylib")
foreach (lib_file ${LIBRARIES_TO_COPY})
get_filename_component(file_name "${lib_file}" NAME)
add_custom_command(
TARGET ${CEF_TARGET} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
"${lib_file}"
"${CEF_FINAL_APP}/Contents/${file_name}"
)
endforeach ()
# Fix the framework rpath in the main executable.
FIX_MACOSX_MAIN_FRAMEWORK_RPATH(${CEF_TARGET})
if(NOT ${CMAKE_GENERATOR} STREQUAL "Xcode")
# Manually process and copy over resource files.
# The Xcode generator handles this via the set_target_properties RESOURCE directive.
set(PREFIXES "mac/") # Remove these prefixes from input file paths.
COPY_MACOSX_RESOURCES("${WEBBROWSER_RESOURCES_SOURCES}" "${PREFIXES}" "${CEF_TARGET}" "${module_path}" "${CEF_FINAL_APP}")
endif()
endfunction()
function(run_cef_windows_config CEF_TARGET CEF_ROOT MODULE_PATH)
# Executable target.
add_dependencies(${CEF_TARGET} libcef_dll_wrapper)
target_link_libraries(${CEF_TARGET} libcef_lib libcef_dll_wrapper ${CEF_STANDARD_LIBS})
include_directories(${CEF_ROOT})
add_dependencies(${CEF_TARGET} libcef_dll_wrapper "${CEF_HELPER_TARGET}")
if(USE_SANDBOX)
# Logical target used to link the cef_sandbox library.
message(STATUS "Using CEF in Sandboxed mode.")
ADD_LOGICAL_TARGET("cef_sandbox_lib" "${CEF_SANDBOX_LIB_DEBUG}" "${CEF_SANDBOX_LIB_RELEASE}")
target_link_libraries(${CEF_TARGET} cef_sandbox_lib ${CEF_SANDBOX_STANDARD_LIBS})
endif()
# Add the custom manifest files to the executable.
SET_OPENSPACE_CEF_TARGET_OUT_DIR()
ADD_WINDOWS_CEF_MANIFEST("${CEF_TARGET_OUT_DIR}" "${MODULE_PATH}" "${CEF_TARGET}" "exe")
# Copy binary and resource files to the target output directory.
copy_files("${CEF_TARGET}" "${CEF_BINARY_FILES}" "${CEF_BINARY_DIR}" "$<TARGET_FILE_DIR:${CEF_TARGET}>")
copy_files("${CEF_TARGET}" "${CEF_RESOURCE_FILES}" "${CEF_RESOURCE_DIR}" "$<TARGET_FILE_DIR:${CEF_TARGET}>")
endfunction()
function(run_cef_linux_config CEF_ROOT)
message(ERROR "Linux is not yet supported for Web Browser Module.")
endfunction()
+11
View File
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- Windows 10 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
<!-- Windows 8.1 -->
<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
</application>
</compatibility>
</assembly>
+1
View File
@@ -0,0 +1 @@
set(DEFAULT_MODULE OFF)

Some files were not shown because too many files have changed in this diff Show More